Get started with Microsoft Access 2000

There are different ways you can get started with Microsoft Access 2000, depending on your background.

What best describes your experience?

Upgrading from previous versions of Microsoft Access

Familiar with other database or spreadsheet applications

Using a database for the first time


What's new about the Database window

The Database window in Microsoft Access 2000 provides a variety of options for viewing and manipulating database objects.

  • Use the Database window toolbar Quickly find commands for creating, opening, or managing database objects.

  • Use the Objects bar View database objects in the Objects bar — its vertical orientation makes it easier to use.

  • Organize database objects into groups Click the Groups bar to view your groups, which can contain shortcuts to database objects of different types.

  • Use new object shortcuts In the Database window, quickly create a new database object by using a wizard, or open a new database object in design view.

  • Customize how you select and open objects in the Database window If you choose, change the default behavior so that you select a database object by resting the pointer over it, and open an object by single-clicking it.

  • Select an object by typing its name For example, select the Shippers table while viewing the list of table objects by typing Sh.


 What's new about working with data and database design?

What's new about working with data and database design?

Microsoft Access 2000 provides many new features that make working with data and designing a database even easier.

  • Use record-level locking A Microsoft Access database now supports record-level locking, in addition to page-level locking (which locks all records on a 4K page). You enable the locking level with the new database option, Open databases using record level locking (Tools menu, Options command, Advanced Tab). The actual level that is used depends on how the Access database is programmed.

  • Find and replace You can now move freely between the Find and Replace dialog boxes and the data in the view or window.

  • View related data in a subdatasheet Use a subdatasheet to view and edit related or joined data in a table, query, or form datasheet, or in a subform all from the same view. For example, in the Northwind sample database the Suppliers table has a one-to-many relationship with the Products table; so for each row of the Suppliers table in Datasheet view, you can view and edit the related rows of the Products table in a subdatasheet.

  • Automatically fix errors caused by renaming fields Name AutoCorrect automatically corrects common side effects that occur when you rename forms, reports, tables, queries, fields, text boxes or other controls.

  • Take advantage of Unicode support Use the characters of any language that Unicode supports in your data. Use Unicode compression to offset the effect of Unicode's increased storage space requirements. Take advantage of dual-font support — specify a substitute font that you can use in addition to your default font to properly display all of the characters in your data.

  • Work with the euro To easily display euro amounts with other currencies, you can use the euro setting ( [image] #,###.##) of the Format property to indicate a euro amount. Alternatively, you can enter the euro symbol ( [image]) by pressing ALT+0128 on the numeric keypad with NUM LOCK on. When you paste or import data that contains the euro symbol ( [image]) from Microsoft Excel 2000 into Microsoft Access, Access stores the euro symbol regardless of the currency symbol defined in Regional Settings in Windows Control Panel. Finally, you can use the EuroConvert function to convert one currency to another by using the euro as an intermediary. More about working with the euro.

  • Print relationships Print a report of the relationships in your Access database as they appear in the Relationships window.

  • Use the keyboard to manage relationships Use the keyboard to create, edit, and delete relationships and joins.

  • Use Microsoft ActiveX Data Objects (ADO) Use Microsoft ActiveX Data Objects (ADO) to access and manipulate data in a database server through any OLE DB provider.


What's new about forms and reports

Microsoft Access 2000 provides new features to make it faster and easier to create great-looking forms and reports.

  • Group text boxes and other controls Use the Group command on the Format menu to group related text boxes and other controls on a form or report.

  • Define conditional formatting rules for text boxes and other controls Use the Conditional Formatting command on the Format menu to define the font color, font size, control background color, and other visual information that gives feedback to users as they enter data on a form.

  • Create forms and reports for SQL Server databases In a Microsoft Access project, create forms and reports for an SQL Server database with the same tools that you use to create them in a Microsoft Access database.

  • Distribute reports to users who don't have Microsoft Access Export Microsoft Access reports to report snapshot (.snp) file format. You can use Snapshot Viewer to view, print, and mail report snapshots.


What's new about data access pages

A data access page is a Web page that you can use to add, edit, view, or manipulate current data in a Microsoft Access database or an SQL Server database. You can create pages that are used to enter and edit data, similar to Access forms. You can also create pages that display records grouped hierarchically, similar to Access reports.

  • Collect and distribute current data in several ways You can use pages to add, edit, and view data within a Microsoft Access database or Microsoft Access project; you can use them on the Internet or on an intranet, and you can send them in e-mail.

  • View grouped records interactively On grouped pages, you can view just the details you want by expanding and collapsing group headers. You can also sort and filter records.

  • Analyze data and make projections You can organize data in different ways using a PivotTable list, make projections and do complex calculations using a spreadsheet control, and view data graphically in a chart.

  • Display HTML text You can store HTML code in fields in your database and display it as formatted HTML text on the page. For example, if a value in a field includes the HTML tag that formats text as italic, <I>Text</I>, you can use a bound HTML control on the page to display the value in italic text.

  • Use familiar design tools In Design view, create pages using toolbars, the toolbox, themes, and other features that are similar to the tools you use to create forms and reports.


What's new with toolbars, menu bars, and shortcut menus?

With the toolbars, menu bars, and shortcut menus that are in Microsoft Access 2000, you can organize commands the way you want so that you can find and use them quickly.

  • Use personalized menus and toolbars Expand a menu to display all commands, and choose a command to add it to a personalized menu. Access 2000 adjusts menus and toolbars as you work so that only the commands and toolbar buttons you use most often appear.

  • Position toolbars next to each other Click More Buttons if there is not enough room on the toolbar for a button that you are looking for. Resize the toolbar if you'd like room for more buttons. After you've clicked a button, it appears on the toolbar with the buttons that you've used most recently.

  • Assign a hyperlink to a toolbar button or menu command Assign a hyperlink to a toolbar button or menu command for easy access to a location on your computer, a network, an intranet or the Internet.


What's new about securing, maintaining, and converting a database

  • Secure your Access database with the User-level Security Wizard The User-level Security Wizard is now much easier to use and is the preferred method for defining user-level security on a Microsoft Access database for most common security schemes.

  • Protect your code with Visual Basic for Applications password protection Modules and modules behind forms and reports are now protected by a Visual Basic Applications (VBA) password that you create in the Visual Basic Editor; they are no longer protected by user-level security.

  • Use the improved Compact utility Compact Microsoft Access databases and Microsoft Access projects with an improved utility that combines compacting and repairing into a single process, and is safer and more effective.

  • Compact automatically Select Compact On Close to automatically compact a Microsoft Access database or Microsoft Access project when you close it.

  • Convert a database to Microsoft Access 97 Convert an Access 2000 database to Access 97 file format.


 What's new about working on the Internet

What's new about working on the Internet

Microsoft Access provides new features designed to help you easily use the Internet. You need a Web browser, such as Microsoft Internet Explorer, and a modem, intranet connection, or other network connection to access the Internet and take advantage of some of these new features.

  • Create data access pages Create Web pages that you can use to add, edit, view, or manipulate current data in a Microsoft Access database or a Microsoft SQL Server database.

  • Collaborate over an intranet or the Internet Use NetMeeting to collaborate with others on a Microsoft Access database or Microsoft Access project.

  • Assign a hyperlink to a toolbar button or menu command Assign a hyperlink to a toolbar button or menu command for easy access to a location on your computer, a network, an intranet, or the Internet.


 What's new about working with other applications?

What's new about working with other applications?

Microsoft Access 2000 provides new features for working with other products.

  • Work with Microsoft SQL Server Create a Microsoft Access project that is easy to connect to a Microsoft SQL Server database, or use the Microsoft SQL Server Database Wizard to quickly create a SQL Server database and an Access project at the same time. Working with an Access project is similar to working with a Microsoft Access database — the process of creating forms, reports, data access pages, macros, and modules is the same. Once you connect to a SQL Server database, you can view, create, modify, and delete tables, views, stored procedures, and database diagrams using the Microsoft SQL Server Design Tools.

  • Create a new Access database from data in another file format Just open a file that is in another file format — such as text, dBASE, Paradox, or spreadsheet format — in Access; Microsoft Access automatically creates an Access database and links the file for you.

  • Import or link data from Microsoft Outlook or Microsoft Exchange Use the Exchange/Outlook Wizard to import or link data from Microsoft Outlook and Microsoft Exchange Server. For example, you might want to link to your Microsoft Outlook Contacts folder and then create form letters and mailing labels by merging the data with the Microsoft Word Mail Merge Wizard.


 What's installed with Microsoft Access 2000

What's installed with Microsoft Access 2000

This topic provides reference information about which features are installed with Microsoft Access 2000 and where you can find these features in the installation program. These features are also installed by the Office 2000 installation program; they include Microsoft Access features as well as Office Tools, Converters, and Filters.

Installed (default)

Installed on first use (default)

Not installed (custom installation only)

Notes about features

Other programs in Microsoft Office 2000

Installed (default)

Feature | Location in the installation program
Clip Gallery | Office Tools; Clip Art
Core Support Files, International Support | Office Tools; International Support
Encapsulated Postscript | Converters and Filters; Graphic Filters
Find Fast Control Panel | Office Tools
GIF (Graphic Interchange Format) | Converters and Filters; Graphic Filters
Help for Microsoft Access | Microsoft Access for Windows
Help for Microsoft Graph | Office Tools; Microsoft Graph
JPEG Interchange Format | Converters and Filters; Graphic Filters
Language Settings Tool | Office Tools
Macintosh PICT Import | Converters and Filters; Graphic Filters
Microsoft Access Program Files | Microsoft Access for Windows
Microsoft Graph | Office Tools
Microsoft Office Shortcut Bar | Office Tools
MS Info | Office Tools
Office Assistant (one Assistant) | Office Tools; Office Assistant
Office Web Components | Office Tools
Spelling Checker | Office Tools; Proofing Tools
Tag Image File Format Import | Converters and Filters; Graphic Filters
Typical Themes | Office Tools; Themes
Typical Wizards For a list of wizards, click [image] . | Microsoft Access for Windows
Web Discussions | Office Tools
Web Publishing | Office Tools
Windows Metafile Import | Converters and Filters; Graphic Filters

Return to top

Installed on first use (default)

Feature | Location in the installation program
Additional Themes | Office Tools; Themes
Additional Wizards For a list of wizards, click [image] . | Microsoft Access for Windows
Address Application | Microsoft Access for Windows; Sample Databases
Bidirectional Support | Office Tools; International Support
Client Server Visual Design Tools | Microsoft Access for Windows
Computer Graphics Metafile Import | Converters and Filters; Graphic Filters
Contact Application | Microsoft Access for Windows; Sample Databases
CorelDRAW Import | Converters and Filters; Graphic Filters
Database Replication | Microsoft Access for Windows
Digital Signature for VBA projects | Office Tools
Enhanced Metafile Import | Converters and Filters; Graphic Filters
FPX Import | Converters and Filters; Graphic Filters
Household Inventory | Microsoft Access for Windows; Sample Databases
Japanese Fonts | Office Tools; International Support
Kodak Photo CD Import | Converters and Filters; Graphic Filters
Korean Fonts | Office Tools; International Support
Microsoft Query | Office Tools
Northwind Database | Microsoft Access for Windows; Sample Databases
Office Assistant (seven additional Assistants) | Office Tools; Office Assistant
Organization Chart | Office Tools
PC Paintbrush PCX Import | Converters and Filters; Graphic Filters
PNG File Format Import | Converters and Filters; Graphic Filters
Scanner and Camera Add-In | Office Tools
Simplified Chinese Fonts | Office Tools; International Support
Snapshot Viewer | Microsoft Access for Windows
Traditional Chinese Fonts | Office Tools; International Support
Visual Basic Help | Office Tools
Web Scripting (Microsoft Script Editor) | Office Tools; HTML Source Editing
Windows Bitmap Import | Converters and Filters; Graphic Filters
WordPerfect Graphics Filters | Converters and Filters; Graphic Filters

Return to top

Not installed (custom installation only)

Feature | Location in the installation program
Calendar Control | Microsoft Access for Windows
Equation Editor | Office Tools
Extended Support Files, International Support | Office Tools; International Support
Lotus VIM Mail Support | Office Tools
Microsoft Photo Editor | Office Tools
Northwind SQL Project File | Microsoft Access for Windows; Sample Databases
Universal Font | Office Tools; International Support

Note The Calendar Control and the Northwind SQL Project File are not advertised in the user interface of Microsoft Access; you must run the Microsoft Office 2000 Setup program or Microsoft Access 2000 Setup program to install these features.

Return to top

Notes about features

After you have installed Microsoft Access 2000 or Microsoft Office 2000, the sample databases appear on the most recently used file list on the File menu, and on the list under Open An Existing File in the dialog box when you start Microsoft Access for the first time. However, as you begin to use your own files with Microsoft Access, the databases may no longer appear on these lists. Use the Microsoft Office 2000 Setup program or Microsoft Access 2000 Setup program to install one of the sample applications on your computer.

The Microsoft Access 2000 Setup program also installs Text Converters and additional Proofing Tools; most of these components are installed on first use and therefore do not consume a large amount of disk space. Although you can use these components with other Microsoft Office 2000 applications such as Microsoft Word and Microsoft Excel, they are not designed to be used directly with Microsoft Access.

If you do not use a custom installation, the Microsoft Office 2000 and Microsoft Access 2000 Setup programs install Microsoft Internet Explorer 5. If you use a custom installation, you can choose not to install Microsoft Internet Explorer. However, you must install Microsoft Internet Explorer 5 if you want to use data access pages in Microsoft Access.

Return to top

Other programs in Microsoft Office 2000

Program and location in the Custom dialog box of Setup | Installed with Typical Setup?
Microsoft Excel for Windows | Yes
Microsoft Word for Windows | Yes
Microsoft PowerPoint for Windows | Yes
Microsoft Outlook for Windows | Yes

Note A typical setup of Microsoft Office 2000 Premium also installs Microsoft FrontPage for Windows.

Return to top


 What's new with sample applications

What's new with sample applications

The sample applications that you can install with Microsoft Access provide documented examples that show you how to create and customize full-featured Microsoft Access databases.

Northwind Traders The Northwind sample application is designed for users new to Microsoft Access databases. Northwind includes data that you can manipulate, and forms, reports, data access pages, and other database objects you can use as models in your own databases.

NorthwindCS The NorthwindCS sample application includes an SQL script that creates the Northwind database in Microsoft SQL Server, and a Microsoft Access project that you connect to the Northwind database. The Access project includes forms, reports, data access pages, and other database objects you can use as models in your own Access projects.

Address Book Use the Address Book database to save address and phone information for every member of a family, print address labels, or remind yourself when it's time to send birthday cards. You can also export your address list to Microsoft Word.

Contact Management Use the Contact Manager database to save information on all of your contacts, keep records of calls, send electronic mail, set reminders, and print labels. You can also export your contact list to Microsoft Word.

Household Inventory Use the Household Inventory database to save information about important possessions, keep a permanent record of serial numbers, purchase and replacement information, and list items donated to charity. You can also import and export information from other applications.


 Microsoft Office 2000 Developer contents

Microsoft Office 2000 Developer contents

Microsoft Office 2000 Developer provides advanced tools that developers can use to create and distribute custom applications.

The Office 2000 Developer includes the following:

Microsoft Office Premium CD-ROM

Office Developer Tools CD-ROM

  • A royalty-free distribution license (including the Microsoft Graph run-time application) and tools that allows you to distribute copies of your custom Microsoft Access applications to all your users, whether or not they have Access installed on their computers.

  • Replication Manager, which schedules updates among replicas, determines which objects in the database are replicated, and manages multiple replica sets at one time. By using Replication Manager, you can see a visual display of all the replicas in a set.

  • Microsoft Visual SourceSafe 6.0 (including the Visual SourceSafe Add-in for Access and the Visual SourceSafe Visual Basic Editor Add-in), which supports multideveloper application development.

  • ActiveX controls that you can use to add versatility to your applications and duplicate Microsoft Windows 95 functionality, including controls for Internet applications and controls to connect Microsoft Outlook messaging with data and other Office applications.

  • Updated Windows API Viewer with enhanced performance. The Windows API Viewer contains declarations and constants used with the Windows 95 application programming interface (API). You can copy and paste these declarations and constants into your Visual Basic modules.

  • The Data Environment, a user interface for easily connecting solutions to external databases.

  • The Make Add-in feature, which you can use to create an add-in directly from the Visual Basic Editor for a specific Visual Basic Editor host.

  • The Package and Deploy Wizard, which you can use to deliver Office programmable solutions for any Visual Basic for Applications 6.0 host to disk, network, and the Web.

  • The Code Librarian, a tool for browsing existing source files for code snippets. You can search text, view descriptions and comment headers, and insert the text into your current project.

  • The HTML Help Workshop Software Development Kit (SDK), with which you can create Help topics similar to those in Microsoft Office 2000. The SDK includes the HTML Help Workshop and the run-time version to distribute to your users.

  • The Agent SDK, which provides programmatic control over Office Assistants you create.

  • Microsoft Office WebBot Components, with which you create applets embedded inside Office 2000 documents. With the user interface these applets provide, users don't need to author script and Visual Basic for Applications code to take advantage of DHTML features. WebBots are written in Microsoft Script Editor.

  • Microsoft Developer Network (MSDN), Office 2000 edition. The entire MSDN library is included, as well as a special default subset of Office and Visual Basic for Applications programming commands .

Printed Documentation

  • Microsoft Office 2000/Visual Basic Programmer’s Guide

  • Object Model Guide


Handling dates in the year 2000 and beyond

What do you want to do?

Learn how Microsoft Access handles dates in the Year 2000 and beyond

Learn about the Microsoft Year 2000 Resource Center Web site


How Microsoft Access handles dates in the year 2000 and beyond

Because the rules that govern the way any calculation program interprets dates are complex, you should be as specific as possible about dates whenever you enter them. This will produce the highest level of accuracy when Access 2000 processes dates.

How Access interprets ambiguous dates When interpreting ambiguous dates, Access makes certain assumptions. For example, when you enter a date that includes only the month and one or two digits, Access assumes that 1 through 31 is the day and that the year is the current year. For example, Access assumes that December 01 is December 1 of the current year, not December of the year 2001. Access assumes that December 32 is December 1, 1932.

How Access interprets two-digit years In datasheets and edit controls, Access interprets dates that are entered with an abbreviated year format to mean the twenty-first century in the following way:

Date range for abbreviated year format | Interpretation
1/1/00 through 12/31/29 | 1/1/2000 through 12/31/2029
1/1/30 through 12/31/99 | 1/1/1930 through 12/31/1999

Use four-digit years To ensure that Access interprets year values the way that you intended, you can type year values as four digits (for example, 2001, rather than 01).

Change how years are interpreted Your system administrator, or the system administrator for your users, can customize Office so that different rules determine how dates are interpreted. For example, your administrator could change the earliest two-digit year value that's interpreted as a date in the twentieth century from 30 to a lower number (see the above table). Also, administrators can change the default date format to display four-digit years instead of two-digit years. For information about how to customize date interpretation, see the Microsoft Year 2000 Resource Center.

Note If you are using Microsoft Windows 2000 Professional or Windows 98, then you can change the century interpretation and the default date format to display to four-digit years without the assistance of your system administrator.


Install or remove individual components

If you can't find the Microsoft Office 2000 or Microsoft Access 2000 component you need and Windows installer doesn't automatically install it, you can install the component yourself. If you originally installed Office 2000 or Access 2000 from a network file server, run that copy of the Setup program.

  1. Quit all programs.

  2. Click the Windows Start button, point to Settings, and then click Control Panel.

  3. Double-click the Add/Remove Programs icon [image].

  4. Do one of the following:

    If you installed Access by using the Office 2000 Setup program, click Microsoft Office 2000 on the Install/Uninstall tab, and then click Add/Remove.

    If you installed Access individually, click Microsoft Access 2000 on the Install/Uninstall tab, and then click Add/Remove.

  5. Follow the instructions on the screen.

    Learn about the location of components in the installer.

Notes

  • If you installed Office or Access from a CD-ROM, and you have mapped your CD-ROM drive to a new drive letter since you originally installed Office or Access, run Setup again from the CD-ROM. If you are running any Office or Access files from the CD-ROM, you must either re-map the CD-ROM drive to the original drive letter, or uninstall and then install Office or Access again from the CD-ROM.

  • If you want Access 2000 and Access 97 to co-exist on your computer, when you install Access 2000, you must choose a folder other than the one you installed Access 97 in; otherwise, Access 97 will be replaced.

  • Microsoft Data Engine (MSDE) is not part of Office or Access Setup, but you can install MSDE from the CD-ROM or network file server by running Setupsql.exe, which is located in the \Sql\x86\Setup folder. Learn about using MSDE.

  • If you want to re-install Microsoft Internet Explorer 5 or upgrade to it, you can install it from the CD-ROM or network file server by running Ie5setup.exe, which is located in the \Ie5 folder.


Automatically repair Office, or an Office program

  • On the Help menu, click Detect and Repair.

    To restore the program shortcuts to the Windows Start menu, make sure the Restore my shortcuts while repairing check box is selected.

Notes

  • This procedure detects and repairs problems associated with all installed Office programs, such as missing files from setup, and registry settings. It will not repair personal files, such as spreadsheets or documents.

  • If the Detect and Repair command does not fix the problem, you may need to reinstall Office using the Windows Installer.


Convert a database

What do you want to do?

I want to use an existing database with several versions of Microsoft Access

Use an Access database with several versions of Microsoft Access

I want to use an existing database in Microsoft Access 2000 without converting it

Read about opening a previous-version Access database without converting it

Open a previous-version Access database in Microsoft Access 2000 without converting it

I want to convert an existing database to Microsoft Access 2000

Read about converting a previous-version Access database to Microsoft Access 2000

Read about converting a secured Access database

Convert a previous-version Access database to Microsoft Access 2000

Convert a replicated database

I want to convert a Microsoft Access 2000 database to Microsoft Access 97

Convert an Access 2000 database to Microsoft Access 97

I want to read about programming conversion issues

Read about compatibility issues when converting tables, forms, and reports from previous versions of Microsoft Access

Read about compatibility issues when converting macros and Access Basic code from previous versions of Microsoft Access

I want to troubleshoot conversion

Troubleshoot converting a previous-version database to Microsoft Access 2000


 Fix missing references after converting an Access 2000 database to Access 97

Fix missing references after converting an Access 2000 database to Access 97

You can convert code that uses Data Access Objects (DAO) back to Microsoft Access 97, but you may receive a message that your computer is missing at least one of the Access 97 object libraries. Use this procedure to fix the missing references.

  1. Convert the Microsoft Access 2000 database to Microsoft Access 97. When you receive a message that your computer is missing at least one of the Access 97 object libraries, click OK.

  2. Open the converted Access database in Microsoft Access 97.

  3. Open a module in the database.

  4. On the Tools menu, click References.

  5. In the Available References box, clear the check boxes next to any missing references, and set a reference to the Microsoft DAO 3.51 Object Library.

Note Unlike Access 2000, Access 97 is not designed to work with ActiveX Data Objects (ADO).


 Convert an Access 2000 database to Access 97

Convert an Access 2000 database to Access 97

  1. Open the Microsoft Access database that you want to convert. If it is a multiuser database that is located on a server or in a shared folder, make sure that no one else has it open.

    Important If you have protected the Microsoft Visual Basic for Applications (VBA) code, you must supply the password before you convert the Access database. To supply the password, start Microsoft Visual Basic by opening a module; then click databasename Properties on the Tools menu and enter the password in the databasename Password dialog box..

    If you are converting a secured Access database, you must have Open/Run and Open Exclusive permissions for the database itself, and Read Design permissions for all objects in the database. To secure the converted database, you must open it in Microsoft Access 97 and apply user-level security.

  2. On the Tools menu, point to Database Utilities, click Convert Database, and then click To Prior Access Database Version.

  3. In the Convert Database Into dialog box, type the name of the new previous-version database that you want to create in the File name box, and then click Save.

Note If your Access 2000 database contains code, you may need to fix missing references after you have converted it to Microsoft Access 97. Also, if your Access database uses add-ins or library databases that were created in Access 2000, you must convert them back to Access 97 as well.

Learn more about converting an Access 2000 database to Access 97.


Open the Northwind sample database

  1. Start Microsoft Access.

  2. In the opening dialog box, make sure Open An Existing File is selected.

  3. In the list, click Northwind Sample Database.

  4. If Northwind hasn't already been installed, click Yes to install it now.

Notes

  • If you already have Access open, you can click the Open Database command on the File menu in any window and then navigate to the Northwind sample database. Northwind is usually in the Program Files\Microsoft Office\Office\Samples folder. If you already have another database open, Access closes it when it opens another database.

  • If you don't see the sample database in the opening dialog box or in the Samples folder, you can install Northwind yourself.

  • For information on Northwind, click [image] .

  • Microsoft Access includes three applications that you can use right away to track information on your addresses, contacts, and household inventory. These files are also displayed in the list when Open An Existing File is selected. If you don't see these files in the list, you can install the application files yourself.


Sample databases included with Microsoft Access

See examples and get ideas from the Northwind Traders sample database

Microsoft Access provides a sample database called Northwind Traders for you to use while you're learning Access : The Northwind database contains the sales data for a fictitious company called Northwind Traders, which imports and exports specialty foods from around the world. By viewing the tables, queries, forms, reports, macros, and modules included in the Northwind database, you can develop ideas for your own Access database. You can also use the Northwind data to experiment with Access before you enter your own data. For example, you may want to practice designing queries using the Orders table since it contains enough records to produce meaningful results.

The Northwind database includes a Help file called Show Me that documents the main features in the database.

How to open Northwind.

Note Microsoft Access also includes a Database Wizard that you can use to create common Access databases. You can use the databases created by the Database Wizard as is or as a learning tool to help you design your own databases.

Start tracking your addresses, contacts, and household inventory right away

If you want to start tracking your own information right away, Access also provides the following three database applications:

  • Address Book application Use this application to manage addresses and other information for individuals, families, and companies. With the database, you can save address and phone information for every member of a family, remind yourself when it's time to send birthday cards, print address labels, and export your address list to Microsoft Word.

  • Contact Management application Use this application to manage your personal and business contacts. With this database, you can save information on your personal and business contacts, record the time and subject of phone calls, send e-mail to any contact, set reminders, print labels or envelopes, and export your contact list to Word.

  • Household Inventory application Use this application to keep track of important possessions in your home. With this database, you can record serial numbers and purchase and replacement information; list items donated to charity for tax purposes; and import and export information from other applications.

How to install and open the applications.


Connect to Microsoft technical resources

If you have a question about an Office program, first ask the Office Assistant and then look in the Microsoft Office 2000 Resource Kit or the Readme file that comes with the program. If you don't find what you need, you can get information from the technical resources in the following list.

Where do you want to go for technical information?

Microsoft Office Update A Web site that is updated regularly and provides information and answers to questions about all of the Office products. Learn about the Microsoft Office Update Web site.

Microsoft Knowledge Base Product information for Microsoft support engineers and customers. Learn about the Microsoft Knowledge Base.

Microsoft Software Library This resource provides the download of free binary files on the Internet for all Microsoft products. Learn about the Microsoft Software Library.

Microsoft TechNet and Microsoft Developer Network CD-ROMs CD-ROMs containing comprehensive information for product support of Microsoft business products, and comprehensive programming information and toolkits. Learn about the Microsoft TechNet and Microsoft Developer Network.

Microsoft Press Training and support materials for Microsoft products. Learn about Microsoft Press.

Microsoft Download Service Sample programs, patches, and other programming aids. Learn about the Microsoft Download Service.

FastTips An automated, toll-free service that provides answers to common technical questions 24 hours a day, 7 days a week. Learn about FastTips.


 Glossary

Glossary

A | Return to top
absolute positioning access key action action argument action list action query action row Active Server Pages (ASP) file ActiveX component ActiveX control ActiveX Data Objects (ADO) add-in Admin account Admins group ADO (ActiveX Data Objects) Advanced Filter/Sort window aggregate function alias American National Standards Institute (ANSI) character set | American Standard Code for Information Interchange (ASCII) Analyze button anonymous replica ANSI (American National Standards Institute) character set API (Windows application programming interface) append query application background Application Note argument array ASCII (American Standard Code for Information Interchange) ASP files autoformat automatic link Automation Automation object AutoNumber data type
B | Return to top
bit mask bitmap body Bookmark Boolean bound column bound control bound HTML control bound hyperlink control bound object frame | bound picture break mode breakpoint browser Build button builder Building Applications with Forms and Reports built-in toolbar Byte data type
C | Return to top
calculated control calculated field Call Stack (View menu) call tree caption section cascading delete cascading event cascading update case-sensitive channel number chart check box class class module class name class name (OLE) Clear All Breakpoints (Debug menu) client client/server code stub Code window collection column column selector combo box command bar | command button command line comparison operator compile time component/ActiveX component compound control condition conditional compiler constant conditional expression conditional formatting conflict connection string constant Continue (Run menu) continuous form control control containing a hyperlink Control menu criteria crosstab query Currency data type current record custom dialog box custom properties dialog box custom toolbar
D | Return to top
Data Access Objects (DAO) data access page data access page Design view data access page properties Data Access Page window data definition data item data source control data type database database objects database replication Database window data-definition query datasheet Datasheet view Date/Time data type DDE (dynamic data exchange) DDE channel debugging Decimal data type Declarations section default control style | default property default value Definition (View menu) delete query delimited text file design grid Design Master Design view destination detail section (forms) detail section (reports) DHTML (Dynamic HTML) direct synchronization disabled control DLL (dynamic-link library) docked document properties domain domain aggregate function Double data type drop-down list box dynamic data exchange (DDE) Dynamic HTML (DHTML) dynamic-link library (DLL)
E | Return to top
echo embed (insert) Empty enabled database End (Run menu) event event procedure event property | exclusive expand control expand indicator export expression Expression Builder external database external table
F | Return to top
field field data types field list field selector File Transfer Protocol (FTP) Fill filter Filter By Form Filter By Selection Filter Excluding Selection Filter For Input fixed positioning fixed-width text file floating focus font foreign key | foreign table form form Design view form footer form header form module form properties form selector Form view Form window format Formatting toolbar Formatting toolbar (Page) front-end/back-end application FTP (File Transfer Protocol) Function procedure
G | Return to top
General sort order GIF (Graphics Interchange Format) global menu bar global replica global shortcut menu globally unique identifier (GUID) Graphics Interchange Format (GIF) grid (Datasheet view) grid (Design view) Grid button | group account group filter control group footer group header group level grouped controls grouped data access page Groups bar GUID (globally unique identifier)
H | Return to top
handle history list hotspot image control HTML (Hypertext Markup Language) HTTP (Hypertext Transfer Protocol) HTX files hub | hyperlink hyperlink address hyperlink base Hyperlink data type hyperlink field Hypertext Markup Language (HTML) Hypertext Transfer Protocol (HTTP)
I | Return to top
IDC files identifier (expressions) identifier (Visual Basic) image control IME (Input Method Editor) Immediate window import import/export specification Indent (Edit menu) index Indexes window indirect synchronization | inline positioning inner join in-place activation input mask Input Method Editor (IME) instance Integer data type Internet Internet synchronization intranet intrinsic constant item
J-L | Return to top
Jet and Replication Objects (JRO) join Joint Photographic Experts Group (JPEG) Journal (Outlook Bar) JPEG (Joint Photographic Experts Group) JRO (Jet and Replication Objects) keyboard handler keyword label language folder Layout Preview left outer join library database | Line/Border Width button link (OLE/DDE) link (tables) linked table list box list index literal local object local replica Locals window locked Long data type Lookup field
M | Return to top
macro macro group Macro window main form make-table query manual link many-to-many relationship marquee Memo data type menu menu bar menu bar macro metafile method Microsoft Access database Microsoft Access data file Microsoft Access object Microsoft Access project | Microsoft Data Engine (MSDE) Microsoft Download Service Microsoft Jet database engine Microsoft Knowledge Base Microsoft Network Microsoft Office Web Components Microsoft Script Editor Microsoft Software Library Microsoft Visual Basic Microsoft Visual Basic Scripting Edition (VBScript) modal module module level module-level variable Move mode MSDE (Microsoft Data Engine) multiuser (shared) database My Computer
N-O | Return to top
Name AutoCorrect navigation buttons Navigation mode New Object button normalize Null null field Number data type numeric expression object Object Browser Object data type object library Object list object-naming rules Objects bar ODBC (Open Database Connectivity) ODBC Connection String Builder ODBC data source ODBC database | ODBCDirect Office Links button OLE OLE container OLE DB OLE DB Provider OLE object OLE Object data type OLE server OLE/DDE link one-to-many relationship one-to-one relationship Open Database Connectivity (ODBC) operator option button option group Outdent (Edit menu) outer join Outlook Bar owner
P | Return to top
page (data storage) page (HTML) page footer (forms) page footer (reports) page header (forms) page header (reports) Page view parameter query partial replica pass-through query permissions personal ID (PID) PivotTable form PivotTable list pixel plus pointer point | pop-up form preview primary key primary table Print Preview private procedure procedure Procedure (Insert menu) procedure level procedure-level variable project property property sheet public variable publish
Q | Return to top
query query Design view query parameter data types Query Type button | Query window question-mark pointer Quick Watch (Debug menu)
R | Return to top
record record navigation control record navigation section record navigation toolbar record number box record selector record source recordset referenced database referencing database referential integrity refresh relationship Relationships window relative link relative positioning repaint replica replica set | replication report report Design view report footer report header report module report selector report snapshot Report window requery Reset (Run menu) result set right outer join row selector ruler run time run-time error
S | Return to top
scrolling text control search page section section selector secure workgroup select query selected control selection rectangle self-join separator server server-generated HTML session shared database shortcut key shortcut menu Single data type single stepping sizing handle Snap To Grid snapshot Snapshot Viewer Snapshot Viewer control sort order Sorting And Grouping box (data access pages) Sorting And Grouping box (reports) Special Effect button spreadsheet SQL (Structured Query Language) | SQL database SQL string/statement SQL view SQL-specific query standard module start page statement status bar Step Into (Debug menu) Step Out (Debug menu) Step Over (Debug menu) stored procedure string string comparison String data type string delimiter string expression Structured Query Language (SQL) Sub procedure subdatasheet subform subform/subreport control submenu subquery subreport synchronization syntax error system object
T | Return to top
tab control tab order table table Design view table properties Table window text box Text data type text query (Microsoft Knowledge Base) theme title bar | Toggle Breakpoint (Debug menu) toggle button toolbar toolbox ToolTips topic topology totals query transaction twip type library
U-V | Return to top
unbound control unbound form or report unbound object frame UNC (Universal Naming Convention) Unicode Uniform Resource Locator (URL) union query unique index Universal Naming Convention (UNC) update update query updateable snapshot URL (Uniform Resource Locator) user account user-defined collection user-defined function | user-defined object user-level security Users group validation validation rule value variable Variant VBScript (Visual Basic Scripting Edition) verb view (window) View button visibility Visual Basic Editor
W-Z | Return to top
watch expression Watch pane Watch window Web Page Preview What's This button What's This tip WHERE clause Windows application programming interface (API) | wizard workgroup workgroup ID (WID) workgroup information file World Wide Web Yes/No data type zero-length string Zoom box
 | Return to top


Turn on or turn off automatic display of Help topics by the Office Assistant

  1. Click the Office Assistant.

    If the Assistant isn't visible, click Show the Office Assistant on the Help menu.

  2. Click Options.

  3. On the Options tab, select or clear the Guess Help topics check box.


Hide or show the Office Assistant

You can temporarily hide or show the Office Assistant while you're working in Microsoft Access. You can also turn off the Office Assistant for your entire Access session and use only the Help window. How to get Help without the Office Assistant.

Temporarily hide or show the Office Assistant

  • On the Help menu, click Hide the Office Assistant or Show the Office Assistant.

Turn off the Office Assistant for an entire Access session

  1. In the Assistant balloon, click Options.

    If the Assistant balloon isn't visible, click the Assistant.

  2. On the Options tab, clear the Use the Office Assistant check box.

Tip To turn on the Assistant at any time, click Show the Office Assistant on the Help menu.

Note You can remove the Assistant permanently by rerunning Access Setup. How to remove the Assistant.


Select a different Office Assistant

  1. Click the Office Assistant.

    If the Assistant isn't visible, click Show the Office Assistant on the Help menu.

  2. In the Assistant balloon, click Options.

  3. Click the Gallery tab, and then click Back or Next until you see the Assistant you want.

Note If you have access to the Internet, you can download additional Assistants from the Microsoft Office Update Web site. On the Help menu, click Office on the Web.


Turn the Office Assistant sound on or off

To hear sound from the Office Assistant, you must have a sound card installed on your computer.

  1. Click the Assistant.

    If the Assistant isn't visible, click Show the Office Assistant on the Help menu.

  2. Click Options.

  3. On the Options tab, select or clear the Make sounds check box.


Keys for using the Office Assistant

To perform most of the following actions, the Office Assistant must be turned on and visible.

Press | To
F1, if the Assistant is showing. | Display the Assistant balloon
ALT+number (ALT+1 is the first topic, ALT+2 is the second, and so on) | Select a Help topic from the list the Assistant displays
ALT+DOWN ARROW | See more Help topics
ALT+UP ARROW | See previous Help topics
ESC | Close an Assistant message
F1 The Assistant must be turned on. How to turn the Assistant off or on. | Get Help from the Assistant
ESC | Close a tip


Ways to get assistance while you work

This topic provides reference information about:

Asking for Help from the Office Assistant

Getting Help from the Help menu

Getting Help from the Office Update Web site

Finding out what’s new in Access 2000

More information

Asking for Help from the Office Assistant

When you have a question about a Microsoft Office program, you can ask the Office Assistant. For example, to get Help about how to format a chart, type How do I format a chart? in the Assistant.

If the correct topic doesn't appear in the Assistant balloon, click None of the above, look for more help on the Web at the bottom of the list of topics. You will get suggestions on how to phrase a question to the Office Assistant or how to narrow your search by using keywords. If you still can't find the information you want, you can send feedback to improve future versions of Help and be automatically connected to the Microsoft Office Update Web site to search for help there.

The Assistant automatically provides Help topics and tips on tasks you perform as you work — before you even ask a question. For example, when you design a report, the Assistant automatically displays topics for helping you create and design a report.

The Assistant also displays tips on how to use the features in the Office programs more effectively. Click the light bulb [image] next to the Assistant to see a tip.

You can also select a different Assistant and set it to operate so that it matches your personality and the way you work. For example, if you prefer using the keyboard to using the mouse, you can have the Assistant display tips on shortcut keys. Because the Assistant is shared by all Office programs, any options you change will apply to the Assistant in your other Office programs as well.

Return to top

Getting Help from the Help menu

Just click Microsoft Access Help on the Help menu. If the Assistant is turned on, it appears. If the Assistant is turned off, the Help window appears. To type a question in the Help window, click the Answer Wizard tab. To scroll through a table of contents for Help, click the Contents tab. When you want to search for specific words or phrases, click the Index tab.

To see a ScreenTip for a menu command, toolbar button, or screen region, click What's This? on the Help menu and then click the item you want information about.

To see a ScreenTip for a dialog box option, click the question mark button [image] in the dialog box, and then click the option. (If you don't see the question mark button, select the option and then press SHIFT+F1.)

To see the name of a toolbar button, rest the pointer over the button until the name appears.

Return to top

Getting Help from the Office Update Web site

You can connect to the Microsoft Office Update Web site and other Microsoft Web sites directly from any Office program by using the Office on the Web command on the Help menu. For example, you can access technical resources and download free product enhancements — all without leaving the Office program you're working in.

Return to top

Finding out what’s new in Access 2000

Discover the new features in Access 2000 that make the product easier to use, along with tips on how you can apply them in your work.

Return to top

More information

Connect to Microsoft technical resources

Display tips and messages through the Office Assistant

Get Help without the Office Assistant

Return to top


Get Help without the Office Assistant

To get help without the Office Assistant, the Assistant must be turned off. How to turn off the Assistant.

  1. On the Help menu, click Microsoft Access Help.

    If the Contents, Answer Wizard, and Index tabs aren't visible, click Show Expand control.

  2. In the Help window, do the following:
Click | To
The Contents tab | View the table of contents for Help.
The Answer Wizard tab | Type a question about an Office program.
The Index tab | Search for specific words or phrases, or choose from a list of keywords. You can control the list of topics found by adding or removing keywords from your search. In this way, you can narrow your search until only very relevant topics and keywords remain in the list.


 Get Help on specific areas in a data access page in Page view

Get Help on specific areas in a data access page in Page view

The topics in Microsoft Access Help explain how to view and work with a data access page in general; however, the authors of the page may have provided Help information specific to the page that you are viewing. For example, they may have added instructions directly to the page, or they may have added a custom Help button or hyperlink to Help information for the page.

A data access page may also include features that have their own Help built into them. For example, a PivotTable list or spreadsheet has its own Help that explains how to work with just that feature of the page.

In Page view of a data access page, do one of the following:

  • To get Help about either the PivotTable list or spreadsheet, click Help [image] on the toolbar in the PivotTable list or spreadsheet.

  • To redisplay Microsoft Access Help, close the Help window for the spreadsheet or PivotTable list, and then click Help [image] on the toolbar at the top of the Page view window.

Note Other features, such as Windows Media Player, also have their own Help, which is available by right-clicking that feature.


 Get Microsoft Script Editor Help in a data access page

Get Microsoft Script Editor help in a data access page

  1. Open a data access page in Design view or Page view.

  2. On the Tools menu, point to Macro, and then click Microsoft Script Editor.

  3. In the Microsoft Script Editor, click Help, and then do one of the following:
    • For a table of contents of Microsoft Script Editor Help, click Contents.

    • To browse through an index of keywords to find information in the Microsoft Script Editor Help, click Index.

    • To search for any words you want to find in the Microsoft Script Editor Help, click Search.

Note Microsoft Script Editor does not work with Microsoft Windows Terminal Server.


Print a Help topic

Print the current topic

  1. Click Print [image].

  2. Select the printing options you want.

Print a collection of topics

  1. Click the Contents tab.

    If the Contents tab isn't visible, click Show Expand control to display the navigation pane.

  2. Select the heading you want to print, and then click Print [image].

  3. Do one of the following:

    To print the current page, click Print the current page.

    To print all of the topics in the selected heading, click Print everything contained in the current heading.

  4. Select the printing options you want.


Change the fonts and background colors in a Help topic

What do you want to do?

Change the text and background color in a Help topic

Change the font in a Help topic

Make Access more accessible

Not sure which choice you want?


 About changing the fonts and background colors in a Help topic

About changing the fonts and background colors in a Help topic

The Help window shares the same settings for font colors, typefaces, and background colors as the settings for the Web browser that is installed on your computer. These settings and other options will vary depending on the version and the type of browser that is installed on your computer. You can change the appearance of the Help topics in the Help window by changing the settings for the font and background color. These settings are specified in a cascading style sheet. You can override any or all of these settings, which can be useful if you have limited vision. Keep in mind that if you change the font and background color of the Help topics in the Help window, the change will also affect the font and background color when you view a Web page in your browser. See your browser Help for more information on the settings and options available in your browser.

Return to Change the fonts and background colors in a Help window.


Change the text and background color in a Help topic

  1. In the Microsoft Access Help window, click Options [image] , and then click Internet Options.

  2. On the General tab, click Accessibility, and then click Ignore colors specified on Web pages.

  3. Click OK.

  4. On the General tab, click Colors, and then select the options you want.


Change the font in a Help topic

  1. In the Microsoft Access Help window, click Options [image], and then click Internet Options.

  2. On the General tab, click Accessibility, and then click Ignore font styles specified on Web pages.

  3. Click OK.

  4. On the General tab, click Fonts, and then select the options you want.


Get information about your program and computer

  1. On the Help menu, click About Microsoft Access.

    Program information appears in the About Microsoft Access dialog box.

  2. In the dialog box, click System Info to see information about your computer.


 The cast of characters

View What's This tips

View What's This tips on menu commands, shortcut menu commands, toolbar buttons, and other screen items

  1. On the Help menu, click What's This. The pointer changes to the question-mark pointer.

  2. Click the item you want information about.

View What's This tips on dialog box options

  1. For Help on an option, click the question mark [image]. The pointer changes to the question-mark pointer.

  2. Click the option you want information about.

Tip You can add the What's This button [image] to a toolbar. The What's This button is in the Window And Help category on the Commands tab in the Customize dialog box (right-click any toolbar and click Customize).


Display tips and messages through the Office Assistant

What do you want to do?

Hide, show, or turn off the Office Assistant

Turn on or turn off automatic display of Help topics by the Office Assistant

Display messages with or without the Office Assistant

Show the Tip of the Day when Microsoft Access starts

Not sure which choice you want?


Show the Tip of the Day when Microsoft Access starts

  1. Click the Office Assistant.

    If the Assistant isn't visible, click Show the Office Assistant on the Help menu.

  2. Click Options.

  3. On the Options tab, select the Show the Tip of the Day at startup check box.


Display messages with or without the Office Assistant

  1. Click the Office Assistant.

    If the Assistant isn't visible, click Show the Office Assistant on the Help menu.

  2. Click Options.

  3. On the Options tab, select or clear the Display alerts check box.


About displaying tips and messages through the Office Assistant

The Office Assistant can answer your questions, offer tips, and provide Help for a variety of features specific to the program you're using. The Assistant is shared by all Microsoft Office programs. Any changes you make to its options — such as the types of tips it displays — will affect the Assistant in all of your Office programs. The Assistant can display Help in the following ways:

Suggested Help The Assistant can suggest Help that is relevant to the specific task you're performing — even before you ask for it.

Messages When the Assistant is turned on, program and system messages are displayed in the Assistant balloon by default. If you want, you can choose to see the messages in a dialog box by turning off the Assistant. How to turn off the Assistant.

Return to Display tips and messages through the Office Assistant.


 Troubleshoot passwords

Troubleshoot passwords

Why can't I delete my password?

Only an administrator account (a member of the Admins group used to manage security for your workgroup) can delete a password. If you have forgotten or lost your password, you must get an administrator to delete it.


Troubleshoot finding and opening files

What do you need help with?

I know a file is on a drive or in a folder displayed in the Open dialog box, but I don't see it.

When I use one of my saved searches, I can't find some of the files previously found.

I can't open a file on the Internet.

I want to open an HTML file in Access, but it opens in another Office program.


 Troubleshoot compacting an Access database or Access project

Troubleshoot compacting an Access database or Access project

A Microsoft Access database or Microsoft Access project will not compact for any of the following reasons:

  • You don't have enough storage space on your disk for both the original and compacted versions of the Access database or Access project. Delete any unneeded files and try again.

  • You don't have both Open/Run and Open Exclusive permissions for the Access database. If you don't own this database, contact its owner to find out whether you can be given these permissions. If you own this database, you need to update your permissions.

  • Another user has the Access database or Access project open.

  • The Access database or Access project is located on a read-only network share, or its file attribute is set to Read Only.


Troubleshoot converting an Access database

You can convert most previous-version Microsoft Access databases to Microsoft Access 2000 with no difficulty. In some rare cases, however, new features can conflict with existing objects and code.

Converting any previous-version database

An identifier causes an error.

My code can't compile.

Time or date values in my query criteria return different results.

Converting a Microsoft Access version 2.0 database

My converted Microsoft Access version 2.0 report has different margins.

A procedure causes an error.

I receive an out-of-memory error when converting a large database.

My 16-bit API calls do not convert.

My custom controls do not convert.

I receive an error that a table exceeds the limit of 32 indexes.

I receive an ODBC error when opening a form or report in a converted database.

Converting a Microsoft Access 2000 database to Microsoft Access 97

I receive a message that my computer is missing at least one of the Access 97 object libraries


 Troubleshoot editing data in a field in Datasheet or Form view

Troubleshoot editing data in a field in Datasheet or Form view

There are several kinds of fields in forms or datasheets that you can't edit. The following fields display values just as regular fields do, but if you try to enter data into them, nothing happens:

  • AutoNumber fields. If a field in a Microsoft Access database has an AutoNumber data type or in a Microsoft Access project has a numeric data type with the Identity property set, Access automatically assigns a number to this field for each record you add. This type of field is often used as a record ID number or primary key. When you start adding a new record, Access automatically fills in the field's value for you and you can't edit it.

  • Calculated fields. In an Access database, a calculated field displays values that Access calculates. They are usually based on other fields in your tables, but calculated fields are not stored in tables. You can't edit calculated fields.

  • Locked or disabled fields. If a control on a form has the Locked property set to Yes or the Enabled property set to No, you can't edit the data in the field.

  • Fields in a locked record. If you use an Access database in a multiuser environment and a record is locked by another user, you can't edit the data in the record. When you move to a locked record, the locked record indicator [image] is displayed in the record selector.

  • Fields in snapshots. While most queries return recordsets that you can edit, some queries return snapshots, which can't be edited.

  • Field in a read-only form or a locked database. If the form you're using has the AllowEdits property set to No or if the underlying data is read-only or locked by another person, you can't edit data in the form.

You may be having problems entering dates in a field with the Date/Time data type. If you are entering dates using the slash mark format, don't enter a trailing slash mark. For example, entering 1/3 is valid, but 1/3/ is not valid.


Troubleshoot finding and replacing text

What do you want help with?

I can't find or replace text that I know exists. Why?

I can't find or replace text in a field with an input mask. Why?


Troubleshoot filters in tables, queries, and forms

What do you need help with?

The filter didn't return the correct records. Why not?

The filter didn't sort the records in the correct order. Why not?

I can't use an existing query as a filter. Why not?

Why are some of the fields in the Filter By Form window unavailable?

Why do the lists in the Filter By Form window take so long to display?

I don't have lists of values to pick from on one or more of the fields in the Filter By Form window. Why not?

I created a filter on a subform in which the records were synchronized with the main form, but the filter didn't have any affect on the main form. Why not?

I created a filter on a subdatasheet, but the filter didn't have any effect on the datasheet that displays the subdatasheet.


Troubleshoot problems viewing data or changing objects in an Access database in a multiuser environment

What do you need help with?

I'm having problems saving changes to a Microsoft Access database.

I can't change the table's design.

I can't view data in a table.

I can't open a database object.


Troubleshoot problems when pasting data

What do you need help with?

I can't paste the data. Why not?

The data I pasted is in the wrong field. Why?


Troubleshoot subdatasheets

I can't see the foreign key or matching field(s) in my subdatasheet.

My datasheet containing a subdatasheet looks different from when I last saved it.

My subdatasheet displays the same data for each row of the datasheet.

The Link Master Fields box is empty when I add a subdatasheet to a query in a Microsoft Access database.

I have defined a relationship between two tables in an Access database but I don't see a subdatasheet.


Troubleshoot select queries

What best describes the problem with your select query?

The records aren't the ones I want.

The records are in the wrong order.

The columns are wrong.

The calculations in the query are wrong.

I can't update data in the query.

I designed the query to use AutoLookup, but it isn't filling in data automatically.

I need help specifying criteria.

Microsoft Access automatically joins tables or queries I add to query Design view when I don't want them joined.

I'm getting a "Query contains ambiguous outer joins" message.

I'm getting a type mismatch message.

The query is too slow.

I get prompted for a parameter when I don't expect it.


Troubleshoot append queries

What best describes the problem?

The records aren't the ones I want.

The calculations in the query are wrong.

The append query appended data to or from the wrong fields.

I'm getting a key violation message.

I'm getting a validation rule violation message.

I'm getting an error message about s_Generation.

I need help specifying criteria.

The query is too slow.


Troubleshoot crosstab queries

What best describes the problem with your crosstab query?

The column headings aren't in the order I want, or I want to exclude some of them.

One or more column headings in the query's results are labeled "<>".

I'm getting the message "Can't bind name name."

The wrong field values are showing as row or column headings.

The records aren't the ones I want.

The records are in the wrong order.

The columns are wrong.

The calculated amounts are wrong.

I need help specifying criteria in the query.

I can't update data in the query.

The query is too slow.


Troubleshoot delete queries

What best describes the problem?

The records aren't the ones I want.

The delete query deleted records from the wrong table.

I want to delete just the duplicate records after using the Find Duplicates Query Wizard.

I need help specifying criteria.

I'm getting a key violation message.

The query is too slow.


Troubleshoot make-table queries

What best describes the problem?

The records aren't the ones I want.

The records are in the wrong order.

The columns are wrong.

The calculations in the query are wrong.

I need help specifying criteria.

The query is too slow.


Troubleshoot parameter queries

What best describes the problem?

I get prompted for a parameter when I don't expect it.

I want the option of returning all records with a parameter query.

I'm getting the message "Can't bind name name."

I'm getting the message "Too few parameters expected."


Troubleshoot update queries

What best describes the problem?

The query didn't perform the update I wanted.

The records aren't the ones I want.

I need help specifying criteria.

An arithmetic calculation in the query design grid returns a Null (blank) value.

I'm getting the message "Operation must use an updatable query."

I'm getting a key violation message.

I'm getting a validation rule violation message.

I need help determining when I can update data from a query.

The query is too slow.


Troubleshoot forms

What do you need help with?

I don't understand how forms work. Please give me an overview.

My form is blank. Why can't I see my data?

Why can't I edit data in my form?

I can see data from only one table. How can I see data from other tables?

My form is too slow. What can I do to improve its performance?

#Error? or #Name? appears in a control.

I need help troubleshooting problems with a combo box or list box on my form.

I need help troubleshooting problems with a subform on my form.

I need help troubleshooting problems with an option group on my form.

I need help troubleshooting problems with pictures or other OLE objects on my form.


Troubleshoot property sheets on forms and reports

What do you need help with?

Why is the property sheet blank even though I selected a control?

I selected controls. Why don't I see all the properties for the controls in the property sheet?

I selected controls, and the correct properties appear in the property sheet, but the property box for a particular property is blank even though values have been set for that property in one or more of the selected controls.

Why don't the property settings for my bound control match the property settings for the field in table Design view?

I can’t open the property sheet in Form view or Datasheet view.


 Troubleshoot sorting and grouping in a report

Troubleshoot sorting and grouping in a report

What do you need help with?

In a Microsoft Access database (.mdb) or in a Microsoft Access project (.adp):

I want the records in my report to print in the same order in which they appear in the underlying table or other record source.

The records in the groups aren't sorted.

I want the group header to print on the same line as the first detail record.

I want to hide duplicate values that appear in the same group.

In a Microsoft Access database:

The records aren't sorted in the way I expect for my language.


Troubleshoot a PivotTable form

What do you need help with?

Some of the data in the PivotTable form is cut off and there aren't any scroll bars to see the rest of the data.

I clicked the button to edit the PivotTable form, but Microsoft Excel won't let me make any modifications.

The data in the PivotTable form isn't current. How do I update it?

If I open Microsoft Excel without going through the form containing the PivotTable object, I can't find the PivotTable form.


Troubleshoot subforms

I don't understand how subforms work. Please give me an overview.

All of my records show up in my subform — they don't change when I move from record to record in the main form.

I get #Error? or #Name? when I try to display data from my subform on my main form.

Why can't I display form headers and form footers in my subform datasheet?

My subform is too slow. What can I do to speed it up?


Troubleshoot charts in a form or report

What do you need help with?

I change the chart in my form or report, but the changes aren't retained.

I get the message "Can't bind name name" when trying to display a chart in a form or report.

The chart in my form or report appears dimmed or blank.

I can't change the format of the labels on my chart in a form or report.

I can't put the columns on my chart in a form or report in the order I want.


Troubleshoot data access page options

Working with files and links

I don't want to keep my supporting data access page files in a folder.

I saved my data access page to a file server, and now some people can't find or view it.

I moved my data access page to another location and now some of the links are broken.

I can't automatically create a backup copy of my data access page.

The name of a supporting folder for a data access page is in another language.

Users can't open my interactive data access page.

I can't open my data access page.

Working with graphics

I see a red X, a blank image, or no image at all on my data access page.

The graphics and text on my data access page look different on another computer.

Specifying the language

My data access page is displaying the wrong characters for a language.

More information

How to publish data access pages and other Web pages in Access


Troubleshoot opening data access pages

What do you need help with?

I'm having problems viewing a data access page.

I can't locate the HTML file corresponding to a data access page.

I want to open an HTML file in Access, but it opens in another Office program.


Troubleshoot designing data access pages

What do you want help with?

The records aren't sorted the way I want.

The euro symbol isn't displayed for a Currency field on a data access page.

I get one of the following messages

"The expression is not valid."

"Undefined function in an expression."

"The setting you entered isn't valid for this property."

"Invalid argument."

"The DefaultSort property is invalid."

"Wizards are not available at this time."


Troubleshoot working with data access pages in Page view

What do you need help with?

Buttons are missing from the record navigation toolbar.

The fields on the data access page are blank.

I'm having problems editing data in a field in Page view.

I sent a data access page as an e-mail message but the recipient can't read it.

I get a message when I attempt to enter data in Page view.

Note The data access page may contain a PivotTable list or spreadsheet, which has its own troubleshooting information. For more information, click Help [image] on the toolbar for the PivotTable list or spreadsheet, then search for “troubleshooting.”


Troubleshoot a group of controls on a form or report

What do you need help with?

I can't group text boxes or other controls.

I can't ungroup selected text boxes or other controls.


Troubleshoot conditional formatting in a text box or other control on a form or report

What do you need help with?

The conditional formatting I applied to a control doesn't change when I thought it would.

Access isn't applying conditional formatting correctly to a control on my form or report.


Troubleshoot list boxes, drop-down list boxes, and combo boxes

I don't understand how list boxes work. Please give me an overview.

I don't understand how combo boxes and drop-down list boxes work. Please give me an overview.

The list box, drop-down list box, or combo box isn't sorted the way I want.

The text displayed in the combo box is from the wrong column. How do I display data from another column?

When I select a value in a list, it disappears or gives me a message.

I can't select a value in the list box, drop-down list box, or combo box.

#Error? appears in the combo box or drop-down list box, or the combo box or drop-down list box is blank.

I want to refer to a column in the list box or combo box other than the bound column.

I can't type a new value in the combo box.

Why isn't a value that I type in the combo box added to the list?

My list box, drop-down list box, or combo box runs too slow. What can I do to speed it up?


Troubleshoot option groups

I don't understand how option groups work. Please give me an overview.

I added a check box, toggle button, or option button to an option group, but the option group doesn't work.


Troubleshoot pictures and other OLE objects on forms and reports

I don't understand the difference between unbound and bound, embedded and linked objects. Please give me an overview.

When I double-click a linked or embedded object, I get a message saying the file can't be opened.

I want to see the content of my object in my form or report, but I see an icon instead.

My picture becomes distorted when I size it.

Why do the colors in my picture or on my form look so bad?

Why did the size of my database increase significantly more than the size of the object I added?


Troubleshoot expressions

What do you need help with?

I don't understand how expressions work. Please give me an overview.

The criteria argument in a DLookup or other domain aggregate function produces unexpected results.

I'm seeing unexpected results when I try to combine (concatenate) control or field values, variables, or text in an expression.

I'm seeing unexpected results when I try to perform operations on fields that have blank values.

I'm seeing unexpected results when I enter a date value in an expression.

I'm seeing unexpected results when I try to refer to a subform or subreport property or control.

I'm seeing unexpected results when I try to refer to a column in a list box or combo box.

How do I convert text so that the first letter is capitalized and the rest is lowercase?


Troubleshoot macros

What do you need help with?

I don't understand how macros work. Please give me an overview.

How do I find where problems are occurring in my macro?

I don't know what event to attach my macro to so that it does what I want

How do I temporarily disable an action in a macro?

The Where Condition argument in my macro's OpenForm or OpenReport action is producing unexpected results.

The RunCode action in my macro won't run a Visual Basic module.

When I run my macro, Microsoft Access displays messages that I don't want to see.

I'm using the SendKeys action in a macro to send keystrokes to a dialog box, but they're not being sent.


Troubleshoot Visual Basic modules

What do you need help with?

How do I find where problems are occurring in my Visual Basic code?

The criteria argument in a DLookup or other domain aggregate function produces unexpected results.

When I run my code, Microsoft Access displays messages that I don't want to see.

How do I use Microsoft Visual Basic to add a new record to a table?

My procedure produces unexpected results when I use one of the Find methods.

I want to test my Function or Sub procedure to see whether it works.

I get a "Sub or Function not defined" message when I try to use the IsLoaded function.

I get a "Method or data member not found" message when I try to refer to a table field in code.

How can I use Visual Basic to change the underlying SQL statement of a query?


 Troubleshoot problems with linked tables in a Microsoft Access database

Troubleshoot problems with linked tables in a Microsoft Access database

Note You can link a table only in a Microsoft Access database, not a Microsoft Access project.

What do you want help with?

I can't open or update a linked Microsoft Visual FoxPro or dBASE table. Why?

I can't open or update a linked Paradox table. Why?

I can't open or update a linked SQL table. Why?

My queries get different results with linked tables. Why?

My filters get different results with linked tables. Why?

I get the message, "Couldn't find file '<file name>'." when I try to open a linked table. Why


Troubleshoot text or spreadsheet import errors

What do you need help with?

Errors are reported when I import a spreadsheet or text file. Why?

Errors are reported when I append a spreadsheet or text file to an existing table. Why?


 I receive an ODBC error when opening a table or form in a converted database.

I receive an ODBC error when opening a table or form in a converted database.

The error "ODBC – connection to datasourcename failed" occurs when a table in your converted Microsoft Access version 1.x or 2.0 database is linked to an ODBC data source that uses a 16-bit driver manager and driver. Microsoft Access 2000 can open only linked ODBC data sources that use the 32-bit versions of the ODBC Driver Manager (Odbc32.dll) and the appropriate ODBC driver — for example, the 32-bit version of Microsoft SQL Server ODBC driver (Sqlsrv32.dll).

To correct this problem, you must create a new, identically-named 32-bit data source name (DSN) for each ODBC data source that is linked to the original 1.x or 2.0 database.

  1. Click the Windows Start button, point to Settings, and then click Control Panel.

  2. Double-click the ODBC (32bit) icon (in Microsoft Windows 95 or later) or ODBC icon (in Microsoft Windows NT Workstation 4.0 or later).

  3. Create the new DSN by entering identical values to the original DSN. For example, for Microsoft SQL Server, you need to define at least Data Source Name and Server, but you may also need to define additional values such as the Database Name. More information about data sources.

If you are uncertain what the original name of the DSN was, open the original database in the version of Microsoft Access it was created with, open the linked table in Design view, and then display the Table Properties sheet. The table's Description property contains the definition for the ODBC connection string. The parameter following DSN= in the connection string is the name of the DSN. To view the rest of the DSN's definition, open Windows Control Panel in Windows 95 or later, double-click the ODBC icon (not the ODBC (32bit) icon). In the Data Sources (Driver) list, click the name of the DSN, and then click Setup to view the DSN's definition.


Troubleshoot printing and viewing report snapshots

What do you need help with?

I can't open a report snapshot.

I get the Web page instead of the report when I print a report snapshot.

I can't send a report snapshot in e-mail.


What is my Registration ID?

After Microsoft receives and verifies your registration information, a Registration ID will be returned to you by the same method that you used to register (unless you registered through the Internet, in which case you don't need a Registration ID). The next time you start Microsoft Access or another Microsoft Office program, you'll be prompted to enter your Registration ID to complete the registration process. If you don't receive your Registration ID by the time you start Access or Office again, you'll have the option of completing the registration process by telephone.


I can't register Microsoft Access or Microsoft Office

You might have chosen not to register In some countries, registration is not required. If you are not required to register, the first time that you start Access or another Office program, you have the opportunity to fill in an electronic registration form and return it to Microsoft by using your Internet or e-mail connection. If you don't have an Internet or e-mail connection, then you can print the form and mail or fax it to Microsoft. You can also register by telephone by following the instructions in the Office Registration Wizard. Your only opportunity to fill in the electronic registration form is the first time you start Access or another Office program. If you chose not to register at that time, then the only other method available for you to register is through the Microsoft Office Update Web site.

You might not have an Internet or e-mail account set up on your computer To return the registration form to Microsoft electronically, you must have a modem and an Internet or e-mail account. You can get an account through an Internet service provider or through your corporate network. If you don't have an Internet or e-mail connection, then you can print the form and mail or fax it to Microsoft. You can also register by telephone by following the instructions in the Office Registration Wizard. If you live in a region where registration is not required, and you choose not to register when you first start Access or another Office program, then the only other method available for you to register is through the Microsoft Office Update Web site.

The network might be busy Check your network connection and try to return the registration form later, when there's less network activity. You can also print the form and then mail or fax it to Microsoft. Or you can register by telephone by following the instructions in the Office Registration Wizard. If you live in a region where registration is not required, and you choose not to register the first time that you start Access or another Office program, the only other method available for you to register is through the Microsoft Office Update Web site.


 My server-generated HTML files do not appear as expected when I display them in a Web browser.

My server-generated HTML files do not appear as expected when I display them in a Web browser.

When you export a datasheet to ASP or IDC/HTX output format, the data that you see when you display the .asp or .htx file in a Web browser is the actual data in the recordset behind the datasheet. By default, Microsoft Access saves Text and Memo fields with left alignment, and saves all other supported data types with right alignment.

When you output a datasheet, Microsoft Access does not output OLE objects or the related values from a Lookup field, and ignores the OrderBy, Filter, Format, or InputMask property settings.

If you want the server-generated HTML files to look like the datasheet in a Microsoft Access database, you can create and export a query that has the same recordset as the datasheet. When you create the query, do the following:

  • Use the Sort cell in the query design grid to sort the data. Learn about sorting in a query.

  • Use the Criteria cell in the query design grid to filter the data. Learn about using criteria in a query.

  • Use the Format function to format the fields, such as Currency, Date/Time, and Yes/No. Learn about using the Format Function.

  • Create an Autolookup query to display the values from a Lookup list. Learn about Autolookup queries.


The Mail Recipient and the Mail Recipient (as Attachment) commands don't appear on the Send To submenu (File menu).

Make sure that you've installed one of the following, or check with your administrator about getting the proper program installed:

  • Microsoft Exchange

  • Microsoft Outlook 2000

  • Outlook Express version 5.0


Troubleshoot collecting and pasting

I can't add additional items to the Office Clipboard.

The Clipboard toolbar no longer appears when I copy and paste items.

The Clipboard toolbar is not available.

The Paste All button is not available.


Troubleshoot online meetings

What do you need help with?

I can't print or save an Access database, Access project, or data access page opened from an online meeting to my local printer or hard disk.

Other people in the online meeting see a crosshatch pattern on the screen.

I don't see some items that other people in the online meeting see.

The name of the person I want to invite to an online meeting is not in the list.

Which NetMeeting directory server should I connect to?


Troubleshoot the Office Assistant

What do you need help with?

The Office Assistant is distracting.

The Office Assistant doesn't show the Help topic I want.

The Office Assistant balloon disappeared.


Troubleshoot toolbars, menu bars, and shortcut menus

What do you need help with?

My built-in toolbars and menus have disappeared. How do I get them back?

I've made changes to the built-in toolbars that came with Microsoft Access. How do I return them to their original state?

I removed the Toolbars command from the View menu or removed the View menu from the menu bar. How can I display the Customize dialog box, or get the Toolbars command or View menu back?

I'm having trouble either pasting or resetting an icon image on a menu or toolbar.

Why can't I customize the toolbar?

Why is my toolbar cut off?

Why can't I show or hide a toolbar, menu bar, or shortcut menu?

I want the menus to look like they did in Microsoft Office 97.

I can't find a menu command, toolbar button, or dialog box option.

I want the short menus to stop expanding automatically.


Troubleshoot using your settings on another computer

My settings aren't available when I log on.

My templates aren't appearing on the correct tab.


Troubleshoot hyperlinks

I can't open a file on the Internet.

When I click a hyperlink, an error message appears.


Microsoft Access accessibility

Access contains accessibility features that make it easier to use for people who are blind or have low vision, or have limited movement or dexterity. Learn about accessibility features.

What do you want to do?

Use the keyboard instead of the mouse

Use keyboard shortcuts

Manage relationships by using the keyboard

Place a text box or other control on a form or report by using the keyboard

Place a text box or other control on a data access page by using the keyboard

Copy a text box or other control on a form or report by using the keyboard

Rearrange columns in Datasheet view by using the keyboard

Customize toolbars and menus

Change the size of all toolbar buttons at once

Organize toolbar buttons, menu commands, or menus into groups by using separator bars

Create a custom toolbar for the current database

Create a custom toolbar for all databases

Change the fonts and background colors in a Help topic

Customize text boxes or other controls

Create custom colors for a section or control on a form or report

Change the background color of a control or section

Enter data

Insert repeated entries in a column by using the keyboard

Make Access correct text automatically

Additional services

Learn more about accessibility information on the Web


About accessibility for people with disabilities

This topic provides reference information about:

Accessibility features in Microsoft Access

Customizing the operating system

Printed information about Microsoft services

Accessibility features in Microsoft Access

If you have disabilities, you can do the following to take advantage of accessibility features in Access:

  • View and print lists of all available shortcut keys.

  • Use the keyboard to define relationships, add or copy text boxes or other controls on forms and reports, and rearrange columns in Datasheet view.

  • Create a toolbar that contains only the buttons and menus you use most often for the current database or for all your databases. You can also increase the size of the buttons and group related buttons together.

  • Set menus to display all commands all the time, as in Microsoft Office 97. You can also change toolbars to appear as they did in Office 97.

  • Create custom colors or change the background color for a section or control on a form or report.

  • Insert repeated entries in a column quickly by using the keyboard.

  • Automatically correct common typing errors and even specify a list of errors you want corrected as you type.

Learn about making Access more accessible.

Return to top

Customizing the operating system

If you're running Microsoft Windows 95 on your computer, you can set or change system accessibility options. For example, with the Windows MouseKeys feature you can use the numeric keypad to move the mouse pointer and to click, double-click, and drag objects. To change the accessibility options, press CTRL+ESC to open the Windows Start menu, select Settings, and then select Control Panel. Select the Accessibility Options icon, press CTRL+TAB to select the tab you want, and then use the keyboard to select the options you want. For Help on an option, select the option and press SHIFT+F1.

If you have access to the World Wide Web, you can learn more about using accessibility features included in Microsoft operating systems and other Microsoft products.

Return to top

Printed information about Microsoft services

More complete information about Microsoft services for people with disabilities is available in an appendix in the Discovering Microsoft Office 2000 book, available with Office 2000. For example, you'll find information about how people who are deaf or hard-of-hearing can contact the Microsoft Sales and Information Center or the Microsoft Support Network. You'll also find information about obtaining Microsoft documentation from Recording for the Blind & Dyslexic, Inc., for those who have difficulty reading or handling printed documentation. The appendix also describes third-party hardware and software products that make personal computers easier to use for people with disabilities, and lists organizations to contact for more information.

Return to top


 Keyboard shortcuts

Keyboard shortcuts

You can use shortcut keys for quick access to frequently used commands or operations. The topics below list the shortcut keys available in Microsoft Access. You can also use access keys to move the focus to a menu, command, or control without using the mouse. Learn how to perform tasks with access keys.

This topic provides links to topics in the following areas:

General shortcut keys

Shortcut keys for working with text and data

Shortcut keys for navigating records

Shortcut keys for working in data access pages

Which shortcut keys do you want to use?

General shortcut keys

Global Microsoft Access shortcut keys

Database window shortcut keys

Work with menus

Work with toolbars

Work in windows and dialog boxes

Work with the Open, File New Database, and Save dialog boxes

Get Help from the Office Assistant

Work with the Help window

Send e-mail messages

Return to top

Shortcut keys for working with text and data

Select text and data

Edit text and data

Return to top

Shortcut keys for navigating records

Navigate in Datasheet view

Navigate in subdatasheets

Navigate in Form view

Navigate in Print Preview and Layout Preview

Navigate in the Database Diagram window in a Microsoft Access project

Navigate in the Query Designer in an Access project

Return to top

Shortcut keys for working in data access pages

Work with data access pages in Page view

Work with data access pages in Design view

Work with a PivotTable list

Work with a spreadsheet

Return to top

Note To learn about keyboard shortcuts you can use in the Visual Basic Editor, open the editor and start Visual Basic Editor Help. In the Help window, press CTRL+TAB to select the Contents tab. Select Visual Basic User Interface Help and press ENTER; select Shortcuts and press ENTER; and then select the topic you want to view and press ENTER.


 Copy a text box or another control on a form or report by using the keyboard

Copy a text box or another control on a form or report by using the keyboard

  1. Press ALT.

  2. Press CTRL+TAB until the Object combo box on the Formatting (Form/Report) toolbar has the focus, and then press ENTER.

  3. Press F4 to open the Object combo box.

  4. Press the DOWN ARROW key to select the control, and then press ENTER.

  5. Press CTRL+C to copy the control to the Clipboard.

  6. Repeat steps 1 through 3 to open the Object combo box.

  7. Press the DOWN ARROW key to select the section, and then press ENTER.

  8. Press CTRL+V to paste the control in the upper-left corner of the section. To paste multiple copies, press CTRL+V repeatedly.

  9. To adjust the location of the control by using property settings, select the control and press ALT+V+P to display the control's property sheet. Press CTRL+TAB to select the All tab. Adjust the Left and Top property settings to move the control to the desired location on the form or report, and then press ALT+F4 to close the property sheet.

    Alternatively, press CTRL+ARROW to manually move the control and SHIFT+ARROW to resize the control as needed. Learn about shortcut keys for editing controls.


 Place a text box or another control on a data access page by using the keyboard

Place a text box or another control on a data access page by using the keyboard

  1. Open the data access page in Design view.

  2. Press ALT.

  3. Press CTRL+TAB to put focus on the toolbox.

    Note If the toolbox is not displayed, press the access keys ALT+V+O.

  4. Press TAB repeatedly until you select the desired control.

  5. Press SHIFT+ENTER to add the control to the upper-left corner of the selected section.

  6. Make sure the control is still selected, and press the access keys ALT+V+P to display the control's property sheet. Then, press CTRL+TAB to select the All tab.

  7. Adjust the Left and Top property settings to move the control to the desired location on the form or report, and then press ALT+F4 to close the property sheet. Alternatively, press CTRL+ARROW to manually move the control. Learn about shortcut keys for editing controls.


 Place a text box or another control on a form or report by using the keyboard

Place a text box or another control on a form or report by using the keyboard

  1. Press ALT.

  2. Press CTRL+TAB twice to put focus on the toolbox.

    Note If the toolbox is not displayed, press CTRL+SHIFT+F10 to display the toolbar shortcut menu. Use the DOWN ARROW key to select Toolbox, and then press ENTER.

  3. Press TAB repeatedly until you select the desired control.

  4. Press SHIFT+ENTER to add the control to the upper-left corner of the form or report detail section.

  5. Make sure the control is still selected, and press ALT+V+P to display the control's property sheet. Then, press CTRL+TAB to select the All tab.

  6. Adjust the Left and Top property settings to move the control to the desired location on the form or report, and then press ALT+F4 to close the property sheet. Alternatively, press CTRL+ARROW to manually move the control and SHIFT+ARROW to resize the control as needed. Learn about shortcut keys for editing controls.

Learn how to copy the control on a form or report by using the keyboard.


 Rearrange columns in Datasheet view by using the keyboard

Rearrange columns in Datasheet view by using the keyboard

  1. Move the insertion point to a field in the column of the datasheet or subdatasheet you want to move. Learn about navigating in a datasheet or navigating between a datasheet and subdatasheet.

  2. If the entire field is not already highlighted, press F2.

  3. To select the entire column, press CTRL+SPACEBAR. You can select more than one column by pressing SHIFT+LEFT ARROW or SHIFT+RIGHT ARROW. (This has to be done before you enter Move mode.)

  4. To turn on Move mode, press CTRL+SHIFT+F8.

  5. To move the column to the right, press the RIGHT ARROW key.

    To move the column to the left, press the LEFT ARROW key.

  6. To turn off Move mode, press ESC.


 Define relationships by using the keyboard

Define relationships by using the keyboard

  1. Close any tables that you have open. You can’t create or modify relationships between open tables.

  2. If you haven’t already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  3. Press ALT+T to select the Tools menu, and then press R to open the Relationships window.

  4. If your database doesn’t have any relationships defined, the Show Table dialog box appears automatically. If you need to add the tables that you want to relate, and the Show Table dialog box does not appear, press ALT+R to select the Relationships menu, and then press T to open the Show Table dialog box. If the tables that you want to relate already appear in the Relationships window, skip to step 7.

  5. In the Show Table dialog box, select the first table that you want to relate, and then press ENTER to add it to the Relationships window.

  6. Repeat step 5 for any other tables you want to relate, and then press ALT+C to close the Show Table dialog box.

  7. Press ALT+R to select the Relationships menu, and then press R to open the Edit Relationships dialog box.

  8. Press ALT+N to open the Create New dialog box.

  9. In the Left Table Name box, select the name of the table that contains the primary key.

  10. In the Right Table Name box, select the name of the table that contains the foreign key.

  11. In the Left Column Name box, select the primary key field, and in the Right Column Name box, select the foreign key field.

    The related fields don’t have to have the same names, but they must have the same data type and contain the same kind of information. In addition, when the matching fields are Number fields, they must have the same FieldSize property setting. There are two exceptions to matching data types: you can match an AutoNumber field with a Number field whose FieldSize property is set to Long Integer; and you can match an AutoNumber field with a Number field if the FieldSize property for both fields is set to Replication ID.

  12. Press ENTER.

  13. In the Edit Relationships dialog box, use the arrow keys to make sure that the two columns contain the field names you want; you can change them if necessary, or you can specify additional fields if you are using a multiple-field primary key.

    Set relationship options if necessary. For information about a specific item in the Relationships dialog box, select the item and then press F1.

  14. Press ALT+C to create the relationship.

  15. Repeat steps 5 through 14 for each pair of tables you want to relate.

Notes

  • If you need to view all the relationships that are defined in the database, press ALT+R to select the Relationships menu, and then press L. To view only the relationships defined for a particular table, select that table, press ALT+R to select the Relationships menu, and then press D.

  • If you need to make a change to the design of a table, select that table; press SHIFT+F10 to select the shortcut menu, and then select Table Design.

  • You can create relationships for queries as well as tables. However, referential integrity isn't enforced with queries.

  • To create a relationship between a table and itself, add that table twice. This is useful in situations where you need to perform a lookup within the same table. For example, in the Employees table in the Northwind sample database, a relationship has been defined between the EmployeeID and ReportsTo fields, so that the ReportsTo field can display employee data from a matching EmployeeID.


Manage relationships by using the keyboard

What do you want to do?

Define a relationship

Edit or delete a relationship

Define the default join type


 Edit or delete a relationship by using the keyboard

Edit or delete a relationship by using the keyboard

  1. Close any tables that you have open. You can’t modify or delete relationships between open tables.

  2. If you haven’t already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  3. Press ALT+T to select the Tools menu, and then press R to open the Relationships window.

  4. Press ALT+R to select the Relationships menu, and then select press R to open the Edit Relationships dialog box.

  5. Press ALT+T. In the Table/Query box, select the name of the table that contains the primary key, and then make sure that the appropriate table appears in the Related Table/Query box.

  6. Set the relationship options if necessary. For more information about a specific item in the Relationships dialog box, select the item, and then press F1.

  7. If you want to delete the relationship, press ENTER, and then press DELETE.


 Define the default join type by using the keyboard

Define the default join type by using the keyboard

  1. If you haven’t already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  2. Press ALT+T to select the Tools menu, and then press R to open the Relationships window.

  3. Press ALT+R to select the Relationships menu, and then press R to open the Edit Relationships dialog box.

  4. Press ALT+T. In the Table/Query box, select the name of the table that contains the primary key, and then select the appropriate table in the Related Table/Query box.

  5. Press ALT+J. In the Join Properties dialog box, select the desired join type.

    Option 1 defines an inner join. This is the default.

    Option 2 defines a left outer join.

    Option 3 defines a right outer join.

Note You cannot change the default join type if the tables are linked tables. If the linked tables are stored in another Microsoft Access database, you can open the database in which they are stored to set the join type.

Defining the join type for a relationship in the Relationships window doesn't affect the relationship itself; instead it sets the kind of join that will be used by default when creating queries based on the related tables. You can always override the default join type later when defining a query.

Learn more about join types.


Change the size of all toolbar buttons at once

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Click the Options tab, and then select or clear the Large Icons check box.

Note This setting affects all Microsoft Office programs.


Add separator bars between toolbar buttons, menu commands, or menus

You can add separator bars to group related buttons, commands, and menus. For example, the New Database, Open Database, and Save buttons are grouped on the Database toolbar with a bar after the Save button.

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the toolbar, menu bar, or shortcut menu you want to group related buttons, menus, or commands on.

  3. Leave the Customize dialog box open. On the toolbar, menu bar, or shortcut menu, right-click the button, menu, or command before which you want to add a separator bar, and then click Begin A Group on the shortcut menu.

    To remove the separator bar, click Begin A Group again to uncheck it.


Create a custom toolbar for the current database

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, click New.

  3. In the Toolbar Name box, type the name you want, and then click OK.

  4. On the Toolbars tab, click Properties.

  5. Set any properties you want, and then click Close.

    The new toolbar is now placed to the right of the Customize dialog box.

  6. To complete the toolbar, do the following:
    • Add buttons from the Customize dialog box. For more information, click [image] .

    • Move or copy a button from another toolbar. For more information, click [image] .

Notes

  • You can also add menus to a toolbar.

  • Microsoft Access can automatically create a toolbar containing buttons that run existing macros. For more information, click [image] .

  • You can attach the custom toolbar to a form or report. For more information, click [image] .


 Create a toolbar for all Access databases and Access projects

Create a toolbar for all Access databases and Access projects

To design a toolbar that's available in all your Microsoft Access databases and Microsoft Access projects, add buttons to the blank built-in toolbars, Utility 1 and Utility 2.

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, select the check box for Utility 1 or Utility 2 in the Toolbars box.

  3. To complete the toolbar, do the following:
    • Add buttons from the Customize dialog box. For more information, click [image] .

    • Move or copy a button from another toolbar. For more information, click [image] .

Note You can also add menus to a toolbar.


 Create custom colors for a section or control on a form or report

Create custom colors for a section or control on a form or report

If the palette doesn't have the color that you need, you can create your own custom colors.

  1. Open a form in Design view or a report in Design view.

  2. Open the property sheet for the section or control.

  3. Click the ForeColor (for text in a control), BackColor, or BorderColor property.

  4. Click the Build button [image] next to the property box to open the Color dialog box.

  5. Click Define Custom Colors to expand the dialog box.

  6. Click one of the Custom Color boxes on the left side of the dialog box.

  7. Click on any part of the color refiner box that has the color you want. The color refiner box displays all of the available custom colors.

  8. Drag the arrow beside the luminosity bar to define the brightness of the color selected in the color refiner box.

    Microsoft Access displays the color you create in the left side of the Color/Solid box. If you want to see the solid color most closely resembling the one you've created, double-click the right side of the Color/Solid box.

  9. Click Add To Custom Colors.

    Access displays the custom color you created in the Custom Color box.

Note You can also create a color by typing numbers in the Red, Green, Blue, Hue, Sat (saturation), and Lum (luminosity) boxes.


 Change the background color of a control or section

Change the background color of a control or section

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control or section that you want to change.

  3. On the Form/Report Formatting toolbar or the Data Access Page Formatting toolbar, click the arrow next to Fill/Back Color [image] .

  4. Click a color in the palette.

Notes

  • If you want to use the same color for another control or section, you can just click Fill/Back Color [image] (you don't have to click the arrow next to the button and pick the color again from the palette). If you want to set different colors for several controls at once, click the arrow next to Fill/Back Color [image] , click the border of the color palette, and drag it to another location. This way you don't need to click Fill/Back Color [image] each time you want to apply a color.

  • If the palette doesn't include the color that you want, you can create your own custom colors.

    How?


Set screen resolution to show more or less on the screen

  1. On the Windows Start menu, point to Settings, and then click Control Panel.

  2. Double-click the Display icon [image].

  3. Click the Settings tab.

  4. Under Display Area, drag the slider to change the screen resolution.

Note Your monitor and video adapter determine whether you can change your screen resolution.


Work with AutoCorrection

What do you want to do?

Automatically correct typing when I'm entering data

Correct two capital letters in a row automatically when I'm entering data

Automatically capitalize names of days when I'm entering data

Add an AutoCorrect entry while checking spelling

Stop the automatic correction of an entry I make when I'm entering data

Stop automatic corrections that occur when I'm entering data

Use AutoCorrection in a text box or combo box control


 Insert the value that is in the same field in the previous record

Insert the value that is in the same field in the previous record

  1. Open a Datasheet.

  2. Click in the field in which you want to insert the value.

  3. Press CTRL+APOSTROPHE (').


Customize the Microsoft Access environment by setting defaults

  1. On the Tools menu, click Options.

  2. Click the tab for the options you want to set.

  3. Select the options you want to use.

Note To customize the Visual Basic Editor environment, display the editor, click Options on the Tools menu, and then select the options you want to use.


Customize your application's environment with Microsoft Access user profiles

What do you want to do?

Learn about customizing your application's environment with Microsoft Access user profiles

Create an Access user profile

Set Access run-time options


 Display a custom icon for an application

Display a custom icon for an application

  1. On the Tools menu, click Startup.

  2. In the Application Icon box, enter the name of the .ico or .bmp file that contains the icon you'd like to use. If you don't know the name of the file, click the Build button [image] next to the box, and then use the Icon Browser to locate the file. (The Icon Browser works the same way as the Open dialog box. For information on using the search features in these dialog boxes, click [image] .)

Notes

  • Changes to the Application Icon setting take effect immediately upon closing the Startup dialog box.

  • If you'll be distributing your application, it's recommended that the icon file reside in the same folder as your Microsoft Access application.

  • For a list of issues to consider when setting options in the Startup dialog box, click [image] .


 About using your settings on another computer

About using your settings on another computer

This topic provides reference information about:

What is a user profile?

Have your settings always available

More user Information

What is a user profile?

A user profile is a group of settings that defines customization preferences and options for a particular user, including personalized files such as custom dictionaries, custom templates, and AutoCorrect and AutoFormat lists. For example, those customization preferences and options that are specific to a user — such as installed applications, desktop icons, and color options — are contained in a user profile. The operating system uses the information contained in your user profile to configure your computer each time you log on.

Return to top

Have your settings always available

Your system administrator must configure your user profile to travel with you so that your settings, which are stored on a server, will always be available whenever you log on to a computer. This is especially useful if you log on to different computers in your company, or if you share your computer with another person. When you log on, your user profile is downloaded from the server to the computer you've logged on to. Your user profile is only valid on the operating system for which it was created — for example, a Windows NT 4.0 user profile cannot be used on a computer running Windows 95. When you log off, your user profile is copied back to the server so that any changes made while you were logged on will be available the next time you log on.

Return to top

More information

Location of your settings

Return to top


Customize Windows registry settings used by Microsoft Access

Caution Many Microsoft Access registry settings are added automatically when you install Microsoft Access. Changing the installed settings can produce unexpected results, which may make it necessary to reinstall Microsoft Access. It is strongly recommended that you not change settings in the Windows registry. However, if you must change registry settings or options, then use the Windows Registry Editor, and change only those settings or options that are explicitly documented in the topics below. The revised settings take effect the next time you start Microsoft Access. It is recommended that you back up all of the registry, or at least the part you will be editing. For information, look up "backing up the registry" in the index of the Registry Editor's online Help (available on the menu bar of the Registry Editor).

What do you want to do?

Learn more about the Windows registry

Customize Microsoft Jet version 4.0 database engine settings

Customize Microsoft Jet version 3.x database engine settings

Customize Microsoft Jet version 2.x database engine settings

Customize Microsoft Excel driver settings

Customize text driver settings

Customize HTML driver settings

Customize Exchange driver settings

Customize ODBC driver settings

Customize dBASE driver settings

Customize Paradox driver settings

Customize Lotus driver settings

Specify whether OLE links are saved in OLE version 2.0 or 1.0 format

Customize your application's environment with user profiles

Create your own wizards, builders, and add-ins


 Location of your settings

Location of your settings

The location of your settings contained in your user profile depends on the operating system you use and the way your system administrator has configured your user profile on the server. You can find your user profile in the following location:

Root\OS\Profiles\user_name

where Root is a server location or a folder on a drive from which all other folders branch (for example, c:\), OS is the operating system folder (for example, Windows or Winnt), and User_name is your user name.

All of your settings and Office-specific files are located in the Application Data folder in your user profile folder. Your system administrator must configure your user profile to travel with you so that these files will always be available whenever you log on to any computer. The paths are listed below.

User Profile Files | Path
Add-ins | Root\OS\Profiles\User_name\Application Data\Microsoft\Addins
AutoCorrect lists | Root\OS\Profiles\User_name\Application Data\Microsoft\Office
Custom dictionary | Root\OS\Profiles\User_name\Application Data\Microsoft\Proof
Graph | Root\OS\Profiles\User_name\Application Data\Microsoft\Proof
Office Shortcut Bar | Root\OS\Profiles\User_name\Application Data\Microsoft\OSB
Personal information profiles (.pip extension) | Root\OS\Profiles\User_name\Application Data\Microsoft\Office
Most recently used shortcuts | Root\OS\Profiles\User_name\Application Data\Microsoft\Office\Recent
Templates | Root\OS\Profiles\User_name\Application Data\Microsoft\Templates
Themes | Root\OS\Profiles\User_name\Application Data\Microsoft\Themes
Queries | Root\OS\Profiles\User_name\Application Data\Microsoft\Queries
Start | Root\OS\Profiles\User_name\Application Data\Microsoft\Excel\XLSTART
Customized toolbars | Root\OS\Profiles\User_name\Application Data\Microsoft\Excel
Chart gallery | Root\OS\Profiles\User_name\Application Data\Microsoft\Excel
Customized toolbars (.pcb extension) | Root\OS\Profiles\User_name\Application Data\Microsoft\PPT
Start | Root\OS\Profiles\User_name\Application Data\Microsoft\Word\STARTUP
Customized wizard information | Root\OS\Profiles\User_name\Application Data\Microsoft\Access
Stationery | Root\OS\Profiles\User_name\Application Data\Microsoft\Stationery
AutoSignature | Root\OS\Profiles\User_name\Application Data\Microsoft\Signatures
Customized Outlook files | Root\OS\Profiles\User_name\Application Data\Microsoft\Outlook


Microsoft Access specifications

What do you want to do?

Read about Microsoft Access database general specifications

Read about Microsoft Access project general specifications

Read about Microsoft SQL Server database technical specifications

Read about Access database table specifications

Read about Access database query specifications

Read about form and report specifications

Read about macro specifications


 Bypass settings that determine what happens when you open an Access database or Access project

Bypass settings that determine what happens when you open an Access database or Access project

  • Hold down the Bypass key (the SHIFT key) while you open the database.

If you used the Startup dialog box (Tools menu) or created an AutoExec macro or an Open event procedure to specify what happens when you open a Microsoft Access database or Microsoft Access project, you can bypass those settings to regain full access to your Access database or Access project.

Note You can disable the bypass key by writing a macro or Visual Basic for Applications code that sets the AllowBypassKey property of the database to True.


 Control how an Access database or Access project looks and behaves when it starts

Control how an Access database or Access project looks and behaves when it starts

You can specify, for example, what form to display, whether toolbars can be customized, and whether shortcut menus are available.

  1. On the Tools menu, click Startup.

  2. Select the options, or enter the settings you want to use.

Notes

  • For information about a specific item in the dialog box, click the question mark [image] at the top of the dialog box, and then click the item.

  • For a list of issues to consider when setting options in the Startup dialog box, click [image] .

  • For additional information about creating an application, click [image] .


Display a specific title in the application window title bar

  1. On the Tools menu, click Startup.

  2. In the Application Title box, enter the title you want displayed in the application window's title bar.

Notes

  • Changes to the Application Title setting take effect immediately upon closing the Startup dialog box.

  • For a list of issues to consider when setting options in the Startup dialog box, click [image] .


 Display a startup form or data access page when an Access database or Access project opens

Display a startup form or data access page when an Access database or Access project opens

  1. On the Tools menu, click Startup.

  2. In the Display Form/Page box, click a form or data access page from the current Microsoft Access database or Microsoft Access project.

  3. If you don't want users to see or use the Database window, which appears behind the form, clear the Display Database Window check box.

  4. Even if you clear the Display Database Window check box, the Database window may still be accessible. For more information, click [image] .

Notes

  • Changes to these settings in the Startup dialog box won't take effect until the next time the Access database or Access project is opened.

  • The Northwind sample database has a startup form. It also has the Main Switchboard form, an example of a form you might use to control navigation in your Access database or Access project. To view these forms, open the Northwind database in your Office folder’s Samples folder. The Startup form appears automatically when you open Northwind, but you can view it or the Main Switchboard form whenever you want by clicking Forms [image] under Objects in the Database window, clicking Startup or Main Switchboard, and then clicking the Open button on the Database window toolbar. For information on opening Northwind, click [image] .

  • For a list of issues to consider when setting options in the Startup dialog box, click [image] .


 Display or hide the Database window when an Access database or Access project opens

Display or hide the Database window when an Access database or Access project opens

  1. On the Tools menu, click Startup.

  2. Clear or select the Display Database Window check box.

Notes

  • Changes to this setting in the Startup dialog box won't take effect until the next time the Microsoft Access database or Microsoft Access project is opened.

  • If you don't display the Database window, you need to display a form or data access page that others can use to navigate in your Access database or Access project. For more information, click [image] .

  • Even if you clear the Display Database Window check box, the Database window may still be accessible by using a special key combination. For more information, click [image] . And even if you disable the Database window and the key combination, it may still be possible for a user to access the Database window. This can happen if a user tries more than once to open the same Access database or Access project from the list of most-recently-used Access databases or Access projects, which automatically appears on the File menu. To prevent users from accessing this list, replace the File menu with your own custom menu.

  • For a list of issues to consider when setting options in the Startup dialog box, click [image] .


 Display multiple database objects on the Windows taskbar

Display multiple database objects on the Windows taskbar

If you have Microsoft Internet Explorer Active Desktop installed, you can use the Windows taskbar to switch between database objects that are currently open.

  1. On the Tools menu, click Options, and then click the View tab.

  2. Select or clear the Windows in Taskbar check box

Notes

  • To determine whether Microsoft Internet Explorer Active Desktop is installed on your computer, right-click your desktop; if Active Desktop appears on the shortcut menu, then it has been installed. If you do not have Microsoft Internet Explorer Active Desktop installed, you can still select the Windows in Taskbar check box, but it has no effect.

  • Selecting or clearing the Windows in Taskbar check box does not affect taskbar switching behavior in other Microsoft Office applications.


Set the number of files shown in the list of recently used files on the File menu

When you click File on the menu bar, a list of the most recently used files appears on the menu; you can click a file name in this list to open the file with the same option settings it had the last time you opened it.

  1. On the Tools menu, click Options.

  2. On the General tab, do one of the following:
    • To prevent any files from appearing on the File menu, clear the Recently used file list check box.

    • To change the number of files that appear in the list on the File menu, make sure the Recently used file list check box is selected, and then, in the box to its right, select the number of files you want in the list. By default, four files appear in the recently used file list, but you can set the list to contain as many as nine files.


 Set default print margins

Set default print margins

  1. On the Tools menu, click Options.

  2. Click the General tab.

  3. Under Print Margins, specify the margins you want to use as defaults.

Notes

  • Changing these options doesn't affect the margin settings for existing forms and reports.

  • These settings do not apply to data access pages.


Show or hide objects defined as hidden by default

If you need to work with objects that are defined as hidden without changing their status as hidden, you can display them in the Database window.

  1. On the Tools menu, click Options.

  2. Click the View tab.

  3. Under Show, select or clear the Hidden Objects check box. Microsoft Access displays hidden objects with dimmed icons to distinguish them from objects that aren't defined as hidden.


 Show or hide the Microsoft Access startup dialog box by default

Show or hide the Microsoft Access startup dialog box by default

The startup dialog box is the first dialog box you see when you start Microsoft Access. It has options for creating or opening a Microsoft Access database or a Microsoft Access project.

  1. On the Tools menu, click Options.

  2. Click the View tab.

  3. Under Show, select or clear the Startup Dialog Box check box.


Specify a substitution font for dual-font support

  1. On the Tools menu, click Options.

  2. Click the View tab.

  3. Under Dual font support, select the Use substitution font check box, and then click a font in the list.

Note To ensure optimal performance, use substitution fonts only if you need dual-font support to display all of your data.

Learn about dual-font support.


Start Microsoft Access with command-line options

What do you want to do?

Specify command-line options for Microsoft Access on the Start menu

Specify command-line options for a shortcut

Not sure which choice you want?


 Startup command-line options

Startup command-line options

The following table lists the Microsoft Access command-line options.

Option | Effect | Applies To
database | Opens the specified Microsoft Access database or Microsoft Access project. Include a path if necessary. If you are running Microsoft Windows 95, the default path is your My Documents folder. | Access database or Access project
/excl | Opens the specified Access database for exclusive access. To open the database for shared access in a multiuser environment, omit this option. | Access database only
/ro | Opens the specified Access database or Access project for read-only access. | Access database or Access project
/user user name | Starts Microsoft Access by using the specified user name. | Access database only
/pwd password | Starts Microsoft Access by using the specified password. | Access database only
/profile user profile | Starts Microsoft Access by using the options in the specified user profile instead of the standard Windows Registry settings created when you installed Microsoft Access. This replaces the /ini option used in versions of Microsoft Access prior to Access 97 to specify an initialization file. | Access database or Access project
/compact target database or target Access project | Compacts and repairs the Access database, or compacts the Access project that was specified before the /compact option, and then closes Microsoft Access. If you omit a target file name following the /compact option, the file is compacted to the original name and folder. To compact to a different name, specify a target file. If you don't include a path in target database or target Access project, the target file is created in your My Documents folder by default. In an Access project, this option compacts the Access project (.adp) file but not the Microsoft SQL Server database. | Access database or Access project
/repair | Repairs the Access database that was specified before the /repair option, and then closes Microsoft Access. In Microsoft Access 2000, compact and repair functionality is combined under /compact. The /repair option is supported for backward compatibility. | Access database only
/convert target database | Converts a previous-version Access database to an Access 2000 database with a new name, and then closes Microsoft Access. You must specify the source database before you use the /convert option. | Access database only
/x macro | Starts Microsoft Access and runs the specified macro. Another way to run a macro when you open a database is to use an AutoExec macro. | Access database or Access project
/cmd | Specifies that what follows on the command line is the value that will be returned by the Command function. This option must be the last option on the command line. You can use a semicolon (;) as an alternative to /cmd. For information on the Command function, click [image] . | Access database or Access project
/nostartup | Starts Microsoft Access without displaying the startup dialog box (the second dialog box that you see when you start Microsoft Access). | Access database or Access project
/wrkgrp workgroup information file | Starts Microsoft Access by using the specified workgroup information file. | Access database only

Notes

  • To run a Visual Basic for Applications procedure when you open a database, use the RunCode action in the AutoExec macro or in the macro that you run by using the command-line option /x. You can also run a Visual Basic procedure when you open a database by creating a form with a Visual Basic procedure defined for its OnOpen event. Designate this form as the startup form by right-clicking the Database window, clicking Startup, and then entering that form in the Display Form/Page box.

  • To specify a forward slash (/) or semicolon (;) on the command line, type the character twice. For example, to specify the password ;mjs/md on the command line, type ;;mjs//md following the /pwd command-line option.


 Set OLE/DDE preferences

Set OLE/DDE preferences

  1. On the Tools menu, click Options, and then click the Advanced tab.

  2. Under DDE Operations, select the options that you want.
    • Select Ignore DDE Requests to ignore DDE requests from other applications.

    • Select Enable DDE Refresh to update DDE links at the interval specified in the Refresh Interval box.
  3. In the OLE/DDE Timeout box, enter the number of seconds (0 to 300) Microsoft Access should wait before retrying a failed OLE or DDE operation.

Click Apply to apply the settings immediately without closing the dialog box; click OK to apply the settings and close the dialog box.


 Enable or disable keys that display the Database window or menu bars, or stop an Access project from retrieving records

Enable or disable keys that display the Database window or menu bars, or stop an Access project from retrieving records

  1. On the Tools menu, click Startup.

  2. Click Advanced.

  3. Clear or select the Use Access Special Keys check box to enable or disable the following keys.
Keys | Result
F11 or ALT+F1 | Brings the Database window to the front
CTRL+G | Brings up the Immediate window
CTRL+F11 | Toggles between the custom menu bar and the built-in menu bar
CTRL+BREAK | In a Microsoft Access project, stops Access from retrieving records from the server.

Notes

  • Changes to this setting in the Startup dialog box won't take effect until the next time the Microsoft Access database or Microsoft Access project is opened.

  • If you clear the Use Access Special Keys check box and you specify a custom menu bar in the Menu Bar box, the built-in menu bar isn't accessible.

  • If you clear both the Use Access Special Keys check box and the Display Database Window check box, it's possible that users can still access the Database window. This can happen when a user tries more than once to open the same Access database or Access project from the list of most-recently-used Access databases or Access projects, which automatically appears on the File menu. To prevent users from accessing this list, replace the File menu with your own custom menu.

  • For a list of issues to consider when setting options in the Startup dialog box, click [image] .


 Show or hide the status bar for all your Access databases or Access projects

Show or hide the status bar for all your Access databases or Access projects

Changes you make to this setting apply to all your Microsoft Access databases and Microsoft Access projects.

  1. On the Tools menu, click Options.

  2. On the View tab under Show, select or clear the Status bar check box.

Note You can control whether the status bar shows or hides for a specific Access database or Access project. For more information, click [image] .


 Show or hide the status bar for a specific Access database or Access project

Show or hide the status bar for a specific Access database or Access project

  1. On the Tools menu, click Startup.

  2. Select or clear the Display Status Bar check box.

Notes

  • Changes to this setting in the Startup dialog box won't take effect until the next time the Microsoft Access database or Microsoft Access project is opened.

  • You can also control whether the status bar is shown or hidden by default for all Access databases or Access projects. To do this click Options on the Tools menu, click the View tab, and then select or clear the Status Bar check box. The current Access database or Access project won't display a status bar if either the Status Bar check box in the Options dialog box or the Display Status Bar check box in the Startup dialog box is cleared.

  • For a list of issues to consider when setting options in the Startup dialog box, click [image] .


 Prevent or allow access to all built-in toolbars in an Access database or Access project

Prevent or allow access to all built-in toolbars in an Access database or Access project

  1. On the Tools menu, click Startup.

  2. Clear or select the Allow Built-in Toolbars check box.

Notes

  • Changes to this setting in the Startup dialog box won't take effect until the next time the Microsoft Access database or Microsoft Access project is opened.

  • This option does not affect toolbars for PivotTable lists or spreadsheets on a data access page.

  • To enable users to modify built-in toolbars, make sure both the Allow Built-in Toolbars and Allow Toolbar/Menu Changes check boxes are selected. To prevent users from customizing all built-in toolbars, select the Allow Built-in Toolbars check box, but clear the Allow Toolbar/Menu Changes check box.

  • You can prevent users from customizing specific toolbars. For more information, click [image] .

  • For a list of issues to consider when setting options in the Startup dialog box, click [image] .


 Control whether some or all of the built-in menus are displayed

Control whether some or all of the built-in menus are displayed

If the Microsoft Access database or Microsoft Access project you're creating provides the user access to the built-in menus, you can display only a predefined subset of the menus. That way, you can hide menus, such as View and Insert, that would enable a user to access the Design view of objects in your Access database or Access project and to change their design.

  1. On the Tools menu, click Startup.

  2. Clear or select the Allow Full Menus check box.

Notes

  • Changes to these settings in the Startup dialog box won't take effect until the next time the Access database or Access project is opened.

  • For a list of issues to consider when setting options in the Startup dialog box, click [image] .


 Prevent or allow changing all toolbars or menu bars in an Access database or Access project

Prevent or allow changing all toolbars or menu bars in an Access database or Access project

You can control whether users are able to change any built-in or custom toolbars and menu bars.

  1. On the Tools menu, click Startup.

  2. Clear or select the Allow Toolbar/Menu Changes check box.

Notes

  • Changes to these settings in the Startup dialog box won't take effect until the next time the Microsoft Access database or Microsoft Access project is opened.

  • This option does not affect toolbars for PivotTable lists or spreadsheets on a data access page.

  • If you clear this option, you can still move, size, and dock the toolbar or menu bar unless you previously specified otherwise in the Customize dialog box for a specific toolbar or menu bar.

  • When this option is cleared, the Customize dialog box is no longer available. Users won't be able to customize any toolbars or menus even if the Allow Customizing box for a specific toolbar or menu bar was previously checked in the Customize dialog box.

  • To prevent users from using the built-in toolbars, clear the Allow Built-In Toolbars check box.

  • To disable the shortcut menu on toolbars and menu bars only, leave the Allow Default Shortcut Menus check box selected, but clear the Allow Toolbar/Menu Changes check box. This prevents users from customizing toolbars and menu bars.

  • For a list of issues to consider when setting options in the Startup dialog box, click [image] .


 Designate a global menu bar for your Access database or Access project

Designate a global menu bar for your Access database or Access project

By using your own global menu bar, you control what tasks users can perform in your Microsoft Access database or Microsoft Access project by limiting and customizing the menus and commands that are available. 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.

  1. On the Tools menu, click Startup.

  2. In the Menu Bar box, click the name of a custom menu bar from the current Access database or Access project, or click (Default) to display the built-in menu bar.

Notes

  • Changes to this setting in the Startup dialog box won't take effect until the next time the Access database or Access project is opened.

  • Even if you designate a global menu bar, the built-in menu bar may still be accessible. For more information, click [image] .

  • You can designate or change the global menu bar in a Visual Basic for Applications procedure by setting the MenuBar property of the Application object. For more information about the MenuBar property, click [image] .

  • For a list of issues to consider when setting options in the Startup dialog box, click [image] .


 Designate a global shortcut menu for an Access database or Access project

Designate a global shortcut menu for an Access database or Access project

You can define a global shortcut menu to replace built-in shortcut menus for datasheets, forms, form controls, and reports.

  1. On the Tools menu, click Startup.

  2. In the Shortcut Menu Bar box, click the name of a custom shortcut menu from the current Microsoft Access database or Microsoft Access project, or click (Default) to use the built-in shortcut menus.

Notes

  • Changes to this setting in the Startup dialog box won't take effect until the next time the Access database or Access project is opened.

  • You can designate or change the shortcut menu in a Visual Basic for Applications procedure by setting the ShortcutMenuBar property of the Application object. For more information about the ShortcutMenuBar property, click [image] .

  • For a list of issues to consider when setting options in the Startup dialog box, click [image] .


 Enable or disable shortcut menus in an Access database or Access project

Enable or disable shortcut menus in an Access database or Access project

You can control whether built-in shortcut menus are accessible.

  1. On the Tools menu, click Startup.

  2. Clear or select the Allow Default Shortcut Menus check box.

Notes

  • Changes to these settings in the Startup dialog box won't take effect until the next time the Microsoft Access database or Microsoft Access project is opened.

  • This option does not apply to shortcut menus on data access pages, including shortcut menus on PivotTable lists or spreadsheets on a data access page.

  • To disable the shortcut menu on toolbars and menu bars only, leave the Allow Default Shortcut Menus check box selected, but clear the Allow Toolbar/Menu Changes check box. This prevents users from customizing toolbars and menu bars.

  • For a list of issues to consider when setting options in the Startup dialog box, click [image] .


 Install or uninstall menu add-ins

Install or uninstall menu add-ins

You can install or uninstall add-ins by using the Add-in Manager.

  1. On the Tools menu, point to Add-ins, and then click Add-in Manager.

    The Add-in Manager dialog box is displayed. The Available Add-ins list displays the add-ins that are currently available. An add-in is already installed if there is an X next to its name. If an add-in is uninstalled, Microsoft Access removes the X but keeps the name in the list.

  2. Do one of the following:
    • To add an add-in to the list, click Add New, and then specify its location.

    • To install a currently available add-in, click the add-in name in the Available Add-ins list, and then click Install.

    • To uninstall a currently available add-in, click the add-in name in the Available Add-ins list, and then click Uninstall.
  3. Click Close when you've finished.

Note You should uninstall an add-in before opening it as a database to modify its design.


 Wizards, add-ins, and builders in Microsoft Access 2000

Wizards, add-ins, and builders in Microsoft Access 2000

Wizard | Description
AutoDialer Wizard | Allows you to specify modem information when you click an AutoDialer button in Form view.
AutoForm Wizard | Creates a form automatically.
AutoFormat Wizard | Applies a predefined format to a form or report.
AutoPage Wizard | Creates a data access page automatically.
AutoReport Wizard | Creates a report automatically.
Chart Wizard | Adds a chart to a form or report based on the data in a table or query.
Combo Box Wizard | Creates a combo box control on a form.
Command Button Wizard | Creates a command button control on a form.
Conflict ResolverWizard | Resolves conflicts between replicated databases at synchronization time.
Crosstab Query Wizard | Creates a query that summarizes data in a compact, spreadsheet-like format.
Database Splitter Wizard | Splits databases into data and interface portions, so that one or more users can have local copies of the interface connected to the data on a server.
Database Wizard | Creates an entirely new database for a variety of uses based on 2210 prebuilt models.
Documenter | Generates an Access report that displays the design characteristics of database objects.
Export Text Wizard | Exports data to a text file.
Find Duplicates Query Wizard | Creates a query that finds records that have duplicate field values and are in a single table or query.
Find Unmatched Query Wizard | Creates a query that finds records in one table that have no related records in another table.
Form Wizard | Creates a new form.
Import Exchange/Outlook Wizard | Imports an Exchange or Outlook folder to a table in a Microsoft Access database.
Import HTML Wizard | Imports HTML tables and lists from the Internet or an intranet into a Microsoft Access table.
Import Spreadsheet Wizard | Imports a Microsoft Excel or other spreadsheet into a Microsoft Access table.
Import Text Wizard | Imports a text file into a Microsoft Access table.
Input Mask Wizard | Creates an input mask for a field that you choose in a table.
Label Wizard | Creates mailing labels in standard and custom sizes.
Link Exchange/Outlook Wizard | Links an Exchange or Outlook folder to a table in a Microsoft Access database.
Link HTML Wizard | Links an HTML table or list on the Internet or an intranet to a Microsoft Access table.
Link Spreadsheet Wizard | Links spreadsheet data to a Microsoft Access table.
Link Text Wizard | Links a text file to a Microsoft Access table.
Linked Table Manager | Manages attachments to tables between databases.
List Box Wizard | Creates a list box control on a form.
Lookup Wizard | Creates a lookup column in a table, which displays a list of values the user can choose from.
Macro To Module Converter | Converts macros to Visual Basic code.
Microsoft SQL Server Database Wizard | Creates a new Microsoft SQL Server Database that a new Microsoft Access project is connected to.
Microsoft Word Mail Merge Wizard | Manages mail merge operations by using letters that are stored in Microsoft Word and addresses that are stored in Microsoft Access.
Option Group Wizard | Creates a group of option buttons on a form.
Page Combo Box Wizard | Creates a drop-down control on a data access page.
Page Command Button Wizard | Creates a command button control on a data access page.
Page List Box Wizard | Creates a list box control on a data access page.
Page Wizard | Creates a new data access page.
Partial Replica Wizard | Creates or modifies a partial replica of a replica database.
Performance Analyzer | Analyzes the efficiency of a database and produces a list of suggestions for improving its performance.
PivotTable Wizard | Places a Microsoft Excel PivotTable on a Microsoft Access form.
Print Relationships Wizard | Creates a report that diagrams the relationships in a Microsoft Access database.
Report Wizard | Creates a report that is based on a table or query.
Simple Query Wizard | Creates a select query from the fields that you pick.
Subform/Subreport Field Linker | Links fields in a main form and a subform, or in a main report and a subreport.
Subform/Subreport Wizard | Creates a new subform or subreport on a form or report.
Switchboard Manager | Creates and manages switchboard forms for applications.
Table Analyzer Wizard | Takes a table with much duplicate data and splits it into related tables for more efficient storage.
Table Wizard | Creates a new table.
Upsizing Wizard | Upsizes a Microsoft Access database to a Microsoft SQL Server database.
User-Level Security Wizard | Creates a new, encrypted database, with regulated user access, from an existing database. Regulates user access to the current database and creates an unsecured backup copy of the database.

Builder | Description
Color Builder | Displays a palette for creating customized colors.
Expression Builder | Creates expressions for macros, queries, and property sheets.
Field Builder | Creates fields in tables.
ODBC Connection String Builder | Creates the correct syntax for a connection to an ODBC database.
Picture Builder | Creates bitmap images for forms and reports.
Query Builder | Creates the correct syntax for a query.

Add-in | Description
Add-in Manager | Installs and uninstalls wizards, builders, and add-ins.


 Create your own Wizards, Builders, and Add-ins

Create your own wizards, builders, and add-ins

To develop your own add-in (wizard, builder, or menu add-in), you can set several database properties and create a USysRegInfo table in the add-in database (*.mda, *.mde) so that it can be installed by using the Add-in Manager. You can also develop a COM add-in that can be installed by the Add-in Manager. For more information, see Chapter 11, "Add-ins, Wizards, Libraries and Templates," in The Microsoft Office 2000/Visual Basic Programmer's Guide. Learn about obtaining the Microsoft Office 2000/Visual Basic Programmer's Guide.


 About finding files

About finding files

How to search for files The Open, Import, and Link dialog boxes (File menu), and the Database To Convert From, Database To Compact From, Database to Save As MDE As, and Encrypt/Decrypt Database dialog boxes (Tools menu) all help you search for files on your hard drive and on any network drive. You can search for a file by the file name, type, date last modified, or by text within the file except for a Microsoft Access database and Microsoft Access project. You can also search for a file by specific file properties such as author, subject, title, or creation date. How to search for files.

Search for files by using file properties File properties are details about the file that help identify the file — for example, a descriptive title, the author name, the subject, keywords you assign to the file, or other important information.

  • Some file properties are preset These include properties such as author, title, and subject that already exist and those you enter a value for. For example, you might add the keyword "employees" to all your personnel database files and then search for all files with that keyword.

  • Create your own file properties You can enter additional file properties, such as a descriptive title or keywords that identify the file, and then quickly find the file by searching for this information. Learn more about setting file properties that can be used to locate files.

  • Some properties are automatically updated These include statistics such as file size and the dates files are created and last modified. For example, you can use these properties to search for all files created after March 3, 1998, or for those that were last modified yesterday. How to search for files by using file properties.

Search for files using special criteria In the Open dialog box, click Tools and then click Find to search for a file by using nontext properties or by using more advanced combinations of criteria. For example, you can search for files that contain the text "budget" or have the keyword "Budget99".

Save search criteria If you search for the same information over and over, or if you have a complex search set up using multiple search criteria, you might want to save your search to use later. How to save search criteria.

Change saved search criteria If you have saved your search criteria and want to change that criteria, you can. How to change saved search criteria.

Return to Find files


 Find files

Find files

If you cannot find the file you want to open by using the shortcuts on the Places Bar or by looking in the folders you usually save documents in, you can enter search criteria from within Access (in the Open dialog box, click Tools, and then click Find).

What do you want to do?

Search for files

Search for files by using file properties

Search for files by using a saved search

Change a saved search

Not sure which choice you want?


 Sort a list of files

Sort a list of files

  1. On the File menu, click Open [image] .

  2. Click the arrow next to Views [image], point to Arrange Icons, and then click the command you want.

Note You can also sort a list of files in the Import and Link dialog boxes on the File menu, or the Database to Convert From, Database To Compact From, Database to Save As MDE, and Encrypt/Decrypt Database dialog boxes on the Tools menu.


 Connect to a network drive

Connect to a network drive

  1. On the File menu, click Open [image] .

  2. Click Tools, and then click Map Network Drive.

  3. In the Drive box, click the drive letter you want to use to connect to the network.

  4. In the Path box, enter the path of the shared folder you want to connect to.

Tip To automatically connect to this network drive each time you start Microsoft Windows, select the Reconnect at logon check box.


 Go back to the previous drive, folder, or Internet location

Go back to the previous drive, folder, or Internet location

  • In the Open dialog box (File menu), click the Back button [image] .

Tip The name of the previous drive, folder, or Internet location appears in the ScreenTip when you rest the mouse pointer on the Back button.


 Ways to create hyperlinks or shortcuts to files, folders, and Web pages

Ways to create hyperlinks or shortcuts to files, folders, and Web pages

You can create shortcuts to files, folders, and Web pages by using hyperlinks or the Favorites folder.

Hyperlinks You can create a hyperlink in a table, on a form, or on a data access page and then use the hyperlink to go to a variety of locations — for example, a database object in another Microsoft Access database or Microsoft Access project a Microsoft Word document or Microsoft Excel workbook; or an Internet, intranet, or e-mail address. You can create a hyperlink from a text box based on a Hyperlink field, a command button on a form, or a label or picture on a form or data access page. You can also assign a hyperlink to a toolbar button so that you can jump to a particular file, Web page, or e-mail address that you use frequently.

Favorites folder The Favorites folder is a good place to store shortcuts to files and folders you use often, including those in remote network locations. The original file or folder doesn't move — instead, you create a shortcut to go to the file or folder. Storing shortcuts in the Favorites folder gives you quick access to any file without your having to remember where the file is located. To quickly access files in the Favorites folder, click Favorites [image] in the Places Bar in the Open dialog box (File menu).

Return to Create shortcuts to files, folders, and Web pages


 Search for files

Search for files

  1. On the File menu, click Open [image] .

  2. Click Tools, and then click Find.

  3. In the Look in box, click the drive or folder you want to search.

  4. To search all subfolders of the selected folders and display the folders that contain the files that are found, select the Search subfolders check box.

  5. In the Property box, click File name.

  6. In the Condition box, click the option you want.

  7. In the Value box, type all or part of the file name.

  8. Click Add to List.

  9. Click Find Now.

Notes

  • To search more than one drive at a time, type each drive name separated by a semicolon in the Look in box. For example, type C:\;D:\.

  • You will not be able to find a file by searching the text within a Microsoft Access database or Microsoft Access project file.

  • You can also search for files using the Import and Link dialog boxes on the File menu, or the Database to Convert From, Database To Compact From, Database to Save As MDE, and Encrypt/Decrypt Database dialog boxes on the Tools menu.


 Delete a saved search

Delete a saved search

  1. On the File menu, click Open [image] .

  2. Click Tools, and then click Find.

  3. Click Open Search.

  4. Click the name of the search, and then click Delete.

Note You can also delete a saved search in the Import and Link dialog boxes on the File menu, or the Database to Convert From, Database To Compact From, Database to Save As MDE, and Encrypt/Decrypt Database dialog boxes on the Tools menu.


 Search for files by using file properties

Search for files by using file properties

  1. On the File menu, click Open [image] .

  2. Click Tools, and then click Find.

  3. In the Look in box, click the drive or folder you want to search.

    To search more than one drive at a time, type each drive name separated by a semicolon in the Look in box. For example, type C:\;D:\.

  4. To search all subfolders of the selected folders and to display the folders that contain the files that are found, select the Search subfolders check box.

  5. Under Define more criteria, specify search criteria by selecting the options you want in the Property, Condition, and Value boxes, and then click Add to List.

    Note If you are searching for an Office file other than a Microsoft Access database or Microsoft Access Project, you can also search for a phrase within the file, such as "apple pie". In the Property box, select Text or property, and in the Value box, enter the phrase in double ("") quotation marks. How to use conditions and values in a search.

  6. To create additional search criteria, click And or Or, and then repeat step 5.

  7. Select any other options you want.

    For Help on an option, click the question mark [image] and then click the option.

  8. To save the search criteria so you can use them later, click Save Search, type a name in the Name for this Search box, and then click OK.

    You can use long, descriptive search names of up to 80 characters and can include spaces.

  9. To begin the search, click Find Now.

Notes

  • You can create custom properties to search on when trying to locate a database later. How?

  • You will not be able to find a file by searching the text within a Microsoft Access database or Microsoft Access project file.

  • You can also search for files using the Import and Link dialog boxes on the File menu, or the Database to Convert From, Database To Compact From, Database to Save As MDE, and Encrypt/Decrypt Database dialog boxes on the Tools menu.


 Search for files by using saved search criteria

Search for files by using saved search criteria

You must have a saved search to use saved search criteria. How to enter and save search criteria.

  1. On the File menu, click Open [image] .

  2. Click Tools, and then click Find.

  3. Click Open Search.

  4. Click the name of the search you want to use, and then click Open.

  5. Click Find Now.

Note You can also search for files using the Import and Link dialog boxes on the File menu, or the Database to Convert From, Database To Compact From, Database to Save As MDE, and Encrypt/Decrypt Database dialog boxes on the Tools menu.


 Use file properties to locate files

Use file properties to locate files

What do you want to do?

Learn about using file properties to locate files

Document a database's characteristics and associated keywords

Create custom database properties for use in locating a file

Modify or delete custom database properties

View a list of database objects in the current database

View the attributes of a database file

Notes

  • Except for the properties on the General and Statistics tabs in the Database Properties dialog box and the properties of a data access page, file properties can also be manipulated by using Visual Basic for Applications.

  • When you are trying to locate a Microsoft Access database, Microsoft Access project, or data access page by using the Open dialog box, you can use the find criteria to specify the properties of the file you are looking for. For example, you can search for a database whose Contents property includes a table named Suppliers. Learn how to search for data files using file properties.


 Copy a file

Copy a file

  1. Click Open [image] .

  2. In the Look In box, click the drive or folder that contains the file you want to copy.

  3. In the folder list, double-click folders until you open the folder that contains the file you want.

    If you can't find the file in the folder list, you can search for it.

    How?

  4. Right-click the file you want to copy, and then click Copy on the shortcut menu.

  5. In the Look In box, click the drive or folder you want to copy the file to.

  6. In the folder list, double-click folders until you open the folder you want to copy the file to.

  7. Right-click in the folder list (make sure a file is not selected), and then click Paste on the shortcut menu.

    The Paste command is not available if a file is selected in the folder list.


 Delete a file

Delete a file

  1. Click Open [image] .

  2. In the Look In box, click the drive or folder that contains the file you want to delete.

  3. In the folder list, double-click folders until you open the folder that contains the file you want.

    If you can't find the file in the folder list, you can search for it.

    How?

  4. Right-click the file you want to delete, and then click Delete on the shortcut menu.


 Rename a file

Rename a file

  1. Click Open [image] .

  2. In the Look In box, click the drive or folder that contains the file you want to rename.

  3. In the folder list, double-click folders until you open the folder that contains the file you want.

    If you can't find the file in the folder list, you can search for it.

    How?

  4. Right-click the file you want to rename, and then click Rename on the shortcut menu.

  5. Type the new name, and then press ENTER.


 Move a file

Move a file

  1. Click Open [image] .

  2. In the Look In box, click the drive or folder that contains the file you want to move.

  3. In the folder list, double-click folders until you open the folder that contains the file you want.

    If you can't find the file in the folder list, you can search for it.

    How?

  4. Right-click the file you want to move, and then click Cut on the shortcut menu.

  5. In the Look In box, click the drive or folder you want to move the file to.

  6. In the folder list, double-click folders until you open the folder you want to move the file to.

  7. Right-click in the folder list (make sure a file is not selected), and then click Paste on the shortcut menu.

    The Paste command is not available if a file is selected in the folder list.


View all file types and file name extensions

  1. In My Computer or Windows Explorer, open the folder you want to view files in.

  2. On the View menu, click Options.

  3. To see all file types, click Show All Files on the View tab.

    To see all file name extensions in Windows 95, clear the Hide MS-DOS File Extensions For File Types That Are Registered check box on the View tab.

    To see all file name extensions in Windows 98, clear the Hide File Extensions For Known File Types check box on the View tab.

    Note The last two settings control whether or not the file extensions are displayed in the Files of Type list of the Open, Export, Import, and Link dialog boxes.


 Best place to store files

Best place to store files

The first time you open the Open and File New Database dialog boxes in Microsoft Access, the My Documents folder is the default working (or active) folder. How to change the default working folder.

My Documents folder

The My Documents folder is a good place to store Microsoft Access databases, Microsoft Access projects, data access pages, and other files you're working on, such as documents, worksheets, and presentations. To quickly access files in the My Documents folder, click My Documents [image] on the Places Bar.

Favorites folder

The Favorites folder is a good place to store shortcuts to files and folders you use often, including those in remote network locations. The original file or folder doesn't move instead, a shortcut is created to go to the file or folder. Storing shortcuts in the Favorites folder gives you quick access to any file without your having to remember where the file is located. To quickly access files in the Favorites folder, click Favorites [image] on the Places Bar. How to add a file or folder shortcut to the Favorites folder.

Web Folders

Web Folders is a good place to save data access page files for use on an Internet or intranet. These files reside on a Web server to allow others easy access to them. To quickly access files stored on a Web server, click Web Folders on the Places Bar. Learn about Web Folders.


When to use the Favorites folder and the My Documents folder

Use the Favorites folder to store shortcuts to databases you use frequently, including those in remote locations. The original file or folder doesn't move. You can use a shortcut for quick access to the file without having to remember where the file is located. For information on adding a database shortcut to the Favorites folder automatically, click [image] .

Use the My Documents folder to store all your original databases and other files, enabling you to back up just one folder. It's the default folder for new Microsoft Access databases unless you change the default. For more information on the default folder, click [image] .


Why is My Documents the default folder when I open or create a database?

In Microsoft Access, the default working folder is the My Documents folder. You can store all your files here, so you only have to back up one folder.

You can rename or move the My Documents folder, and Microsoft Windows still keeps track of it. This means that when you restart Microsoft Access, it uses the renamed My Documents folder by default, regardless of its name or location on your computer.

If you prefer, you can have Microsoft Access use a different folder entirely as the default folder. For more information, click [image] .


Set the default working folder

You can change the default working folder for all your Office programs — and for the Open Office Document button and command — by renaming the My Documents folder, moving the folder to a new location, or both. You can change the default folder for Microsoft Access-only on both Windows and Windows NT Workstation 4.0 or later.

What do you want to do?

Change the default working folder for Office

Change the default working folder for Microsoft Access only

Not sure what choice you want?


Change the default working folder for Microsoft Access only

  1. On the Tools menu, click Options, and then click the General tab.

  2. In the Default database folder box, type the path for the folder you want to display as the default working folder.

    For example, type c:\work.


Change the default working folder for Office

  1. Save and close all Office files, and then quit all Office programs.

  2. In Windows Explorer, move or copy any files you want to find quickly to the My Documents folder.

  3. To rename the My Documents folder, right-click the My Documents folder in Windows Explorer, and then click Rename on the shortcut menu. Type the new name for the folder, and then press ENTER.

    To move the My Documents folder, drag the My Documents folder to a new location in Windows Explorer.


View the printing status of the printer and files as they print

  • Double-click the printer icon next to the clock on the Windows taskbar.

    When a file is printed, the printer icon disappears.


Set the default printer

To do this procedure, you must have a printer set up. Learn how to set up a printer.

  1. On the Windows Start menu, point to Settings, and then click Printers.

  2. Right-click the icon for the printer you want to use as the default printer, and then click Set As Default on the shortcut menu.

    If there is a check mark next to this command, the printer is already set as the default printer.


Set up a new printer

  1. On the Windows Start menu, point to Settings, and then click Printers.

  2. Double-click the Add Printer icon [image].

  3. Follow the instructions in the Add Printer Wizard.

    If you want to print a test page, make sure your printer is turned on and ready to print.

Tip If you want to use a shared network printer, you can double-click the Network Neighborhood icon on the Windows desktop to set up the printer quickly. Double-click the computer that is connected to the shared printer. Click the printer icon, and then click Install on the File menu.


Databases: What they are and how they work

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


 About designing a database

About designing a database

Before you use Microsoft Access to actually build the tables, forms, and other objects that will make up your database, it is important to take time to design your database. Whether you are using a Microsoft Access database or a Microsoft Access project, good database design is the keystone to creating a database that does what you want it to do effectively, accurately, and efficiently.

Learn more about Microsoft Access databases and how they work.

Learn more about Microsoft Access projects.

Steps in designing a database

This topic provides reference information about these basic steps in designing a database:

  1. Determine the purpose of your database

  2. Determine the tables you need in the database

  3. Determine the fields you need in the tables

  4. Identify fields with unique values in each record

  5. Determine the relationships between tables

  6. Refine your design

  7. Enter data and create other database objects

  8. Use Microsoft Access analysis tools

1 Determine the purpose of your database

The first step in designing a database is to determine its purpose and how it's to be used. You need to know what information you want from the database. From that, you can determine what subjects you need to store facts about (the tables) and what facts you need to store about each subject (the fields in the tables).

Talk to people who will use the database. Brainstorm about the questions you and they would like the database to answer. Sketch out the reports you'd like it to produce. Gather the forms you currently use to record your data. Examine well-designed databases similar to the one you are designing.

Return to top

2 Determine the tables you need

Determining the tables can be the trickiest step in the database design process. That's because the results you want from your database — the reports you want to print, the forms you want to use, the questions you want answered — don't necessarily provide clues about the structure of the tables that produce them.

You don't need to design your tables using Microsoft Access. In fact, it may be better to sketch out and rework your design on paper first. When you design your tables, divide up pieces of information by keeping these fundamental design principles in mind:

  • A table should not contain duplicate information, and information should not be duplicated between tables. In this respect, a table in a relational database differs from a table in a flat-file application such as a spreadsheet.

    When each piece of information is stored in only one table, you update it in one place. This is more efficient, and it also eliminates the possibility of duplicate entries that contain different information. For example, you would want to store each customer address and phone number only once, in one table.

  • Each table should contain information about one subject.

    When each table contains facts about only one subject, you can maintain information about each subject independently from other subjects. For example, you would store customer addresses in a different table from the customers' orders, so that you could delete one order and still maintain the customer information.

Learn about tables in a Microsoft Access database and how they work. Learn about optimizing general table performance in an Access database.

Learn about optimizing performance in a Microsoft Access project.

Return to top

3 Determine the fields you need

Each table contains information about the same subject, and each field in a table contains individual facts about the table's subject. For example, a customer table may include company name, address, city, state, and phone number fields. When sketching out the fields for each table, keep these tips in mind:

  • Relate each field directly to the subject of the table.

  • Don't include derived or calculated data (data that is the result of an expression).

  • Include all the information you need.

  • Store information in its smallest logical parts (for example, First Name and Last Name, rather than Name).

Learn about available field data types in an Access database.

Compare field data types in an Access database with those in an Access project.

Return to top

4 Identify the field or fields with unique values in each record

In order for Microsoft Access to connect information stored in separate tables — for example, to connect a customer with all the customer's orders — each table in your database must include a field or set of fields that uniquely identifies each individual record in the table. Such a field or set of fields is called a primary key.

Learn about primary keys in an Access database.

Learn about primary keys in a Microsoft SQL Server database.

Return to top

5 Determine the relationships between tables

Now that you've divided your information into tables and identified primary key fields, you need a way to tell Microsoft Access how to bring related information back together again in meaningful ways. To do this, you define relationships between tables in a Microsoft Access database.

Learn more about relationships in a Microsoft SQL Server database.

You may find it useful to view the relationships in an existing well-designed database. For example, open the Northwind sample database and click Relationships on the Tools menu to see the relationships between its tables. Or you may want to view the relationships in the Northwind sample Access project and Microsoft SQL Server database.

Learn more about referential integrity.

Return to top

6 Refine your design

After you have designed the tables, fields, and relationships you need, it's time to study the design and detect any flaws that might remain. It is easier to change your database design now than it will be after you have filled the tables with data.

Use Microsoft Access to create your tables, specify relationships between the tables, and enter enough sample data in your tables so you can test your design. To test the relationships in your database, see if you can create queries to get the answers you want. Create rough drafts of your forms and reports and see if they show the data you expect. Look for unnecessary duplications of data and eliminate them. If you find problems, refine the design.

Learn more about queries in an Access database and how they work.

Learn more about working with views in a Microsoft SQL Server database.

Return to top

7 Enter data and create other database objects

When you are satisfied that the table structures meet the design principles described here, then it's time to go ahead and add all your existing data to the tables. You can then create any queries, forms, reports, data access pages, macros, and modules that you may want.

See a comparison of database objects in a Microsoft Access project and database objects in an Access database.

Learn more about importing data into an Access database.

Return to top

8 Use Microsoft Access analysis tools

Microsoft Access includes two tools that can help you to refine the design of your Microsoft Access database. The Table Analyzer Wizard can analyze the design of one table at a time, can propose new table structures and relationships if appropriate, and can divide a table into new related tables if that makes sense. For information on running the Table Analyzer Wizard, click [image] .

The Performance Analyzer can analyze your entire database and make recommendations and suggestions for improving it. The wizard can also implement these recommendations and suggestions. For information on using the Performance Analyzer, click [image] .

For additional ideas on designing a Microsoft Access database, you may want to look at the design of the Northwind sample database or of one of the databases that you can create with the Database Wizard. For information on using the Database Wizard, click [image] .

See Microsoft SQL Server documentation for additional ideas on analyzing your Microsoft SQL Server database to improve its performance.

Return to top


Create a database

What do you want to do?

Create a database by using a Database Wizard

Create a database without using a Database Wizard

Learn about creating a database by opening a data file in another file format

See an overview of what databases are and how they work

Learn about designing a database

Not sure which choice you want?


 About creating an application

About creating an application

After you become familiar with Microsoft Access and learn how to create tables, queries, forms, reports, custom command bars, and so on, you can add macros and Visual Basic for Applications code to tie these objects together in an application. An application organizes related tasks so that the user can focus on the job at hand, not on how the application works or on the program used to develop the application. For comprehensive information on creating an application, see Building Applications with Forms and Reports. You can also ask the Office Assistant about specific topics.

You can control how your application looks and behaves when it starts by setting options in the Startup dialog box (Tools menu). For example, you can indicate which form your application displays when it starts, or you can specify the text that appears in the title bar while your application is running. For more information, see Building Applications or click [image] .

If you plan to distribute your application to other users, you might want to establish security to protect the objects you have created, as well as the data in your tables. For more information on security, see Building Applications or click [image] .

After your application has been distributed, use the maintenance tools provided by Microsoft Access to periodically compact and repair the database. Be sure to provide a way for users at remote locations to do this as well. For more information, see Building Applications. For information on repairing and compacting a database, click [image] .

Note In addition to the tools and information provided by Microsoft Access to assist you with application development, Microsoft Office 2000 Developer provides tools to help you develop Microsoft Windows-compatible and Office-compatible applications. For information on what tools Microsoft Office 2000 Developer includes, click [image] .


 Display or change the general properties of a database object

Display or change the general properties of a database object

  1. Under Objects in the Database window, click the type of database object whose properties you want to change.

  2. Click the database object whose properties you want to change.

  3. Click Properties [image] on the toolbar.

To get Help on an item, click the question mark [image] and then click the item.

Notes

  • The content of the Description field in the Properties dialog box is what is displayed under Description in the Database window when you click Details [image] on the toolbar.

  • In a Microsoft Access project, you cannot change the properties of a table, view, database diagram, or stored procedure because these objects reside in the Microsoft SQL Server database. However, you can change the properties of a form, report, macro, or module, because these objects reside in the Access project itself, not in the Microsoft SQL Server database; you can also change the properties of a data access page.


 Rename, delete, copy, or move an Access database or Access project

Rename, delete, copy, or move an Access database or Access project

What do you want to do?

Rename a Microsoft Access database or Microsoft Access project

Delete an Access database or Access project

Copy or move an Access database or Access project

Important

  • If you rename, delete, copy or move a Microsoft Access database, and another database includes links to objects in that database, use the Linked Table Manager in the other database to update the link information. Otherwise, Access will produce an error when you try to use those linked objects in the other database.

  • Links to a data access page need to be updated only if you rename, delete, or move the data access page .html files. For more information, click [image] .


 Open a Microsoft Access database

Open a Microsoft Access database

  1. On the File menu, click Open [image] .

  2. Click a shortcut in the Places Bar, or, in the Look In box, click the drive or folder that contains the Microsoft Access database that you want.

  3. In the folder list, double-click folders until you open the folder that contains the database.

    If you can't find the database that you want to open, click Tools and then click Find [image] . In the Find dialog box, enter additional search criteria. For Help on an option, click the question mark [image] and then click the option. Learn more about searching for files.

  4. Do one of the following:
    • To open the database for shared access in a multiuser environment, so you and other users can read and write to the database, click Open.

    • To open the database with exclusive access, click the arrow next to the Open button, and then click Open Exclusive.

    • To open the database for read-only access so that you can view it but cannot edit it, click the arrow next to the Open button, and then click Open Read–Only.

    • To open the database for read-only access and also prevent other users from opening it, click the arrow next to the Open button, and then click Open Exclusive Read Only.

    For Help on an option in the dialog box, click the question mark [image], and then click the item.

Notes

  • To view in the Open dialog box a list of shortcuts to databases that you have opened previously, click History [image] on the Places Bar.

  • To open one of the last several databases you had open, click the file name at the bottom of the File menu. Microsoft Access opens the database with the same option settings it had the last time you opened it. If the list of recently used files isn’t displayed, click Options on the Tools menu, click the General tab, and then select the Recently used file list check box.

  • Microsoft Access can automatically create a shortcut in the Favorites folder, which you can use to open the database directly the next time. For more information, click [image] . For information on creating a shortcut manually, click [image] .

  • You can directly open a data file in an external file format such as dBASE, Paradox, Microsoft Exchange, Microsoft Excel; you can also directly open any ODBC data source, such as Microsoft SQL Server or Microsoft FoxPro. Microsoft Access automatically creates a new Access database in the same folder as the data file and adds links to each table in the external database. Learn more about importing and linking data.


 Automatically create a shortcut to an Access database or Access project in the Favorites folder

Automatically create a shortcut to an Access database or Access project in the Favorites folder

The Favorites folder stores shortcuts to Microsoft Access databases, Microsoft Access projects, folders, and other files you use frequently, including those in remote locations, so that you don't have to search for the files each time. The original file or folder doesn't move.

  1. Click Open [image] on the toolbar.

  2. To create a shortcut to a folder, subfolder, Access database, or Access project that appears in the list under the Look In box, select the file or folder, click Tools, and then click Add To Favorites.

Tip To quickly open the Favorites folder after you start Microsoft Access, in the Open dialog box, click Favorites [image] . To open a favorite file or folder, click the shortcut, and then click Open.


 Add the current Access database to the Favorites folder

Add the current Access database to the Favorites folder

You can add the current Microsoft Access database to the Favorites folder so you can open it again without having to remember the path you typed to get the file the first time.

  1. If the Web toolbar isn't displayed, on the View menu, point to Toolbars, and then click Web.

  2. On the Web toolbar, click Favorites, and then click Add to Favorites.

  3. Click Add.


Create hyperlinks or shortcuts to files, folders, and Web pages

What do you want to do?

Create a field to store hyperlinks in a Microsoft Access database

Create a column to store hyperlinks in a Microsoft Access project

Create a hyperlink on a form or data access page

Assign a hyperlink to a toolbar button or menu command

Add a folder or file shortcut to the Favorites folder

Add the current file to the Favorites folder

Not sure which choice you want?


 Open an Access database or Access project on a network by using a UNC address

Open an Access database or Access project on a network by using a UNC address

  1. On the File menu, click Open [image] .

  2. In the File name box, type the UNC address for the network share you want, and then press ENTER.

    For example, type \\Computer1\Files to open a Microsoft Access database or Microsoft Access project on the Files share of the Computer1 server.

  3. In the folder list, locate and open the Access database or Access project you want.

Tip To open an Access database or Access project on a network share you've recently opened by using a UNC address, click the arrow next to the File name box, and then click the UNC connection.


 Change the appearance of objects in the Database window

Change the appearance of objects in the Database window

  1. In the Database window, click one of the following buttons on the Database window toolbar: Large Icons [image] , Small Icons [image] , List [image] , or Details [image] .

  2. To sort the objects, on the View menu, point to Arrange Icons, and click one of the following: By Name, By Type, By Created, or By Modified.

Note In a Microsoft Access project, descriptions of tables, views, database diagrams, or stored procedures do not appear because these objects reside in the Microsoft SQL Server database. However, you can view descriptions of forms, reports, macros, and modules, because these objects reside in the Access project itself, not in the Microsoft SQL Server database; you can also view descriptions of data access pages.


 Change the default behavior for selecting or opening database objects

Change the default behavior for selecting or opening database objects

By default, you select a database object in the Database window by clicking it, and you open an object by double-clicking it. However, you can change this default behavior so that you open an object by single-clicking it and select it by resting the pointer on it.

  1. On the Tools menu, click Options.

  2. On the View tab, click Single-click open.

Tip You can also select a database object in the Database window by typing the name of the object.


 Refresh the Database window

Refresh the Database window

Refreshing the Database window ensures that the list of objects in the Object list is current.

  1. In a Microsoft Access database or Microsoft Access project, switch to the Database window if you haven’t already done so. You can press F11 to switch to the Database window from any other window.

  2. Press F5 to refresh the Database window.

Note Microsoft Access automatically refreshes the Database window when you open an Access database or Access project, or when you create a new database object in a Microsoft SQL Server database from the Access project that is connected to it.


 Show or hide shortcuts for creating new database objects

Show or hide shortcuts for creating new database objects

When you click Objects in the Database window and then click an object type, the Object list contains shortcuts that you can use to create a new database object of that type. For example, when you click Reports [image], the shortcuts Create report in Design view and Create report by using wizard appear in the Object list. You can show or hide these new object shortcuts.

  1. On the Tools menu, click Options.

  2. Click the View tab.

  3. Do one of the following:

    To display the new object shortcuts in the Database window, select the New object shortcuts check box.

    To hide the new object shortcuts, clear the New object shortcuts check box.


 Use groups to organize objects in the Database window

Use groups to organize objects in the Database window

In the Database window, you can organize different types of database objects into a group.

What do you want to do?

Learn about groups

Create a group

Delete or rename a group

Add a database object to a group

Rename or delete a database object in a group


Copy a database object

What do you want to do?

Use the Copy command to copy a database object

Use the Save As command to copy a database object

Save a copy of a database object as another object type

Not sure what you want to do?


 Delete a database object

Delete a database object

  1. Close the database object you want to delete. In a multiuser environment, confirm that all users have closed the database object.

  2. Under Objects in the Database window, click the type of database object you want to delete.

  3. Click the object in the Object list, and then press DELETE.

    Note When you delete a data access page from the current database, Microsoft Access will ask you if you want to delete the link and the page, or just the link. Deleting just the link removes the page from the current database, but it doesn't remove the page HTML file from your computer.


 Rename a database object

Rename a database object

  1. Close the database object you want to rename. In a multiuser environment, confirm that all users have closed the database object.

  2. Under Objects in the Database window, click the object type of the object you want to rename.

  3. Right-click the object, and then click Rename.

  4. Type the new name for the object following Microsoft Access object-naming rules, and then press ENTER.

Note Renaming a data access page renames the link to the HTML file, but it does not rename the HTML file itself. Use My Computer or Windows Explorer to rename the HTML file.

Learn more about saving changes to a shared Access database.


 Save a database object

Save a database object

  1. Click Save [image] on the toolbar.

  2. If you are saving a database object for the first time, type a name that follows Microsoft Access object-naming rules in the Save As dialog box, and then click OK. If you click Cancel in the Save As dialog box, the object is not saved.

Notes

  • You don't need to save new data in records. Access automatically saves a record when you do any of the following: move the focus to a different record; close the active form, datasheet, data access page, or database; or quit Access.

  • If you attempt to save a new query, and you receive an error that the name you entered already exists for another object, try using a different name. The database may contain queries that were created in Visual Basic for Applications (VBA) code with ActiveX Data Objects (ADO). Queries created with ADO do not appear in the Object list in the Database window.

  • Learn more about saving changes to a shared Access database.

  • Learn more about how database diagrams can affect saving changes to a table in a Microsoft Access project.


 View, print, output, or save the design characteristics of database objects

View, print, output, or save the design characteristics of database objects

  1. On the Tools menu, point to Analyze, and then click Documenter.

  2. Click the tab that corresponds to the type of database object you want to view or print.

    You can click the All Object Types tab to display a complete list of objects in the database.

  3. Select the objects whose definition you want to view or print.

  4. Click Options to specify which features of the selected object you want to print, and then click OK.

  5. Click OK.

  6. You can now do one of the following:
    • To print the definitions, click Print [image] on the toolbar.

      You might want to check the length of your definitions before printing them, because some definitions, particularly those for forms and reports, can be many pages long.

    • To output the definitions to an HTML file, a Microsoft Excel worksheet, a Rich Text Format file, an MS-DOS text file, or a file in Report Snapshot format, click Export on the File menu, and then complete the Export Report 'ReportName' To dialog box.


 Print a database object from a shortcut

Print a database object from a shortcut

After you create a shortcut for a table, query, form, or report, you can print the object directly from the shortcut icon.

  1. Right-click the shortcut.

  2. On the shortcut menu, click Print.

Tip You can quickly print from a shortcut by dragging the shortcut icon to a printer icon on the desktop or in the Printers folder.


 Print the datasheet of a table, query, or form

Print the datasheet of a table, query, or form

To print the entire datasheet

  1. Display the table, query, or form in Datasheet view.

  2. If your datasheet contains a subdatasheet that you also want to print, click the expand indicator(+) to the left of each row whose subdatasheet you want to expand.

    Caution If you expand all subdatasheets (click Format, point to Subdatasheet, and then click Expand All), the result might contain an unexpectedly large number of records. Do not print after expanding all subdatasheets unless you are certain that you want to print all of the records in the result.

  3. To change the settings in the Print dialog box before printing, click Print on the File menu, and then select the options you want.

    To print immediately without changing the settings in the Print dialog box, click Print [image] on the toolbar.

To print only certain records in the datasheet

  1. Display the table, query, or form in Datasheet view.

  2. Select the records you want to print.

  3. On the File menu, click Print, and then click Selected Record(s).

Notes

  • You can preview your datasheet before printing by clicking Print Preview [image] on the toolbar.

  • For information about how to quickly print the datasheet from a shortcut, click [image] .


 Create a shortcut to open a database object from the desktop or a folder

Create a shortcut to open a database object from the desktop or a folder

You can create a shortcut to open a database object in a Microsoft Access database or Microsoft Access project that is stored locally on your computer or remotely on a network file server or in a shared directory.

To create a shortcut by dragging the object

  • You can quickly create a shortcut by dragging the object from the Database window to the desktop or to a folder. Make sure the place you want to drag the shortcut to is visible. (If you previously maximized the Access window, minimize it enough to show the desktop or the folder where you want to place the shortcut.)

To create a shortcut by using the Create Shortcut command

  1. Under Objects in the Database window, click the type of database object you want to create a shortcut for.

  2. Right-click the object you want to make a shortcut for, and then click Create Shortcut.

  3. If you want the shortcut to go to a location other than the desktop, type a new path in the Location box, or click Browse to choose the location and have Access fill in the path for you. For example, you might want to store the shortcut in the Favorites folder, which stores shortcuts to items you use frequently.

  4. If you're creating a shortcut for an object in a database that is on a network, Access selects This Database Is on the Network, and fills in the network path in the Full Network Path box. If you move the database later, you can type in a new network path in this format:

    \\server\share\filename

    With the network path specified, you can, for example, send the shortcut through email so that others with access to the network can use the shortcut, too.

  5. Click OK.

When you double-click the shortcut, Access opens the database in which the object is stored and displays the object. A shortcut to a macro runs the macro, and a shortcut to a stored procedure in an Access project runs the stored procedure. To open the object in a specific view, right-click the shortcut, and then click the view you want.

Notes

  • If you have a shortcut to a database that is subsequently moved, delete the old shortcut and create a new one.

  • To delete a shortcut, click it, and then press DELETE. Deleting the shortcut does not delete the object that the shortcut opens.


 Automatically repair errors caused by renaming

Automatically repair errors caused by renaming

  1. On the Tools menu, click Options.

  2. On the General tab, do any of the following:
    • To have Microsoft Access maintain the information it needs to run Name AutoCorrect, but not take any action, select the Track name AutoCorrect info check box.

    • To have Access run Name AutoCorrect as name changes occur in the database, select the Perform name AutoCorrect check box.

    • To have Access keep a log of the changes it makes each time it runs Name AutoCorrect, select the Log name AutoCorrect changes check box. Access saves the changes in a table called Name AutoCorrect Log. Each change is a record in the Name AutoCorrect Log table.

Note Name AutoCorrect can fix all discrepancies that occur when you rename a form or other object. However, Name AutoCorrect can't repair objects in certain conditions. Learn about what Name AutoCorrect can and can't fix.


 What Name AutoCorrect fixes and doesn't fix in an Access database

What Name AutoCorrect fixes and doesn’t fix in an Access database

This topic provides reference information about:

Overview

What Name AutoCorrect repairs

What Name AutoCorrect doesn’t repair

Overview

In Microsoft Access 97 and previous versions, if you rename a field in a table, you find that the objects based on that field no longer display the data from that field. Microsoft Access 2000 automatically corrects common side effects that occur when you rename forms, reports, tables, queries, fields, text boxes or other controls in a Microsoft Access database. This feature is called Name AutoCorrect.

Whenever you open a form or other object, Access automatically looks for and fixes discrepancies between the form and the other objects that the form depends on. For example, if you open a form that is bound to a table, Access compares the date/time stamps for the table and the form. If they are different, Access performs a Name AutoCorrect.

In order to take advantage of the Name AutoCorrect feature, you must be able to save changes to the form, report, or other object that Name AutoCorrect is fixing. You can save changes to an object if you have permissions to modify the design of the object, you have write access to the database, and you have exclusive access to make changes. If you can't save the object, the fixes are not saved when you close the object. Name AutoCorrect makes the changes each time that the object is opened but can't save the changes until someone with permissions to modify the design opens and saves the object.

Name AutoCorrect is on by default in databases that were created with Access 2000. However, for databases converted to Access 2000 from previous versions, you must turn Name AutoCorrect on. How to repair renaming errors in a database automatically.

Return to top

What Name AutoCorrect repairs

Name AutoCorrect fixes all discrepancies that occur when you rename any forms, reports, tables, queries, or controls on forms and reports. If you create forms or other objects while Name AutoCorrect is turned off, then when you turn Name AutoCorrect on, Access will fix any new discrepancies as you continue working with the objects. If one of the objects already has a renaming error when you turn Name AutoCorrect on, you will have to fix references to the object manually. For forms or reports that contain Visual Basic code, Access repairs references to the form, but does not repair references to objects in the Visual Basic project.

Return to top

What Name AutoCorrect doesn’t repair

Name AutoCorrect can't repair references to renamed objects in certain situations; for example, Name AutoCorrect can't do the following:

  • Change references in an invalid SQL statement.

  • Fix references in your Visual Basic code.

  • Fix references in a linked table when the table or fields have been renamed in the back end of a front-end/back-end database.

  • Work in a replicated database. When you replicate your database, Access turns Name AutoCorrect off. You can't turn on Name AutoCorrect in a database Design Master or replica.

  • Repair references to macros in a toolbar or menu, including menu and toolbar properties and event properties that are set to macro names.

  • Work in an Microsoft Access project.

Return to top


 Back up a database

Back up a database

  1. Close the database. If you are in a multiuser environment, confirm that all users have closed the database.

  2. Using the Windows Explorer, My Computer, Microsoft Backup, the MS-DOS copy command, or other backup software, copy the database file (an .mdb file) to a backup medium of your choice.

Notes

  • If you are backing up to a floppy disk and your database file exceeds the size of the disk, you cannot use Windows Explorer or My Computer to back up your database; you must use Microsoft Backup or backup software so that you can copy the file over more than one disk.

  • You should also create a backup of the workgroup information file. If this file is lost or damaged, you won't be able to start Microsoft Access until you restore or rebuild it.

  • You can back up individual database objects by creating a blank database and then importing the objects you want from the original database.

  • You can't use the FileCopy statement in a second instance of Microsoft Access to back up a database you have open in the first instance of Microsoft Access.


Restore a database from a backup copy

  • Depending on what method was used originally to produce the backup copy, use the Windows Explorer, My Computer, Microsoft Backup, MS-DOS copy or restore commands, or other backup software to copy the backup database file to your database folder.

Caution If the existing database file in the database folder and the backup copy have the same name, restoring the backup copy may replace the existing database file. If you want to save the existing file, rename it before you copy the backup file.

For information on how to rename a database file, click [image] .


 Compact an Access database or Access project

Compact an Access database or Access project

To ensure optimal performance, compact your Microsoft Access databases and Microsoft Access projects on a regular basis. Compacting and repairing have been improved, and they are now integrated into a single process that is safer and more effective. Learn more about compacting an Access database or Access project.

What do you want to do?

Compact the current Access database or Access project

Compact an Access database or Access project that is not open

Compact an Access database or Access project automatically every time you close it


 Optimize performance

Optimize performance

Depending on your computer's configuration and your working environment, there are several things you can do that may improve the performance of Microsoft Access, your Microsoft Access database, or your Microsoft Access project.

If you are optimizing the performance of an Access database, the best place to start is with the Performance Analyzer. You can use the Performance Analyzer to analyze a whole database or just selected objects in a database. The Performance Analyzer can also make some proposed changes for you if you want.

What do you want to do?

Run the Performance Analyzer

Improve the performance of Microsoft Access and your system

Improve table performance

Improve performance of linked tables

Improve external SQL database performance

Improve performance in a multiuser environment

Improve query performance

Improve filter performance

Improve find and replace performance

Improve form and subform performance

Improve list box and combo box performance

Improve report and subreport performance

Improve data access page performance

Read about making your database an MDE file to improve performance

Improve Visual Basic for Applications performance

Optimize Microsoft Access project performance

Compact an Access database or Access project automatically when you close it


 Split a table into related tables using the Table Analyzer Wizard

Split a table into related tables using the Table Analyzer Wizard

If your Microsoft Access database has a table that contains duplicate information in one or more fields, you can use the Table Analyzer Wizard to split the data into related tables so that you can store data more efficiently. This process is called normalization.

  1. On the Tools menu, point to Analyze, and then click Table.

  2. Follow the instructions in the steps of the Table Analyzer Wizard.

You can either specify the tables that you want the wizard to create or have the wizard normalize your table for you. After you have defined the proposed new tables, the wizard helps you to reconcile data that the original table repeated inconsistently. In the last step, you can create a query to view all the information from the split tables in a single datasheet that is similar to your original table.

Note In a Microsoft Access project, the tables reside in a Microsoft SQL Server database; therefore, the Table Analyzer Wizard is not available.


Tables: What they are and how they work

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


Ways to customize a table

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


 Create a table

Create a table

Microsoft Access provides two ways to create a table. You can create a blank (empty) table for entering your own data, or you can create a table using existing data from another source.

What do you want to do?

Create all tables, forms, and reports in one operation

Choose fields for a new table from existing tables

Create tables automatically from your data

Create a table from scratch

Create a new table from existing data

Find out more about what tables are and how they work


 Open a table

Open a table

  1. In the Database window, click Tables [image] under Objects.

  2. Click the name of the table you want to open.

  3. To open the table in Design view, click Design on the Database window toolbar.

    To open the table in Datasheet view, click Open on the Database window toolbar.

Notes

  • After you've opened a table, you can easily switch between the two views by clicking the View button on the toolbar.

  • For information about creating a shortcut that opens a table directly from the desktop or a folder, click [image] .


 Switch between views of a table

Switch between views of a table

Tables have two views: Design view and Datasheet view. You use Design view to create and modify the structure of a table. You use Datasheet view to view, add, delete, and edit data in a table.

  • Click the View button on the toolbar.

The View button is a toggle button. When your table is displayed in Datasheet view, only the button to switch to Design view is displayed, and vice versa.


 Optimize general table performance

Optimize general table performance

There are several things you can do to optimize your tables. In addition to the following tips, you can use the Performance Analyzer to analyze specific tables in your database. For information on using the Performance Analyzer, click [image] .

Design tables without redundant data A well-designed database is a prerequisite for fast data retrieval and updates. If existing tables contain redundant data, you can use the Table Analyzer Wizard to split your tables into related tables to store your data more efficiently. For more information, click [image] .

Choose appropriate data types for fields You can save space in your database and improve join operations by choosing appropriate data types for fields. When defining a field, choose the smallest data type or field size that's appropriate for the data in the field. For more information, click [image] .

Create indexes for fields you sort, join, or set criteria for You can make dramatic improvements in the speed of queries by indexing fields on both sides of joins, or by creating a relationship between those fields and indexing any field used to set criteria for the query. Finding records through the Find dialog box is also much faster when searching an indexed field.

Indexes aren't appropriate in all cases, however. Indexes add to the size of the .mdb file, reduce concurrency (the ability of more than one user to modify a page at the same time) in multiuser applications, and decrease performance when you update data in fields that are indexed, or when you add or delete records. It's a good idea to experiment to determine which fields should be indexed. Adding an index may speed up a query one second, but slow down adding a row of data by two seconds and cause locking problems. Or it may add negligible gains depending on which other fields are indexed. For example, adding an index to a PostalCode field may provide very little performance gain if a CompanyName field and LastName field in the table are already indexed. Regardless of the types of queries you create, you should only index fields that have mostly unique values.

In a multiple-field index, use only as many fields in the index as necessary For more information on indexes, click [image] .


 Define validation rules to control when a record can be saved

Define validation rules to control when a record can be saved

  1. Open a table in Design view.

  2. Click Properties [image] on the toolbar to display the table's property sheet.

  3. In the ValidationRule property box, type the validation rule. Or click the Build button [image] to create the validation rule using the Expression Builder.

    For example, you could define the validation expression "[RequiredDate]<=[OrderDate]+30" to make sure that the date entered into the RequiredDate field is within 30 days of the date in the OrderDate field.

  4. In the ValidationText property box, type the message that you want Microsoft Access to display when the rule is broken.

    For example, for the validation expression "[RequiredDate]<=[OrderDate]+30," you could enter "The required date must be within 30 days of the order date."

    If you set a validation rule in a table that contains data, Microsoft Access will ask if you want to apply the new rule to existing data when you save the table.

Notes

  • You can specify only one validation expression for a table. However, if you want to specify more than one rule, you can combine expressions for the ValidationRule property setting with the And operator.

  • Record validation rules are enforced whenever you add or edit data, whether it is through table Datasheet view, a form bound to the table, an append query, an update query, Visual Basic for Applications code, or by importing data from another table.

  • You can test to see if the data in a table meets validation rules by right-clicking the title bar of table Design view, and then by clicking Test Validation Rules.


About the Table Analyzer Wizard's query

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


 Add a field to a table in Design view

Add a field to a table in Design view

  1. Open the table in Design view.

  2. To insert the field within the table, click in the row below where you want to add the field, and then click Insert Rows [image] on the toolbar.

    To add the field to the end of the table, click in the first blank row.

  3. Click in the Field Name column and type the name for the field, following Microsoft Access object-naming rules.

  4. In the Data Type column, keep the default (Text); or click in the Data Type column, click the arrow, and select the data type you want.

    For information on selecting an appropriate data type, click [image] .

  5. In the Description column, type a description of the information this field will contain. This description is displayed on the status bar when adding data to the field and is included in the Object Definition of the table. The description is optional.

  6. If you want, set field properties for the field in the bottom part of the window.

    How?

Note If this is a linked table, you can't add a new field in the current database. If the linked table is a Microsoft Access table, you must open its source database to add a field. If the linked table is from another application, you must open the source file with that application to add a field.


 What data type should I use for a field in my table?

What data type should I use for a field in my table?

Decide what kind of data type to use for a field based on these considerations:

  • What kind of values do you want to allow in the field? For example, you can't store text in a field with a Number data type.

  • How much storage space do you want to use for values in the field?

  • What types of operations do you want to perform on the values in the field? For example, Microsoft Access can sum values in Number or Currency fields, but not values in Text or OLE Object fields.

  • Do you want to sort or index a field? OLE Object fields can't be sorted or indexed.

  • Do you want to use a field to group records in queries or reports? OLE Object fields can't be used to group records.

  • How do you want to sort values in a field? In a Text field, numbers sort as strings of characters (1, 10, 100, 2, 20, 200, and so on), not as numeric values. Use a Number or Currency field to sort numbers as numeric values. Also, many date formats will not sort properly if entered in a Text field. Use a Date/Time field to ensure proper sorting.

  • View a summary of field data types available in Microsoft Access.


 Copy a field's definition in table Design view

Copy a field's definition in table Design view

  1. Open the table in Design view.

  2. Select the field(s) you want to copy.

    To select one field, click that field's row selector.

    To select a group of fields, drag through the row selectors of those fields.

  3. Click Copy [image] on the toolbar and then click in the first blank row.

  4. Click Paste [image] on the toolbar.

  5. Type a new name for the copied field.

Note This procedure only copies a field's definition; it doesn't copy any values in the field.


 Create a field for text or memos

Create a field for text or memos

  1. Open a table in Design view.

  2. To insert the field within the table, click in the row below where you want to add the field, and then click Insert Rows [image] on the toolbar.

    To add the field to the end of the table, click in the first blank row.

  3. In the Field Name column, type the name for the field, following Microsoft Access object-naming rules.

  4. In the Data Type column, click the arrow and select either Text or Memo. For information on which data type to use for different circumstances, click [image] .

  5. Set the other field properties, if desired.

    How?

Note The default field size for Text fields is 50 characters. You can change this for a particular field by setting the FieldSize property. You can change the default field size itself by clicking the Options command on the Tools menu, and then by clicking the Tables/Queries tab.


 Create a field for numbers or currency

Create a field for numbers or currency

  1. Open a table in Design view.

  2. To insert the field within the table, click in the row below where you want to add the field, and then click Insert Rows [image] on the toolbar.

    To add the field to the end of the table, click in the first blank row.

  3. In the Field Name column, type the name for the field, following Microsoft Access object-naming rules.

  4. In the Data Type column, click the arrow and select either Number or Currency. For information on which data type to use, click [image] .

  5. If you are creating a Number field, in the bottom part of the window set the FieldSize property to the size you want. For more information on field sizes, click [image] .

  6. To set a display format for your field, in the bottom part of the window click in the Format box, click the arrow, and select the format you want. You can also create a custom display format, if the predefined formats don't meet your needs. For more information, click [image] .

  7. Set the other field properties, if desired.

    How?

Note Changes made to the currency formats that are specified by double-clicking Regional Settings in Windows Control Panel will be automatically reflected in your database for Currency fields. However, this only affects the format; no conversion of currency values will be made.


 Create a field for Yes/No, True/False, and On/Off data

Create a field for Yes/No, True/False, and On/Off data

  1. Open a table in Design view.

  2. To insert the field within the table, click in the row below where you want to add the field, and then click Insert Rows [image] on the toolbar.

    To add the field to the end of the table, click in the first blank row.

  3. In the Field Name column, type the name for the field, following Microsoft Access object-naming rules.

  4. In the Data Type column, click the arrow and select Yes/No.

  5. To display True/False or On/Off instead of Yes/No (the default) in the field, in the bottom part of the window on the General tab, click in the Format box and select the format you want.

  6. Set the other field properties, if desired.

    How?


 Create a field for dates or times

Create a field for dates or times

  1. Open a table in Design view.

  2. To insert the field within the table, click in the row below where you want to add the field, and then click Insert Rows [image] on the toolbar.

    To add the field to the end of the table, click in the first blank row.

  3. Click in the Field Name column and type the name for the field, following Microsoft Access object-naming rules.

  4. In the Data Type column, click the arrow and select Date/Time.

  5. To set a display format for your field, in the bottom part of the window, click in the Format box and select the format you want. You can also create a custom display format, if the predefined formats don't meet your needs. For more information, click [image] .

  6. Set the other field properties, if desired.

    How?

Note Storing dates and times in a Date/Time field ensures that dates and times will be sorted properly. Also, changes made to the date or time formats that are specified by double-clicking Regional Settings in Windows Control Panel will be automatically reflected in Date/Time fields.


 Create a field that automatically generates numbers

Create a field that automatically generates numbers

  1. Open a table in Design view.

  2. To insert the field within the table, click in the row below where you want to add the field, and then click Insert Rows [image] on the toolbar.

    To add the field to the end of the table, click in the first blank row.

  3. In the Field Name column, type the name for the field, following Microsoft Access object-naming rules.

  4. In the Data Type column, click the arrow and select AutoNumber.

  5. To create an incrementing AutoNumber, leave the property settings in the bottom part of the window as they are (the FieldSize property is set to Long Integer and the NewValues property is set to Increment by default).

    To create a random AutoNumber, in the bottom part of the window on the General tab, set the NewValues property to Random. For more information on the types of AutoNumber fields you can create, including fields for database replication, click [image] .

  6. Set the other field properties, if desired.

    How?


Create a field that looks up or lists values in tables

Using the Lookup Wizard, you can create a field that displays either of two kinds of lists to make data entry simpler:

  • A Lookup list that displays values looked up from an existing table or query

  • A value list that displays a fixed set of values that you enter when you create the field

What do you want to do?

Create a Lookup list field in Design view

Create a Lookup list field in Datasheet view

Create a value list field in Design view

Create a value list field in Datasheet view

Not sure which choice you want?


Define or change data types

What do you want to do?

Learn what data type I should use

Change a field's data type

Create a field for dates or times

Create a field to store OLE objects (pictures, Word documents, and so on)

Create a field for Yes/No, True/False, and On/Off data

Create a field that automatically generates numbers

Create a field for numbers or currency

Create a field for text or memos

Create a field to store hyperlinks

Create a field that looks up or lists values in tables

Learn the consequences of changing a field's data type

Learn about AutoNumber fields and replication


 Create a field to store OLE objects (pictures, Word documents, and so on)

Create a field to store OLE objects (pictures, Word documents, and so on)

  1. Open a table in Design view.

  2. To insert the field within the table, click in the row below where you want to add the field, and then click Insert Rows [image] on the toolbar.

    To add the field to the end of the table, click in the first blank row.

  3. In the Field Name column, type the name for the field, following Microsoft Access object-naming rules.

  4. In the Data Type column, click the arrow and select OLE Object.

Note OLE Object fields are used to store data such as Microsoft Word or Microsoft Excel documents, pictures, sound, and other types of binary data created in other programs. OLE objects can be linked to or embedded in a field in a Microsoft Access table. You must use a control in a form or report to display the OLE object. To find out more about editing and displaying objects stored in OLE Object fields, click [image] .


 Move a field in table Design view

Move a field in table Design view

  1. Open the table in Design view.

  2. Select the field(s) you want to move.

    To select one field, click that field's row selector.

    To select a group of fields, drag through the row selectors of those fields.

  3. Click and hold down the mouse button in the row selector again. Microsoft Access displays a thin horizontal bar just above the last selected row.

  4. Drag the horizontal bar to the row just below where you want to move the fields.

Note Changing field order in table Design view changes the order in which fields are stored in the table and also changes the column order in the table's datasheet. For information on how to change only the datasheet's column order, click [image] .


 Change a field name in a table

Change a field name in a table

You can change a field name at any time without affecting the data in the field. Microsoft Access automatically fixes common side effects that occur when you make changes to a field name. For more information on how Microsoft Access updates field names, click [image] .

You can change a field name in either Design view or Datasheet view.

What do you want to do?

Change a field name in Design view

Change a field name in Datasheet view


 Delete a field from a table

Delete a field from a table

How you delete a field depends on whether you're in Design view or Datasheet view.

What do you want to do?

Delete a field from a table in Design view

Delete a field from a table in Datasheet view


 Change a field's data type

Change a field's data type

  1. If your table contains data, make a backup copy of the table before you change data types or field sizes.

  2. Open the table in Design view.

  3. Click the Data Type column of the field you want to change, click the arrow, and select the new data type.

  4. Click Save [image] on the toolbar.

Caution If the data type conversion would result in lost values, Microsoft Access displays a message telling you that errors occurred during conversion before it actually saves the changes. Click Cancel to cancel the changes. Click OK to continue and save the changes anyway.

For more information on the consequences of changing a field's data type, click [image] .

Note In large tables, changing a data type might take a long time. If you want to cancel the conversion process at any point while it is running, press CTRL+BREAK, and then click OK.


 Specify a different display name for a field (column) in Datasheet view

Specify a different display name for a field (column) in Datasheet view

  1. Open the table in Design view.

  2. In the upper portion of the window, click the field for which you want to define a different column name.

  3. In the lower portion of the window on the General tab, click the Caption property box, and then type the text for the column name. The text can contain any combination of letters, numbers, spaces, and symbols up to 255 characters in length.

Notes

  • This is useful in situations where you want the column heading to be longer or more descriptive than the actual field name. For example, you might want to name a field LName for use in Visual Basic for Applications code and expressions, but display "Last Name" as the field's column heading.

  • A field's Caption property also specifies the default text for labels attached to controls in forms and reports created with a wizard or by dragging a field from the field list.

  • If you set a field's Caption property, and later rename that field while in Datasheet view, the field's caption text will be deleted. If this happens, you can redefine the field's caption as described in this topic. You can avoid this by renaming the field in Design view.


 Specify the default control (list box, combo box, or check box) for a field

Specify the default control (list box, combo box, or check box) for a field

  1. Open the table that contains the field in Design view.

  2. Click in the Data Type column for a Text, Number, or Yes/No field.

  3. Click the Lookup tab in the lower portion of the screen.

  4. In the DisplayControl property box, click a control type in the list.

Notes

  • You can specify a default control type for Text, Number, and Yes/No fields. When you set the default control type for a field, Microsoft Access displays that control in the datasheet for the table and automatically creates that type of control whenever you add that field to a form or report. For Text and Number fields, the default control type can be a text box, combo box, or list box (forms only). For Yes/No fields, the default control type can be a check box, text box, or combo box.

  • If you want to display the field as a combo box in a table datasheet, but as a text box in a query datasheet, you can set the Lookup property for the field in query Design view in addition to the table property.


 Change the field size for Text and Number fields

Change the field size for Text and Number fields

Use this procedure to control the maximum number of characters that can be entered into a Text field, or the range and kind of numeric values that can be entered into a Number field.

  1. In table Design view, in the upper portion of the window, click the field whose FieldSize property you want to set.

  2. In the lower portion of the window on the General tab, click the FieldSize property box.

  3. For a Text field, type the maximum number of characters to allow in the field (up to 255).

    For a Number field, click the arrow and select the desired field size. For more information on field sizes for Number fields, click [image] .


 Create an input mask to control how data is entered in a field or control

Create an input mask to control how data is entered in a field or control

You can use the InputMask property to control how data is entered in a field in a table or query, or in a control on a form or a report.

What do you want to do?

Define an input mask for a field in table Design view

Define an input mask for a field in query Design view

Define an input mask for a text box or combo box in form Design view

Not sure which choice you want?


Define a default value that is automatically entered in a field or control

You can use the Default Value property of a field to specify a value that is automatically entered into that field when you add a new record.

What do you want to do?

Define a default value for a field in table Design view

Define a default value for a control on a form or data access page

Not sure which choice you want?


 Properties that control how blank fields are handled

Properties that control how blank fields are handled

You can control the way that a blank field is handled by setting different combinations of the field's Required and AllowZeroLength properties. The AllowZeroLength property is only available for Text, Memo, or Hyperlink fields. The Required property determines whether an entry must be made. If the AllowZeroLength property is set to Yes, then Microsoft Access will differentiate between two kinds of blank values: Null values and zero-length string values.

This topic provides reference information about:

The difference between Null values and zero-length strings

When to allow Null values in a field

When to allow neither Null values nor zero-length strings in a field

When to allow both Null values and zero-length strings in a field

When to allow only zero-length strings or some value in a field

Distinguishing Null values from zero-length strings

Finding zero-length strings or Null values

The difference between Null values and zero-length strings

Microsoft Access allows you to distinguish between two kinds of blank values. In some situations, a field may be left blank because the information may exist but is not currently known, or because the field doesn't apply to the record at all. For example, if a table has a Number field, you can leave the field blank if you're unsure of the customer's fax number, or whether the customer even has a fax. In this case, leaving the field blank enters a Null value, which means "I don't know." Entering a zero-length string by typing double quotation marks (" ") means "I know that there is no value."

Return to top

When to allow Null values in a field

If you want to leave a field blank and don't need to determine why the field is left blank, set both the Required and AllowZeroLength properties to No. This is the default when creating a new Text, Memo, or Hyperlink field.

Return to top

When to allow neither Null values nor zero-length strings in a field

If you never want a field to be left blank, set the Required property to Yes and the AllowZeroLength property to No.

Return to top

When to allow both Null values and zero-length strings in a field

If you want to be able to distinguish between a field that is blank because the information is unknown and a field that is blank because it doesn't apply, set the Required property to No and the AllowZeroLength property to Yes.

In this case, when adding a record, you would leave the field blank (which enters a Null value) if the information is unknown. On the other hand, you would type double quotation marks (" ") with no space between them to enter a zero-length string, indicating that the field doesn't apply to the current record.

Return to top

When to allow only zero-length strings or some value in a field

If you only want a field left blank if you know that a field isn't applicable to a record, set both the Required property and the AllowZeroLength property to Yes.

In this case, the only way to leave a field blank is to type double quotation marks with no space between them, or press the SPACEBAR to enter a zero-length string.

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

Required | AllowZeroLength | User's action | Value entered
No | No | Presses ENTER | <Null>
 |  | Presses SPACEBAR | <Null>
 |  | Types " " | (not allowed)
Yes | No | Presses ENTER | (not allowed)
 |  | Presses SPACEBAR | (not allowed)
 |  | Types " " | (not allowed)
No | Yes | Presses ENTER | <Null>
 |  | Presses SPACEBAR | <Null>
 |  | Types " " | <Zero-length string>
Yes | Yes | Presses ENTER | (not allowed)
 |  | Presses SPACEBAR | <Zero-length string>
 |  | Types " " | <Zero-length string>

Return to top

Distinguishing Null values from zero-length strings

When you view data in a field that contains both Null values and zero-length strings, the fields look the same — they contain no values. You can distinguish Null values from zero-length strings by using an expression in a query field or in the control source of an unbound control in a form, a report or a data access page. The following expression returns “Unknown” if the field contains Null and “ZLS” if the field contains a zero-length string; otherwise, the expression returns the value in that field.

=IIf(IsNull([fieldname]),”Unknown”,Format([fieldname],”@;\ZLS”))

Learn more about how to use the Format property with fields that contain Null values or zero-length strings.

Return to top

Finding zero-length strings or Null values

You can use the Find command on the Edit menu to locate Null values or zero-length strings. In Datasheet view or Form view, select the field in which you want to search. In the Find In Field box, type Null to find Null values, or type quotation marks (" ") with no space between them to find zero-length strings. In the Match box, select Whole Field, and make sure the Search Fields As Formatted check box isn't selected.

For more information on using the Find command, click [image] .

Return to top


 Set field properties to customize how data is stored, handled, or displayed

Set field properties to customize how data is stored, handled, or displayed

The properties of a field allow you to customize how that field’s data is stored, handled or displayed.

What do you want to do?

Speed up searches on fields that are searched frequently, joined in queries, or sorted

Set the maximum size for a Text field, or the number size for a Number field

Set how many decimal places to display for a Number or Currency field

Define the display format for a field, such as a date's format

Define an input mask with literal characters and blanks to fill in for data such as phone numbers, postal codes, and dates

Define a label that is different from the field name for the field's column heading in Datasheet view, and for controls in forms and reports created by dragging the field from the field list

Define a value that is automatically entered when you add a new record

Limit data entered in a field to values that meet a certain requirement

Require that data be entered in a field

Allow zero-length strings to be stored in a Text, Memo, or Hyperlink field

Read about compressing the data in a Text, Memo, or Hyperlink field

Not sure which choice you want?


 About compressing the data in a Text, Memo, or Hyperlink field

About compressing the data in a Text, Memo, or Hyperlink field

Microsoft Access 2000 uses the Unicode character-encoding scheme to represent the data in a Text, Memo, or Hyperlink field. In Unicode, each character is represented by two bytes instead a single byte.

An encoding scheme that stores each character in one byte limits you to a single code page — a numbered set containing a maximum of 256 characters. However, Unicode can support a maximum of 65,536 characters, because it represents each character as two bytes. As a result, the data in a Text, Memo, or Hyperlink field requires more storage space than it did in previous versions of Access.

You can offset this effect of Unicode character representation and ensure optimal performance by setting the Unicode Compression property of the field to Yes. This is the default when you create a new Text, Memo, or Hyperlink field. When the Unicode Compression property of a field is set to Yes, any character whose first byte is 0 is compressed when it is stored and uncompressed when it is retrieved. Because the first byte of a Latin character — a character of a Western European language such as English, Spanish, or German — is 0, Unicode character representation does not affect how much storage space is required for compressed data that consists entirely of Latin characters.

You can store in a single field any combination of characters that Unicode supports. However, if the first byte of a particular character is not 0, that character is not compressed.

Note Data in a Memo field is not compressed unless it requires 4,096 bytes or less of storage space after compression. As a result, the contents of a Memo field might be compressed in one record, but might not be compressed in another record.

Learn about Unicode support in Microsoft Office.


Define the number of decimal places to display in a field or control

What do you want to do?

Set the number of decimal places to display for a field in table Design view

Set the number of decimal places to display for a field in query Design view

Set the number of decimal places to display for a control in form Design view or report Design view

Not sure which choice you want?


 Define the data display format for a field or control

Define the data display format for a field or control

You can use the Format property to specify the data display format for a field in a table or a query, or for a control in a form or a report.

What do you want to do?

Define the data display format for a field in table Design view

Define the data display format for a field in query Design view

Define the data display format for a control on a form or report

Not sure which choice you want?


 Make a Text, Memo, or Hyperlink field accept zero-length strings

Make a Text, Memo, or Hyperlink field accept zero-length strings

  1. Open the table that includes the field in Design view.

  2. Click the field in which you want to enter a zero-length string.

  3. Make sure the AllowZeroLength field property is set to Yes.

Note Only Text, Memo, and Hyperlink fields can accept zero-length strings.


 Restrict or validate data

Restrict or validate data

You can use validation rules or input masks to control how data is entered in a field in a table or query, or in a control on a form or report. You can also use macros to perform more complex validation.

What do you want to do?

Find out more about validating or restricting data entry by using field or table properties

Find out more about validating or restricting data entry by using form properties or macros

Not sure which choice you want?


 Define validation rules to control what values can be entered into a field

Define validation rules to control what values can be entered into a field

  1. Open a table in Design view.

  2. In the upper portion of the window, click the field you want to define a validation rule for.

  3. In the lower portion of the window on the General tab, click the ValidationRule property box, and then type the validation rule, or click the Build button [image] to create the validation rule using the Expression Builder.

    For example, you could define the validation expression ">9" for a Quantity field to prevent a user from placing an order for fewer than 10 units.

  4. In the ValidationText property box, type the message that you want displayed when the rule is broken.

    For example, for the validation expression ">9", you could enter "You must order 10 or more units." To view more examples of field validation rules, click [image] .

    If you set a validation rule in a field that contains data, Microsoft Access will ask if you want to apply the new rule to existing data when you save the table.

Notes

  • Field validation rules are enforced whenever you add or edit data, whether it is through table Datasheet view, a control on a form that is bound to the field, an append query, an update query, Visual Basic for Applications code, or by importing data from another table.

  • You can test to see if the data in a table meets validation rules by right-clicking the title bar of table Design view, and then by clicking Test Validation Rules.


 Require that data be entered for a field

Require that data be entered for a field

  1. In table Design view, in the upper portion of the window, click the field that you want to require data entry for.

  2. In the lower portion of the window on the General tab, click the Required property box, and then click Yes.

    When you save changes to your table, Microsoft Access gives you the option to check to see 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 (blank) values in the field that aren't going to be changed.

Note The Required property is enforced at the table level, so if you set this property to Yes, the field must have a value in all instances in which data might be entered in the field — in the table, in forms and datasheets based on the table, when a macro or Visual Basic for Applications code sets the value of the field, or when data is imported into the table.


 What kind of primary key should I use?

What kind of primary key should I use?

The power of a relational database system such as Microsoft Access comes from its ability to quickly find and bring together information stored in separate tables using queries, forms, and reports. In order to do this, each table should include a field or set of fields that uniquely identifies each record stored in the table. This information is called the primary key of the table. Once you designate a primary key for a table, to ensure uniqueness, Microsoft Access will prevent any duplicate or Null values from being entered in the primary key fields.

There are three kinds of primary keys that can be defined in Microsoft Access: AutoNumber, single-field, and multiple-field.

AutoNumber primary keys

Single-field primary keys

Multiple-field primary keys

AutoNumber primary keys

An AutoNumber field can be set to automatically enter a sequential number as each record is added to the table. Designating such a field as the primary key for a table is the simplest way to create a primary key. If you don't set a primary key before saving a newly created table, Microsoft Access will ask if you want it to create a primary key for you. If you answer Yes, Microsoft Access will create an AutoNumber primary key. There are additional considerations if your table will be used with database replication. Learn more about Autonumber fields and replication in a Microsoft Access database.

Return to top

Single-field primary keys

If you have a field that contains unique values such as ID numbers or part numbers, you can designate that field as the primary key. If the field you select as primary key does have duplicate or Null values, Microsoft Access won't set the primary key. You can run a Find Duplicates query to determine which records contain duplicate data. If you can't readily eliminate duplicate entries by editing your data, you can either add an AutoNumber field and set it as the primary key or define a multiple-field primary key.

Return to top

Multiple-field primary keys

In situations where you can't guarantee the uniqueness of any single field, you may be able to designate two or more fields as the primary key. The most common situation where this arises is in the table used to relate two other tables in a many-to-many relationship. The Order Details table in the Northwind sample database is such a table, relating the Orders and Products tables. Its primary key consists of two fields: OrderID and ProductID. The Order Details table can list many products and many orders, but each product can only be listed once per order, so combining the OrderID and ProductID fields produces an appropriate primary key.

Each product can be listed only once per order.

Another example would be an inventory database that uses a field part number of two or more fields (part and subpart).

Note If you are in doubt about whether you can select an appropriate combination of fields for a multiple-field primary key, you should probably add an AutoNumber field and designate it as the primary key instead. For example, combining FirstName and LastName fields to produce a primary key is not a good choice, since you may eventually encounter duplication in the combination of these two fields.

For information on setting a primary key, click [image] .

Return to top


 Set or change the primary key

Set or change the primary key

  1. Open a table in Design view.

  2. Select the field or fields you want to define as the primary key.

    To select one field, click the row selector for the desired field.

    To select multiple fields, hold down the CTRL key and then click the row selector for each field.

  3. Click Primary Key [image] on the toolbar.

For more information on how to choose a primary key, click [image] .

Notes

  • You can specify a primary key for a field that already contains data, but Microsoft Access generates a message when you save the table if it finds duplicate values or Null values in the field. If you encounter this message, you have three choices: use a Find Duplicates query to locate records with duplicate values or Null values and then edit the field to remove them; choose a different field; or add an AutoNumber field and set it as the primary key. For more information on finding duplicate records, click [image] .

  • In a multiple-field primary key, field order may be important to you. The fields in a multiple-field primary key are sorted according to their order in table Design view. If you want a different order, first specify the fields for the primary key as described in the preceding procedure, and then click Indexes [image] on the toolbar to display the Indexes window and reorder the field names for the index named PrimaryKey.


 Remove the primary key

Remove the primary key

  1. If the primary key is used in a relationship, you must delete the relationship before you can remove the primary key.

    How?

  2. Open the table in Design view.

  3. Click the row selector for the current primary key and then click Primary Key [image] on the toolbar.

Note This procedure doesn't delete the field or fields that are designated as the primary key; it simply removes the primary key features from the table. In some situations, you may need to temporarily remove the primary key. For example, importing records into a table may result in some duplicate records. Until you eliminate the duplicates, you should remove the primary key. For more information on finding duplicate records, click [image] .


 Create an index to find and sort records faster

Create an index to find and sort records faster

You can index a single field or a combination of fields so that you sort and find records more quickly.

What do you want to do?

Define a single-field index

Define a multiple-field index

View or edit indexes

Not sure which choice you want?


 Delete an index

Delete an index

Indexes speed up searches, but they can also slow bulk record updates such as append queries. If you have indexed a field or fields that you don't use to search, sort, or join, and you perform operations that perform bulk record updates that you want to speed up, delete the index. Deleting an index doesn't delete the field or the data in the field.

To delete a single-field index

  1. Open the table in Design view.

  2. In the upper portion of the window, click the field whose index you want to delete.

  3. In the lower portion of the window on the General tab click in the Indexed property box, and then click No.

To delete a multiple-field index

  1. Open the table in Design view.

  2. Click Indexes [image] on the toolbar.

  3. In the Indexes window, select the rows containing the index you want to delete and press the DELETE key. This removes only the index, not the field itself.


 Prevent duplicate values from being entered in a combination of fields

Prevent duplicate values from being entered in a combination of fields

  1. Open the table in Design view.

  2. Create a multiple-field index using the fields you want to prohibit duplicate values for. Leave the Indexes window open when you have finished defining the index.

    How?

  3. In the upper portion of the Indexes window, click the new index name.

  4. In the lower portion of the Indexes window, click the Unique property box, and then select Yes.


 Prevent duplicate values from being entered into a field

Prevent duplicate values from being entered into a field

A single-field primary key prohibits duplicate values in that field to ensure that each record has a unique identifier. However, you may want to prevent duplicate values in other fields as well. For example, you might want to assign computers to employees using a serial number field for the computers.

  1. Open a table in Design view.

  2. In the upper portion of the window, click the field that you want to prohibit duplicate values for.

  3. In the lower portion of the window on the General tab, click in the Indexed property box, and then click Yes (No Duplicates).

To find out how to prevent duplicate entries in a combination of fields, click [image] .


Define or change a primary key

What do you want to do?

Set or change the primary key

Remove the primary key

Decide what kind of primary key I should use


 View or edit indexes

View or edit indexes

  1. Open the table in Design view.

  2. Click Indexes [image] on the toolbar.

  3. Change indexes or index properties as desired. To delete an index, delete its row in the Indexes window. This removes only the index, not the field itself.


 About relationships in an Access database

About relationships in an Access database

This topic provides reference information about:

Why you should define relationships

How relationships work

A one-to-many relationship

A many-to-many relationship

A one-to-one relationship

Defining relationships

Why define relationships?

After you've set up different tables for each subject in your Microsoft Access database, you need a way of telling Microsoft Access how to bring that information back together again. The first step in this process is to define relationships between your tables. After you've done that, you can create queries, forms, and reports to display information from several tables at once. For example, this form includes information from five tables:

Orders form displaying related information from five tables at once

Return to top

How do relationships work?

In the previous example, the fields in five tables must be coordinated so that they show information about the same order. This coordination is accomplished with relationships between tables. A relationship works by matching data in key fields — usually a field with the same name in both tables. In most cases, these matching fields are the primary key from one table, which provides a unique identifier for each record, and a foreign key in the other table. For example, employees can be associated with orders they're responsible for by creating a relationship between the Employees table and the Orders table using the EmployeeID fields.

EmployeeID used as primary key in Employees table and foreign key in Orders table.

Return to top

A one-to-many relationship

A one-to-many relationship is the most common type of relationship. In a one-to-many relationship, a record in Table A can have many matching records in Table B, but a record in Table B has only one matching record in Table A.

A record in Suppliers table with more than one related record in Products table

Return to top

A many-to-many relationship

In a many-to-many relationship, a record in Table A can have many matching records in Table B, and a record in Table B can have many matching records in Table A. This type of relationship is only possible by defining a third table (called a junction table) whose primary key consists of two fields — the foreign keys from both Tables A and B. A many-to-many relationship is really two one-to-many relationships with a third table. For example, the Orders table and the Products table have a many-to-many relationship that's defined by creating two one-to-many relationships to the Order Details table.

Foreign keys in Order Details table and matching primary keys in Orders table and Products table

Return to top

A one-to-one relationship

In a one-to-one relationship, each record in Table A can have only one matching record in Table B, and each record in Table B can have only one matching record in Table A. This type of relationship is not common, because most information related in this way would be in one table. You might use a one-to-one relationship to divide a table with many fields, to isolate part of a table for security reasons, or to store information that applies only to a subset of the main table. For example, you might want to create a table to track employees participating in a fundraising soccer game.

Every record in the Employees table can have only one matching record in the Soccer Players table.

Return to top

Defining relationships

You define a relationship by adding the tables that you want to relate to the Relationships window, and then dragging the key field from one table and dropping it on the key field in the other table. You can also define relationships by using the keyboard.

Drag a field from one table to the matching field in the other table.

The kind of relationship that Microsoft Access creates depends on how the related fields are defined:

  • A one-to-many relationship is created if only one of the related fields is a primary key or has a unique index.

  • A one-to-one relationship is created if both of the related fields are primary keys or have unique indexes.

  • A many-to-many relationship is really two one-to-many relationships with a third table whose primary key consists of two fields — the foreign keys from the two other tables.

For more information on how to define relationships, click [image] .

Note If you drag a field that isn't a primary key and doesn't have a unique index to another field that isn't a primary key and doesn't have a unique index, an indeterminate relationship is created. In queries containing tables with an indeterminate relationship, Microsoft Access displays a default join line between the tables, but referential integrity won't be enforced, and there's no guarantee that records are unique in either table.

Return to top

Learn more about relationships in a Microsoft Access project.


 Display the Relationships window

Display the Relationships window

  1. If you haven't already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  2. Click Relationships [image] on the toolbar.

    The Relationships window is displayed. If the relationship layout was saved previously, the saved layout is displayed. If not, the Show Tables dialog box is displayed to select tables or queries to add to the Relationships window.


 Define relationships between tables

Define relationships between tables

  1. Close any tables you have open. You can't create or modify relationships between open tables.

  2. If you haven't already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  3. Click Relationships [image] on the toolbar.

  4. If your database doesn't have any relationships defined, the Show Table dialog box will automatically be displayed. If you need to add the tables you want to relate and the Show Table dialog box isn't displayed, click Show Table [image] on the toolbar. If the tables you want to relate are already displayed, skip to step 6.

  5. Double-click the names of the tables you want to relate, and then close the Show Table dialog box.

  6. Drag the field that you want to relate from one table to the related field in the other table.

    To drag multiple fields, press the CTRL key and click each field before dragging them.

    In most cases, you drag the primary key field (which is displayed in bold text) from one table to a similar field (often with the same name) called the foreign key in the other table. The related fields don't have to have the same names, but they must have the same data type (with two exceptions) and contain the same kind of information. In addition, when the matching fields are Number fields, they must have the same FieldSize property setting. The two exceptions to matching data types are that you can match an AutoNumber field with a Number field whose FieldSize property is set to Long Integer; and you can match an AutoNumber field with a Number field if both fields have their FieldSize property set to Replication ID.

  7. The Edit Relationships dialog box is displayed. Check the field names displayed in the two columns to ensure they are correct. You can change them if necessary.

    Set the relationship options if necessary. For information about a specific item in the Relationships dialog box, click the question mark button [image], and then click the item.

  8. Click the Create button to create the relationship.

  9. Repeat steps 5 through 8 for each pair of tables you want to relate.

    When you close the Relationships window, Microsoft Access asks if you want to save the layout. Whether you save the layout or not, the relationships you create are saved in the database.

Notes

  • If you need to view all the relationships defined in the database, click Show All Relationships [image] on the toolbar. To view only the relationships defined for a particular table, click the table, and then click Show Direct Relationships [image] on the toolbar.

  • If you need to make a change to the design of a table, you can right-click the table you want to change, and then click Table Design.

  • You can create relationships using queries as well as tables. However, referential integrity isn't enforced with queries.

  • To create a relationship between a table and itself, add that table twice. This is useful in situations where you need to perform a lookup within the same table. For example, in the Employees table in the Northwind sample database, a relationship has been defined between the EmployeeID and ReportsTo fields, so that the ReportsTo field can display employee data from a matching EmployeeID.

  • You can also define a relationship by using the keyboard.


 Define a many-to-many relationship between tables

Define a many-to-many relationship between tables

  1. Create the two tables that will have a many-to-many relationship.

    How?

  2. Create a third table, called a junction table, and add fields with the same definitions as the primary key fields from each of the other two tables to this table. In the junction table, the primary key fields function as foreign keys. You can add other fields to the junction table, just as you can to any other table.

  3. In the junction table, set the primary key to include the primary key fields from the other two tables. For example, in an Order Details junction table, the primary key would be made up of the OrderID and ProductID fields.

    How?

  4. Define a one-to-many relationship between each of the two primary tables and the junction table.

    How?

  5. To add data to the tables, do one of the following:
    • Create a query that works with more than one table. For more information, click [image] .

    • Create a form that works with more than one table. For more information, click [image] .

Note In the Northwind sample database, a many-to-many relationship exists between the Orders and Products tables. One order in the Orders table can include multiple products from the Products table. In addition, a single product can appear in many orders. In the sample database, the Order Details table is a junction table between the Orders table and the Products table.


 Define the default join type for a relationship between two tables

Define the default join type for a relationship between two tables

  1. If you haven't already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  2. Click Relationships [image] on the toolbar to open the Relationships window.

  3. Double-click the middle section of a join line between two tables to open the Relationships dialog box.

  4. Click the Join Type button, and then click the desired join type.

    Option 1 defines an inner join. This is the default.

    Option 2 defines a left outer join.

    Option 3 defines a right outer join.

Note The Join Type button won't be enabled if the tables are linked tables. If the tables are in Microsoft Access format, you can open the database in which they are stored to set the join type.

Defining the join type for a relationship in the Relationships window doesn't affect the relationship itself; it sets the kind of join that will be used by default when creating queries based on the related tables. You can always override the default join type later when defining a query.

Note You can also define the default join type by using the keyboard. Learn more about join types.


 Delete a relationship

Delete a relationship

  1. Close any tables you have open. You can't delete relationships between open tables.

  2. If you haven't already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  3. Click Relationships [image] on the toolbar.

  4. If the tables whose relationship you want to delete aren't displayed, click Show Table [image] on the toolbar and double-click each table you want to add. Then click Close.

  5. Click the relationship line for the relationship you want to delete (the line will turn bold when it's selected), and then press the DELETE key.

Note You can also delete a relationship by using the keyboard.


 Edit an existing relationship

Edit an existing relationship

  1. Close any tables you have open. You can't modify relationships between open tables.

  2. If you haven't already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  3. Click Relationships [image] on the toolbar.

  4. If the tables whose relationship you want to edit aren't displayed, click Show Table [image] on the toolbar and double-click each table you want to add.

  5. Double-click the relationship line for the relationship you want to edit.

  6. Set the relationship options. For information about a specific item in the Relationships dialog box, click the question mark button [image], and then click the item.

Note You can also edit a relationship by using the keyboard.


 Print the Relationships window

Print the Relationships window

In a Microsoft Access database, you can use the Print Relationships Wizard to create a report that displays the relationships as they appear in the Relationships window.

  1. Open the Access database whose relationships you want to print.

  2. On the Tools menu, click Relationships to open the Relationships window.

  3. On the File menu, click Print Relationships.

Note You cannot print the relationships in a Microsoft Access project.

Tip The Print Relationships Wizard generates a report with the header Relationships for databasename and the date that you created the report. You can save this report for future reference.


Remove a table from the Relationships window

  • Click the table you want to remove, and then press the DELETE key.

    Microsoft Access removes the table and its relationship lines from the Relationships window. This action affects only the display of the Relationships window. The table and relationships remain in the database.


 View existing relationships

View existing relationships

  1. If you haven't already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  2. Click Relationships [image] on the toolbar.

  3. To view all the relationships defined in the database, click Show All Relationships [image] on the toolbar.

    To view only the relationships defined for a particular table, click the table, and then click Show Direct Relationships [image] on the toolbar.

Note If all of the tables related to the selected table are already displayed in the Relationships window, clicking the Show Direct Relationships button will have no effect because it only adds tables related to the current table. If you want to view only the direct relationships for one table, click Clear Layout [image] on the toolbar to remove all tables from the Relationships window (this won't delete the tables or relationships, it just removes them from the Relationships window), add the table back, and then click the Show Direct Relationships button. To add a table, click Show Table [image] on the toolbar, double-click the table, and then click Close.


 What is referential integrity?

What is referential integrity?

Referential integrity is a system of rules that Microsoft Access uses to ensure that relationships between records in related tables are valid, and that you don't accidentally delete or change related data. You can set referential integrity when all of the following conditions are met:

  • The matching field from the primary table is a primary key or has a unique index.

  • The related fields have the same data type. There are two exceptions. An AutoNumber field can be related to a Number field with a FieldSize property setting of Long Integer, and an AutoNumber field with a FieldSize property setting of Replication ID can be related to a Number field with a FieldSize property setting of Replication ID.

  • Both tables belong to the same Microsoft Access database. If the tables are linked tables, they must be tables in Microsoft Access format, and you must open the database in which they are stored to set referential integrity. Referential integrity can't be enforced for linked tables from databases in other formats.

When referential integrity is enforced, you must observe the following rules:

  • You can't enter a value in the foreign key field of the related table that doesn't exist in the primary key of the primary table. However, you can enter a Null value in the foreign key, specifying that the records are unrelated. For example, you can't have an order that is assigned to a customer that doesn't exist, but you can have an order that is assigned to no one by entering a Null value in the CustomerID field.

  • You can't delete a record from a primary table if matching records exist in a related table. For example, you can't delete an employee record from the Employees table if there are orders assigned to the employee in the Orders table.

  • You can't change a primary key value in the primary table, if that record has related records. For example, you can't change an employee's ID in the Employees table if there are orders assigned to that employee in the Orders table.

If you want Microsoft Access to enforce these rules for a relationship, select the Enforce Referential Integrity check box when you create the relationship. If referential integrity is enforced and you break one of the rules with related tables, Microsoft Access displays a message and doesn't allow the change.

You can override the restrictions against deleting or changing related records and still preserve referential integrity by setting the Cascade Update Related Fields and Cascade Delete Related Records check boxes. When the Cascade Update Related Fields check box is set, changing a primary key value in the primary table automatically updates the matching value in all related records. When the Cascade Delete Related Records check box is set, deleting a record in the primary table deletes any related records in the related table. For more information on Cascade Delete Related Records and Cascade Update Related Fields check boxes, click [image] .

For information on how to edit an existing relationship and set referential integrity, click [image] .

For information on how to define a new relationship, click [image] .


 Why should I use cascading updates or cascading deletes?

Why should I use cascading updates or cascading deletes?

For relationships in which referential integrity is enforced, you can specify whether you want Microsoft Access to automatically cascade update and cascade delete related records. If you set these options, delete and update operations that would normally be prevented by referential integrity rules are allowed. When you delete records or change primary key values in a primary table, Microsoft Access makes necessary changes to related tables to preserve referential integrity.

If you select the Cascade Update Related Fields check box when defining a relationship, any time you change the primary key of a record in the primary table, Microsoft Access automatically updates the primary key to the new value in all related records. For example, if you change a customer's ID in the Customers table, the CustomerID field in the Orders table is automatically updated for every one of that customer's orders so that the relationship isn't broken. Microsoft Access cascades updates without displaying any message.

Note If the primary key in the primary table is an AutoNumber field, setting the Cascade Update Related Fields check box will have no effect, because you can't change the value in an AutoNumber field.

If you select the Cascade Delete Related Records check box when defining a relationship, any time you delete records in the primary table, Microsoft Access automatically deletes related records in the related table. For example, If you delete a customer record from the Customers table, all the customer's orders are automatically deleted from the Orders table (this includes records in the Order Details table related to the Orders records). When you delete records from a form or datasheet with the Cascade Delete Related Records check box selected, Microsoft Access warns you that related records may also be deleted. However, when you delete records using a delete query, Microsoft Access automatically deletes the records in related tables without displaying a warning.

For information on how to edit an existing relationship and set referential integrity, click [image] .

For information on how to define a new relationship, click [image] .


 About exporting data and database objects to another database or file format

About exporting data and database objects to another database or file format

This topic provides reference information about:

What is exporting?

Exporting database objects

Mailing database objects

Exporting to a Web page

Exporting to or exchanging data with Microsoft Word

Exporting to Microsoft Excel or another spreadsheet program

Automating export operations

What is exporting?

Exporting is a way to output data and database objects to another database, spreadsheet, or file format so another database, application, or program can use the data or database objects. Exporting is similar in functionality to copying and pasting. In general, you use the Export command on the File menu to export data or database objects, but there are other commands you can use as described below. You can export data to a variety of supported databases, programs, and file formats.

Return to top

Exporting database objects

You can export most database objects from a Microsoft Access database or Microsoft Access project to another Access database or Access project.

Return to top

Mailing database objects

By using the Mail Recipient (as Attachment) command on the Send To submenu of the File command, you can e-mail the output of a database object by attaching it to an electronic mail message in several different file formats, including Microsoft Excel (.xls), Rich Text Format (.rtf), MS-DOS text (.txt), HTML (.html), IDC/HTX, ASP, or data access page.

By using the Mail Recipient command on the Send To submenu of the File command, you can also send a page as the body of an e-mail message.

To send a database object in e-mail, you need Microsoft Outlook, Microsoft Exchange, Microsoft Mail, or another electronic mail application that supports Messaging Application Programming Interface (MAPI).

Return to top

Exporting to a Web page

There are three ways you can use Microsoft Access data or database objects to create a Web page:

  • In a Web browser that supports Dynamic HTML version 4.0 or later, you can use data access pages. You do not output data access pages; you create a data access page as a database object that contains a shortcut to the location of the data access page's corresponding HTML file. Use data access pages to view, edit, update, delete, filter, group, and sort live data from either a Microsoft Access database or a Microsoft SQL Server database. Learn about creating data access pages.

  • You can output server-generated HTML files, either ASP or IDC/HTX, from tables, queries, and forms. Server-generated HTML files are displayed in a table format in a Web browser. Use server-generated HTML files when you want to use any Web browser, your data changes frequently, and you need to see live data in a table connected to an ODBC data source, but you don't need to update or interact with the data.

  • You can create output HTML files from tables, queries, forms, and reports. In a Web browser, reports display in a report format, and tables, queries, and forms display in a datasheet format. Use static HTML files when you want to use any Web browser that supports HTML version 3.2 or later and your data does not change frequently.

Return to top

Exporting to or exchanging data with Microsoft Word

There are four ways you can use Microsoft Access data with Microsoft Word:

  • In an Access database, you can use the Microsoft Word Mail Merge Wizard to create a mail merge document in Microsoft Word 2000 that links to Microsoft Access 2000 data by using the Merge It With MS Word command on the Office Links submenu of the Tools menu. Once the link is established, you can open your document in Microsoft Word at any time to print a new batch of form letters or labels using the current data in Microsoft Access.

  • For any version of Microsoft Word, you can export Microsoft Access data to a mail merge data source file that can be used with the mail merge feature of Word.

  • You can save the output of a datasheet, form, or report as a Rich Text Format (.rtf) file. A Rich Text Format file preserves formatting, such as fonts and styles, and can be opened with Microsoft Word and other Windows word-processing or desktop-publishing programs.

  • You can save the output of a datasheet, form, or report as a .rtf file and automatically load the file into Microsoft Word by using the Publish It With MS Word command on the Office Links submenu of the Tools menu.

Return to top

Exporting to Microsoft Excel or another spreadsheet program

There are three ways you can use Microsoft Access data with Microsoft Excel or another spreadsheet program:

  • You can export the datasheet as unformatted data to Microsoft Excel or another spreadsheet program.

  • You can save the output of a datasheet, form, or report directly as an Excel (.xls) file or worksheet .

  • You can save the output of a datasheet, form, or report as an Excel (.xls) file and automatically load the file into Microsoft Excel by using the Analyze It With MS Excel command on the Office Links submenu of the Tools menu.

In the latter two cases, you can preserve most formatting, such as fonts and colors. Report group levels are saved as Microsoft Excel outline levels, and a form is saved as a table of data.

Return to top

Automating export operations

To make frequent export operations more convenient, you can automate them by creating a macro or creating a Visual Basic for Applications procedure. This is useful, for example, when you export data on a regular schedule or you are building a Web site by using multiple database objects.

Return to top


 About importing and linking data and importing database objects

About importing and linking data and importing database objects

This topic provides reference information about:

The difference between importing and linking

Importing data

Linking data

Ways to import and link data

Using ODBC data sources

Unsupported programs

Automating import operations

The difference between importing and linking

Microsoft Access provides two choices for using data from an external data source. You can:

  • Import the data into a new Microsoft Access table, which is a way to convert data from a different format and copy it into Microsoft Access. You can also import database objects into the current Microsoft Access database or Microsoft Access project.

  • Link the data, which is a way to connect to data from another application without importing it so that you can view and edit the data in both the original application and in an Access database. (In previous versions of Microsoft Access, this process was referred to as attaching.)

You can import or link data from a variety of supported databases, programs, and file formats.

Return to top

Importing data

Importing data creates a copy of its information in a new table in your Access database or Access project. The source table or file is not altered in this process.

When importing data, you can't append data to existing tables (except when importing spreadsheet or text files). However, once you have imported a table, in an Access database you can perform an append query or in an Access project you can use a stored procedure to add the table's data to another table.

You can also import database objects other than tables, such as forms or reports, from another Access database or Access project.

Return to top

Linking data

In an Access database, linking data enables you to read and in most cases, update data in the external data source without importing. The external data source's format is not altered so that you can continue to use the file with the program that originally created it, but you can add, delete, or edit its data by using Microsoft Access as well. You can link a table only in an Access database, not an Access project.

Microsoft Access uses different icons to represent linked tables and tables that are stored in the current database. If you delete the icon for a linked table, you delete the link to the table, not the external table itself.

Icons for linked tables in the Database window

Return to top

Ways to import and link data

There are two ways to import or link data:

  • Open or create an Access database or create an Access project to contain the imported tables, or linked tables in the case of an Access database, and then use the Import or Link Tables commands on the Get External submenu of the File menu.

  • In an Access database, Open the external database directly, including dBASE, Paradox, Exchange, and any ODBC data source, including Microsoft SQL Server and Microsoft Visual FoxPro. Microsoft Access will automatically create a new Access database in the same folder as the external database and add links to each table in the external database.

Return to top

Using ODBC data sources

You can import or link data from ODBC databases, such as Microsoft SQL Server and Visual FoxPro, as well as other programs that provide drivers compliant with ODBC Level 1 to access their data files.

Return to top

Unsupported programs

If you have a program whose data is not stored in one of the supported external database or file formats, but the program can export, convert, or save its data as one of these formats, then you can import that data. Additionally, when you import or link an external database format, such as dBASE or Paradox, Access usually preserves indexes. For example, you can't import or link a Microsoft Works database directly, but you can export the data from Microsoft Works to a dBASE IV (.dbf) database file and then import that data into Microsoft Access to preserve field names and indexes.

In general, most unsupported programs, even those on different operating systems, can export data to a delimited or fixed-width text file, which you can then import or link from Microsoft Access, although you won't preserve indexes.

Return to top

Automating import operations

To make frequent import operations more convenient, you can automate them by creating a macro or creating a Visual Basic for Applications procedure. This is useful, for example, when you import data on a regular schedule or you have unusual or complex requirement for importing data.

Return to top


 Should I import or link a table?

Should I import or link a table?

Note You can link a table only in a Microsoft Access database, not a Microsoft Access project.

Reasons to import data into a table

If you know that you will use your data only in Microsoft Access, you should import it. Microsoft Access generally works faster with its own tables, and, if you need to, you can modify the imported table to meet your needs just like any other table that is created in Microsoft Access.

Reasons to link data from an external table

If the data that you want to use in your Access database is also being updated by a program other than Microsoft Access, you should link it. Using this approach, the current methods of updating, managing, and sharing the data can remain in place, and you can use Microsoft Access to work with the data as well. For example, you can create queries, forms, and reports that use the external data, combine external data with the data in Microsoft Access tables, and even view and edit the external data while others are using it in the original program.

You can also link tables from other Microsoft Access databases. For example, you might want to use a table from another Microsoft Access database that is shared on a network. This is particularly useful if you want to store all of your tables in one database on a network server, while keeping forms, reports, and other objects in a separate database that is copied among users of the shared database. You can easily split an existing database into two databases by using the Database Splitter subcommand on the Database Utilities command on the Tools menu. For more information, click [image] .


 Data formats Microsoft Access can export

Data formats Microsoft Access can export

Application | Version or format supported
Microsoft Access database | 2.0, 7.0/95, 8.0/97, 9.0/2000
Microsoft Access project | 2000
dBASE | III, III+, IV, and 5 7 (Requires Borland Database Engine 4.x or later)
Paradox, Paradox for Windows | 3.x, 4.x, and 5.0 8.0 (Requires Borland Database Engine 4.x or later)
Microsoft Excel | 3.0, 4.0, 5.0, 7.0/95, 8.0/97, and 9.0/2000
Microsoft Word, Rich Text Format |
Lotus 1-2-3 | .wk1 and .wk3 formats
Delimited text files | All character sets
Fixed-width text files | All character sets
HTML and IDC/HTX | 1.0 (if a list) 2.0, 3.x, 4.x (if a table or list)
Microsoft Active Server Pages |
SQL tables, Microsoft Visual FoxPro, and programs and databases that support the ODBC protocol | Visual FoxPro 3.0, 5.0, and 6.x For an up-to-date list of supported ODBC drivers, see the Microsoft Knowledge Base.


 Data sources Microsoft Access can import or link

Data sources Microsoft Access can import or link

Note You can link a table only in a Microsoft Access database, not a Microsoft Access project.

Data source | Version or format supported
Microsoft Access database | 2.0, 7.0/95, 8.0/97, 9.0/2000
Microsoft Access project | 9.0/2000
dBASE | III, III+, IV, and 5 7 (Linking (read/write) requires Borland Database Engine 4.x or later )
Paradox, Paradox for Windows | 3.x, 4.x, and 5.0 8.0 (Linking (read/write) requires Borland Database Engine 4.x or later )
Microsoft Excel spreadsheets | 3.0, 4.0, 5.0, 7.0/95, 8.0/97, and 9.0/2000
Lotus 1-2-3 spreadsheets (Linking is read-only) | .wks, .wk1, .wk3, and .wk4
Microsoft Exchange | All versions
Delimited text files | All character sets
Fixed-width text files | All character sets
HTML | 1.0 (if a list) 2.0, 3.x (if a table or list)
SQL tables, Microsoft Visual FoxPro, and data from other programs and databases that support the ODBC protocol | Visual FoxPro 2.x, 3.0, 5.0, and 6.x (import only) For an up-to-date list of supported ODBC drivers, see the Microsoft Knowledge Base.


 About ODBC data sources

About ODBC data sources

This topic provides information about the following subjects:

What is a data source?

Machine data sources

File data sources

Connect strings

What is a data source?

A data source is a source of data and the connection information needed to access that data. Examples of data sources are Microsoft Access, Microsoft SQL Server, Oracle RDBMS, a spreadsheet, and a text file. Examples of connection information include server location, database name, logon ID, password, and various ODBC driver options that describe how to connect to the data source.

In the ODBC architecture, an application (such as Access or a Microsoft Visual Basic program) connects to the ODBC Driver Manager, which in turn uses a specific ODBC driver (for example, Microsoft SQL ODBC driver) to connect to a data source (in this case, an SQL Server database). In Access, you use ODBC data sources to connect to data external to Access that do not have built-in drivers.

To connect to these data sources, you must do the following:

  • Install the appropriate ODBC driver on the computer that contains the data source.

  • Define a data source name (DSN) by using either the ODBC Data Source Administrator to store the connection information in the Windows registry or a DSN file, or a connect string in Visual Basic code to pass the connection information directly to the ODBC Driver Manager.

Return to top

Machine data sources

Machine data sources store connection information in the Windows Registry on a specific computer with a user-defined name. You can use machine data sources only on the computer they are defined on. There are two types of machine data sources — user and system. User data sources can be used only by the current user and are visible only to that user. System data sources can be used by all users on a computer and are visible to all users on the computer and system-wide services, such as Microsoft Windows NT services. A machine data source is especially useful when you want to provide added security, because only users who are logged on can view a machine data source and it cannot be copied by a remote user to another computer.

Return to top

File data sources

File data sources (also called DSN files) store connection information in a text file, not the Windows Registry, and are generally more flexible to use than machine data sources. For example you can copy a file data source to any computer with the correct ODBC driver so that your application can rely on consistent and accurate connection information to all the computers it uses. Or you can place the file data source on a single server, share it between many computers on the network, and easily maintain the connection information in one location.

A file data source can also be unshareable. An unshareable file data source resides on a single computer and points to a machine data source. You can use unshareable file data sources to access existing machine data sources from file data sources.

Return to top

Connect strings

If you are a programmer, you can define a formatted connect string in your Visual Basic code that specifies the connection information. Using a connect string avoids defining a machine or file DSN and passes the connection information directly to the ODBC Driver Manager. This is useful, for example, when you want to avoid requiring system administrators or users from first creating a DSN, or to simplify the installation of your application.

For more information about programming ODBC, see the ODBC 3.0 Programmer's Reference Manual.

Return to top

More information

Set up ODBC data sources

Return to top


 Differences between ODBC drivers and built-in drivers for external data

Differences between ODBC drivers and built-in drivers for external data

In Microsoft Access, you can import, export, or link data from a number of different database, spreadsheet, and text file formats. To do this, Access uses either a built-in driver or an ODBC driver. This topic provides reference information about:

Built-in drivers

ODBC drivers

Built-in drivers

Access contains built-in drivers that enable you to import, export, or link the following types of data: Other Microsoft Access databases, Microsoft Access projects, Paradox, dBASE, Microsoft Excel, Lotus 1-2-3 spreadsheets, Microsoft Exchange, Microsoft Outlook, fixed-width text files, delimited text files, and HTML.

More information about data sources you can import or link to.

More information about data formats you can export.

These built-in drivers are available when you use the Export command on the File menu, and the Import and Link Tables commands on the Get External Data submenu on the File menu. If a built-in driver for a type of data has been installed, that type will be available in the Save As Type box in the Export Object 'Object Name' To dialog box, or in the Files Of Type box in the Import or Link dialog boxes. All built-in drivers are installed automatically when you install Access.

Return to top

ODBC drivers

You can use ODBC drivers to connect to Microsoft SQL Server databases, Microsoft FoxPro databases, and data from other programs that provide 32-bit drivers in compliance with ODBC Level 1 to access their data files. Microsoft Access automatically installs the Microsoft SQL Server ODBC driver (Sqlsrv32.dll), the FoxPro ODBC driver (vfpodbc.dll), the Oracle ODBC driver (msorcl32.dll), and some ODBC support files (Help files and the Control Panel ODBC (32bit) icon). The ODBC Databases option is available in the Save As Type box in the Export Object 'Object Name' To dialog box and in the Files Of Type box on the Import or Link dialog boxes. Also, the ODBC (32bit) icon is available in Control Panel.

Third-party vendors may supply additional ODBC drivers and documentation that support other data formats. For more information about whether an ODBC driver is available for a particular type of data, contact the vendor of the program that produces that type of data. Access requires 32-bit ODBC drivers that are in compliance with ODBC Level 1.

Other Microsoft products and products from other vendors may also contain ODBC drivers, including drivers for the same applications listed in the section above on built-in drivers. These ODBC drivers may be installed on your computer, but Microsoft recommends you use a corresponding built-in driver when available. If you want to know whether these ODBC drivers have been tested and verified for use with Access, contact the driver vendor.

You can find more information about ODBC driver support and availability in the Microsoft Access Knowledge Base.

More information about accessing Microsoft technical resources.

Return to top


 About import/export specifications and Schema.ini files

About import/export specifications and Schema.ini files

An import/export specification contains information, such as file format, date order, or number formats, that Microsoft Access uses to import or export a fixed-width or delimited text file. An import/export specification is stored with the default name: Filename_ImportSpec or Filename_ExportSpec in the database that you import to or export from.

You create an import/export specification by using the Import Text Wizard or by using the Export Text Wizard. On the first screen of either wizard, click Advanced, define the specification, and then click Save As. Click the Specs button to select the import/export specification the next time you use either wizard.

Use an import/export specification when you want to repeatedly import to the same table, export to the same file, or automate the import or export process.

Alternatively, you can use a Schema.ini file in a Visual Basic program to provide even more control over data in the text file, such as specifying special currency formats or handling floating point data types. A schema.ini file is a text file containing entries that override default text driver settings in the Windows Registry. You store a schema.ini in the same folder as the imported or exported text file, and it must always be named schema.ini.


 Obtain optimal performance with linked tables in a Microsoft Access database

Obtain optimal performance with linked tables in a Microsoft Access database

Note You can link a table only in a Microsoft Access database, not a Microsoft Access project.

Although you can use linked tables as if they're regular Microsoft Access tables, it's important to keep in mind that they aren't actually in your Microsoft Access database. Each time you view data in a linked table, Microsoft Access has to retrieve records from another file. This can take time, especially if the linked table is on a network or in an SQL database.

If you're using a linked table on a network or in an SQL database, follow these guidelines for best results:

  • You can greatly enhance performance when opening the main database and opening tables and forms by forcing the linked database to remain open. To do this, create an empty table in the linked database, and link the table in the main database. Then use the OpenRecordset method to open the linked table. This prevents the Microsoft Jet database engine from repeatedly opening and closing the linked database and creating and deleting the associated .ldb file.

  • View only the data that you need. Don't move up and down the page unnecessarily in the datasheet. Avoid jumping to the last record in a large table. If you want to add new records to a large table, then use the Data Entry command on the Records menu to avoid loading existing records into memory.

  • Use filters or queries to limit the number of records that you view in a form or datasheet. This way, Microsoft Access can transfer less data over the network.

  • In queries that involve linked tables, avoid using functions in query criteria. In particular, avoid using domain aggregate functions, such as Dsum, anywhere in your queries. When you use a domain aggregate function, Microsoft Access retrieves all of the data in the linked table to execute the query.

  • If you often add records to a linked table, create a form for adding records that has the DataEntry property set to Yes. When you open the form to enter new data, Microsoft Access doesn't display any existing records. This property setting saves time because Microsoft Access doesn't have to retrieve all the records in the linked table.

  • Remember that other users might be trying to use an external table at the same time you are. When a Microsoft Access database is on a network, you should avoid locking records longer than necessary.


 Automate importing, exporting, or linking of data

Automate importing, exporting, or linking of data

Depending on the type of data you're working with, you can automate importing, exporting, and linking of data by carrying out the TransferDatabase, TransferSpreadsheet, or TransferText action in a macro or Visual Basic procedure.

What do you want to do?

Automate importing, exporting, or linking of data by using a macro

Automate importing, exporting, or linking of data by using Visual Basic for Applications


 Rename and set properties for linked tables in a Microsoft Access database

Rename and set properties for linked tables in a Microsoft Access database

Note You can link a table only in a Microsoft Access database, not a Microsoft Access project.

Set properties for linked tables

When you open a linked table in Design view, it looks much like a regular Microsoft Access table. Although you can't change the way the linked table and its fields are defined in the external database, you can set the properties that control the way the fields appear in Microsoft Access. Changes that you make to properties for linked tables affect only how Microsoft Access handles and displays data from the linked table; no changes are made to the source table. Field properties that you can set for linked tables are listed in the following table.

Property | Effect
Format | Controls how data is displayed in a field
DecimalPlaces | Controls the number of decimal places displayed
InputMask | Used to create a data input mask with separator characters and blanks to fill in
Caption | Changes the name used for a field's datasheet column heading, and specifies a default name to be used as a label when adding a field to a form

For information on setting field properties, click [image] .

You can't change other field properties for linked tables. However, to help make data entry more efficient and reliable, you can create forms that you use to add or edit data in your linked tables, and set properties for controls that are bound to fields from your linked tables. For example, you might want to set the DefaultValue, ValidationRule, andValidationText properties for controls in those forms.

Note If you link tables from another Microsoft Access database, the tables use the property settings from the database they are stored in. For example, if a table has validation rules in the original database, data that you enter in the linked table must follow these rules as well. If you need to change these properties, you must open the table in the database it is stored in.

Rename linked tables

You might want to rename linked tables. Because Microsoft Access table names can contain spaces and up to 64 characters , you might want to give a linked table a more descriptive name after you link it. For example, if you link a dBASE table named SLSDATA, you could rename the linked table "Sales Data 1995 (from dBASE)." Note that this won't rename the table itself, just the name Microsoft Access uses to refer to the link to that table.

Rename a linked table using the same procedure as renaming other database objects. For more information, click [image] .


 Export database objects to an existing Microsoft Access database or Microsoft Access project

Export database objects to an existing Microsoft Access database or Microsoft Access project

  1. In the Database window, click the name of the object you want to export, and then on the File menu, click Export.

  2. Click the arrow to the right of the Save In box, and select the drive or folder where the Microsoft Access database you want to export to is located.

  3. Double-click the icon for the database that you want to export.

  4. In the Export dialog box, enter a name for the new object (or accept the current name). If you are exporting a table, in Export Tables, select whether you want to export both the table's definition and data or just the table's definition. Click OK to export the object.

Notes

  • You can only export tables to earlier versions of Microsoft Access.

  • When you export a table in an Access database, Microsoft Access exports only the table data and data definitions, not its properties (including constraints, relationships, and indexes).

  • Because Microsoft Access 2000 encodes data in Unicode format, data might get converted and changed when you export a table to a previous version. Learn about converting databases.

  • You cannot export views, stored procedures, and database diagrams to a Microsoft Access project or a Access database. You cannot export queries or relationships from an Access database to an Access project.

  • You can export only one object at a time. If you want to export several objects at one time, open the database you want to export to, and then import the objects instead. For more information, click [image] .

  • When you export an object to another database, you might also want to export related objects to make it work. For example, a report might have a query as a record source, and that query might be based on a relationship between two tables.

  • When you export a data access page, you are exporting only the link to the corresponding HTML file. The HTML file remains in the same location, which means you have two data access pages pointing to the same corresponding HTML file. If you don't want this, save one of the data access pages under a different name (by using the Save As command on the File menu), enter a different file location for the new corresponding HTML file in the Save As Data Access Page dialog box, and then delete the data access page you just saved.


 Export a datasheet to a delimited or fixed-width text file

Export a datasheet to a delimited or fixed-width text file

  1. In the Database window, click the name of the table, query, view, or stored procedure you want to export, and then on the File menu, click Export.

  2. In the Save As Type box, click Text Files (*.txt;*.csv;*.tab;*.asc).

  3. Click the arrow to the right of the Save In box, and select the drive or folder to export to.

  4. In the File Name box, enter the file name, and then click Save All.

    Microsoft Access starts the Export Text Wizard.

  5. Follow the directions in the dialog boxes. Click Advanced to create or use an import/export specification.

Note To include the datasheet's font and other formatting elements that aren't included in a text file, you can save all or a selection of a datasheet as a Rich Text Format file. For information, click [image] .


 Export a datasheet to a spreadsheet file

Export a datasheet to a spreadsheet file

  1. In the Database window, click the name of the table, query, view, or stored procedure you want to export, and then on the File menu, click Export.

  2. In the Save As Type box, click the spreadsheet format you want.

  3. Click the arrow to the right of the Save In box, and select the drive or folder to export to.

  4. Double-click an existing spreadsheet, or enter a new name in the File Name box.

    Caution If you export to an existing spreadsheet file, Microsoft Access deletes and replaces the data in that spreadsheet, unless you export to a Microsoft Excel version 5.0 or later workbook, where the data is copied to the next available worksheet.

    If you selected Microsoft Excel 5-7 or Microsoft Excel 97-2000 (*.xls) in step 3 and you want to preserve fonts, preserve the displayed data from Lookup fields, and preserve field widths, select the Save Formatted check box. Saving files will take longer.

  5. Click Save All.

    Microsoft Access creates the spreadsheet file containing the data from your datasheet. Field names from the datasheet are placed in the first row of the spreadsheet.


 Export a table or query to a Microsoft Word mail merge data source file

Export a table or query to a Microsoft Word mail merge data source file

  1. In the Database window, click the name of the table or query (Microsoft Access database only) you want to export, and then on the File menu, click Export.

  2. In the Save As Type box, click Microsoft Word Merge (*.txt).

  3. Click the arrow to the right of the Save In box, and select the drive or folder to export to.

  4. In the File Name box, enter the file name, and then click Save All.

    Microsoft Access creates the data source containing the field names and all the data from your table.

Note In a Word mail merge data source, the first record in the file contains the field names and is called the header row. All succeeding records are the data rows. The field names in the header record must match the field names in the main document. If they don't match, edit the field names either in the data source (you can open the data source in Microsoft Word) or in the main document so they do match.


 Export a table or query to a Paradox or dBASE file

Export a table or query to a Paradox or dBASE file

  1. In the Database window, click the name of the table or query (Microsoft Access database only) you want to export, and then on the File menu, click Export.

  2. In the Save As Type box, click the Paradox or DBASE database format you want.

  3. Click the arrow to the right of the Save In box, and select the drive or folder to export to.

  4. In the File Name box, enter the file name, and then click Save All.

Notes

  • To export to Paradox 8.0 or dBASE 7 file format, you must have the Borland Database Engine (BDE) version 4.x or later installed on your computer. If you do not have BDE 4.x or later installed, you can obtain it by installing Paradox 8.0 or Delphi. If you have an older version of the BDE that does not support Paradox 8.0 file format, you can upgrade your engine from the Borland World Wide Web site. Alternatively, if you do not have the BDE installed on your computer, you can still export to Paradox 3.x, 4.x, and 5.0 file formats and to dBASE III, IV and 5 file formats.

  • If you export a table with table or field names that aren't allowed in the destination database, Microsoft Access adjusts the names. For example, if you export data to a dBASE table, any field names longer than 10 characters will be truncated.


 Export a table or query to an SQL database table or other ODBC data source

Export a table or query to an SQL database table or other ODBC data source

Important You cannot export a table or query to an SQL database or other ODBC data source unless you have installed the appropriate driver.

  1. In the Database window, click the name of the table or query (Microsoft Access database only) you want to export, and then on the File menu, click Export.

  2. In the Export Object Name 'Object name' In dialog box, in the Save As Type box, click ODBC Databases ().

  3. In the Export dialog box, enter a name for the file (or use the suggested name), and then click OK.

    The Select Data Source dialog box is displayed; it lists the defined data sources for any ODBC drivers installed on your computer. Click either the File Data Source or Machine Data Source tab, and then double-click the ODBC data source that you want to export to. To define a new data source for any installed ODBC driver, click New, and then follow the instructions in the Create New Data Source dialog box and the dialog boxes that follow it before continuing. Learn about data sources.

    Particular ODBC data sources have different requirements for accessing their data. For example, most require you to enter a logon ID and password. You might need to get this information from your system administrator. Enter the appropriate information in the dialog box, and then click OK.

    Microsoft Access connects to the ODBC data source and creates the new table.

Notes

  • After you export a table from a Microsoft Access database to an SQL database, you can use an SQL pass-through query to add an index to the table. For more information, click [image] .

  • If you are exporting from a Microsoft Access Project to a Microsoft SQL Server database, consider using Data Transformation Services (DTS), which can be a faster and more flexible way to export and transform data. For more information, see the Microsoft SQL Server documentation.


 Load the output of a datasheet, form, or report into Microsoft Excel

Load the output of a datasheet, form, or report into Microsoft Excel

  1. In the Database window, click the name of the datasheet, form, or report you want to save and load into Microsoft Excel. To save a selection of a datasheet, open the datasheet, and then select the portion of the datasheet before continuing.

  2. On the Tools menu, point to Office Links, and then click Analyze It With MS Excel.

    The output is saved as a Microsoft Excel file (.xls) in the default database folder. Microsoft Excel automatically starts and opens it.


 Load the output of a datasheet, form, or report into Microsoft Word

Load the output of a datasheet, form, or report into Microsoft Word

  1. In the Database window, click the name of the datasheet, form, or report you want to save and load into Microsoft Word. To save a selection of a datasheet, open the datasheet and select the portion of the datasheet before continuing.

  2. On the Tools menu, point to Office Links, and click Publish It With MS Word.

The output is saved as a Rich Text Format (.rtf) file in the default database folder. Microsoft Word automatically starts and opens it.


 Save an object's output as a Microsoft Excel or Rich Text Format file

Save an object's output as a Microsoft Excel or Rich Text Format file

  1. In the Database window, click the name of the object you want to save. To save a selection of a datasheet, open the datasheet and select the portion of the datasheet before continuing.

  2. On the File menu, click Export.

  3. In the Save As Type box, click Microsoft Excel 5-7 (*.xls), Microsoft Excel 97-2000 (*.xls), or Rich Text Format (*.rtf).

  4. Click the arrow to the right of the Save In box, and select the drive or folder to save to.

  5. In the File Name box, enter a name for the file (or use the suggested name).

  6. If you are saving as Microsoft Excel 5-7, Microsoft Excel 97, or Microsoft Excel 2000, select the Save Formatted check box. If you are saving the object in Rich Text Format, the Save Formatted check box is selected automatically.

  7. Click Save All to save the entire datasheet or Save Selection if you selected a portion of the datasheet in Step 1.


 Merge data from a table or query by using the Microsoft Word Mail Merge Wizard

Merge data from a table or query by using the Microsoft Word Mail Merge Wizard

Note You can use the Microsoft Word Mail Merge Wizard only in a Microsoft Access database, not a Microsoft Access project.

  1. In the Database window, click the name of the table or query (Access database only) you want to export, and then on the Tools menu, point to Office Links and click Merge It With MS Word.

  2. Follow the instructions in the Microsoft Word Mail Merge Wizard.

  3. In the Microsoft Word window, click Insert Merge Field to insert the desired fields into the document.

Note You can also begin the operation of merging data into form letters from within Microsoft Word. For more information, see Microsoft Word Help.


 Export a datasheet to server-generated HTML format

Export a datasheet to server-generated HTML format

  1. In the Database window, click the name of the table, query, or form, you want to export, and then on the File menu, click Export.

  2. In the Save As Type box, click Microsoft IIS 1-2 (*.htx;*.idc) or Microsoft Active Server Pages (*.asp) depending on which server-generated HTML output format you want. Learn about server-generated HTML.

  3. Click a shortcut on the Places Bar or click the arrow to the right of the Save In box and select the drive or folder to export to.

  4. In the File Name box, enter the file name.

  5. Click Save.

  6. Enter the appropriate information in the Microsoft Active Server Pages Output Options or HTX/IDC Output Options dialog boxes:

    In the HTML Template box, enter the location of an HTML template. Learn about an HTML Template file.

    In the Data Source Name box, enter the name of the ODBC data source that you will connect to when the server-generated HTML files are processed on the Web server. Learn about ODBC data sources.

    For a Microsoft Access database, in the User to Connect As and Password for User boxes, enter a user-level security username and password to allow users access to the Access database from the Web page. If you do not enter a username or password, the default username is Admin, and no password is used. Learn about user-level security.

    For a Microsoft Access project, in the Username and Password boxes, enter a database username and password to allow users to access the Microsoft SQL Server database from the Web page. If you do not enter a username or password, the default username is Sa and no password is used. Learn about SQL Server database security.

Once you have output a datasheet to ASP or IDC/HTX output format, you need to publish the files to make them available on the World Wide Web. Learn about publishing server-generated HTML files to a Web server.

Notes

  • If the datasheet contains a parameter query, Microsoft Access simulates the Enter Parameter Value dialog box by creating an additional HTML parameter page that contains an HTML form text box control for entering the parameter value, and a button for running the query. You must explicitly define the parameter data types when you create the parameter query. You must also display this HTML parameter Web page before you display the datasheet Web page. During the export operation, Microsoft Access executes the query and displays the Enter Parameter Value dialog box, but you can just click OK because the input is ignored.

  • Fields with a Hyperlink data type are output as strings using the following hyperlink address format: displaytext#address#subaddress#screentip. Although you cannot click the string in a Web browser to follow the hyperlink address, you can copy and paste the address portion into the Address Bar of the Web browser.

  • A datasheet with many records may take a long time to output and display through a Web browser. Consider reducing the size of the datasheet by using criteria such as a date field or by using a parameter query.


 Export a datasheet to static HTML format

Export a datasheet to static HTML format

  1. In the Database window, click the name of the table, query, or form, you want to export, and then on the File menu, click Export.

  2. In the Save As Type box, click HTML Documents (*.html;*.htm).

  3. Click a shortcut on the Places Bar or click the arrow to the right of the Save In box and select the drive or folder to export to.

  4. In the File Name box, enter the file name.

  5. Select the Save Formatted check box to: save the table, query, or form in a format similar to its appearance in Datasheet view, enable the AutoStart check box, and display the HTML Output Options dialog box after you click Save in step 6.

  6. Select AutoStart if you want to display the results in your default Web browser.

  7. Click Save.

  8. If you selected Save Formatted in step 5, the HTML Output Options dialog box is displayed. In the HTML Template box, you can enter the location of an HTML template. Learn about HTML Template files.

Once you have output a datasheet to an HTML file, you need to publish it to make it available on the World Wide Web. Learn about publishing static HTML files to a Web server.

Notes

  • If the datasheet contains a parameter query, Microsoft Access first prompts you for the parameter values, then exports the results.

  • Fields with a Hyperlink data type are output as hyperlink addresses by using <A HREF> HTML tags.

  • If you selected Save Formatted in step 5, the HTML table simulates the appearance (including color, font, and alignment) of the datasheet.

  • Although a default theme is not applied when you export the datasheet, you can apply a theme by creating a data access page from an existing Web page (in this case, the static HTML file you just created), applying a theme in page Design view, and then saving the page. Learn about using themes.

  • A datasheet with many records may take a long time to output and display through a Web browser. Consider reducing the size of the datasheet by using criteria such as a date field, or by using a parameter query.


 Export a report to static HTML format

Export a report to static HTML format

  1. In the Database window, click the name of the report you want to export, and then on the File menu, click Export.

  2. In the Save As Type box, click HTML Documents (*.html;*.htm).

  3. Click a shortcut on the Places Bar or click the arrow to the right of the Save In box and select the drive or folder to export to.

  4. In the File Name box, enter the file name.

  5. Select the AutoStart check box to display the results in your default Web browser.

  6. Click Save.

    In the HTML Template box of the HTML Output Options dialog box, enter the location of an HTML template. If you do not specify an HTML template file containing navigation tokens, Microsoft Access provides a default navigation scheme. Learn about an HTML Template file.

Once you have output a report to an HTML file, you need to publish it to make it available on the World Wide Web. Learn about publishing static HTML files to a Web server.

Notes

  • Microsoft Access outputs a report, unlike a datasheet, as multiple HTML files, with one file per printed page. The file names are created by using the object name and a suffix; for example, Products.html, ProductsPage2.html, ProductPage3.html, and so on.

  • If the report contains a parameter query, Microsoft Access first prompts you for the parameter values, then exports the results.

  • Fields with a Hyperlink data type are output as hyperlink addresses by using <A HREF> HTML tags.

  • Most controls and features of a report, including subreports, are supported except for the following: lines, rectangles, and OLE objects. However, you can use an HTML template file to include images in a report header or report footer.

  • Although a default theme is not applied when you export the report, you can apply a theme by creating a data access page from an existing Web page (in this case, the static HTML file you just created), applying a theme in page Design view, and then saving the page. Learn about using themes.

  • Microsoft Access provides several ways to display report information in a Web browser in addition to static HTML reports. You can display a report snapshot on a Web page, and you can create a grouped data access page. However, you cannot output a report to server-generated HTML format.


 About HTML template files

About HTML template files

You can use one or more HTML template files to enhance the appearance, consistency, and navigation of your static HTML and server-generated HTML files. For example, you might want to include a company logo in the header section, a company-approved background image in the body section, and your own navigation buttons in the footer section of a static HTML report.

An HTML template is a text file that includes HTML tags and tokens that are unique to Microsoft Access. These tokens indicate where to insert output and other information in the static HTML or server-generated HTML files. See an example of an HTML template file.

When you output a table, query, form, or report, and you specify an HTML template file in the associated Output Options dialog box, Microsoft Access merges the HTML template file with the .html, .asp, and .htx output files by replacing the tokens with the following.

HTML template token | Replacement
<!--AccessTemplate_Title--> | The name of the table, query, form, or report placed in the title bar of the Web browser
<!--AcessTemplate_Body--> | The output of the table, query, form, or report
<!--AccessTemplate_FirstPage--> | An HTML anchor tag that links to the first page of a report
<!--AccessTemplate_PreviousPage--> | An HTML anchor tag that links to the page previous to the current report page
<!--AccessTemplate_NextPage--> | An HTML anchor tag that links to the next page after the current report page
<!--AccessTemplate_LastPage--> | An HTML anchor tag that links to the last page of a report
<!--AccessTemplate_PageNumber--> | The current page number


 Import database objects from another Microsoft Access database or Microsoft Access project

Import database objects from another Microsoft Access database or Microsoft Access project

  1. Open the database or switch to the Database window for the open database.

  2. On the File menu, point to Get External Data, and then click Import.

  3. In the Files Of Type box, make sure Microsoft Access (*.mdb;*.adp;*.mdw;*.mda;*.mde;*.ade) is selected.

  4. Click the arrow to the right of the Look In box, select the drive and folder where the Microsoft Access database (.mdb) or Microsoft Access project (.adp) that you want to import from is located, and then double-click the database's icon.

  5. In the Import Objects dialog box, click the tab for the kind of object that you want to import, and then click each object that you want to import, or click Select All to import all objects of the desired type. Repeat this step for each kind of object that you want to import.

    If you want to import just the tables' definitions (not the datathat they contain), click Options, and thenunder Import Tables, click Definition Only.

    In an Access database, if you're importing select queries, and you want to import them as tables (for example, to create a read-only database), click Options, and thenunder Import Queries, click As Tables. Action queries import as queries no matter how this option is set.

    If you want to include relationships (Access database only), custom menus and toolbars, or import/export specifications (Access database only), click Options, and then, under Import, select the items you want included. Microsoft Access won't import a toolbar, menu bar, or shortcut menu if it has the same name as one in the Access database or Access project that you're importing to.

Notes

  • You cannot import views, stored procedures, or database diagrams from an Access project to an Access database. You cannot import queries or relationships from an Access database to an Access project.

  • When you import a data access page, you are only importing the link to the corresponding HTML file. The HTML file remains in the same location, which means that you have two pages pointing to the same corresponding HTML file. If you don't want this, save one of the pages under a different name (using the Save As command on the File menu), enter a different file location for the new corresponding HTML file in the Save As Data Access Page dialog box, and then delete the page that you just saved.

  • When you import an object from another database, you may also want to import related objects to make it work. For example, a report may have a query as a record source, and that query may be based on a relationship between two tables.

  • Although you can import tables from an Access project to an Access database, you may find it more efficient to import the table from Microsoft SQL Server. If you are importing tables from one Access project to another, consider using Data Transformation Services (DTS), which can be a faster and more flexible way to import and transform data. For more information, see the Microsoft SQL Server documentation.

  • When you import a table into an Access project, Microsoft Access only imports the table data and data definitions, not its properties, including constraints, relationships, and indexes.

  • Although you normally use the Convert Database command on the Database Utilities submenu of the Tools menu to convert a prior version of a Microsoft Access database, you can also convert a prior version by importing its database objects. This is useful if you only need to convert some of the database objects, or if you want to automate the conversion process in Visual Basic by using the CreateDatabase and TransferDatabase methods.


 Import or link tables from another Microsoft Access database or Microsoft Access project

Import or link tables from another Microsoft Access database or Microsoft Access project

Note You can link a table only in a Microsoft Access database, not a Microsoft Access project.

  1. Open a database, or switch to the Database window for the open database.

  2. To import tables, on the File menu, point to Get External Data, and then click Import.

    To link tables, on the File menu, point to Get External Data, and then click Link Tables.

  3. In the Import (or Link) dialog box, in the Files Of Type box, make sure that Microsoft Access (*.mdb;*.adp;*.mdw;*.mda;*.mde;*.ade) is selected.

  4. Click the arrow to the right of the Look In box, select the drive and folder where the Access database (.mdb) or Access project (.adp) that you want to import or link is located, and then double-click the database's icon.

    Important If you link to a file on a local area network, make to use a universal naming convention (UNC) path, instead of relying on the drive letter of a mapped network drive in Windows Explorer. A drive letter can vary on a computer or may not always be defined, whereas a UNC path is a reliable and consistent way for Microsoft Access to locate the data source that contains the linked table.

  5. In the Import Objects dialog box, click each table that you want to import or link.

    If you're importing, and you want to import just the selected tables' definitions (not the data they contain), click Options, and then under Import Tables, click Definition Only. Learn about importing other database objects.

Notes

  • If you import a table that is already linked, then Microsoft Access does not import the data; instead, it links the table to its data source (in effect, copies the link information).

  • Although you can import tables from an Access project to an Access database, you might find it more efficient to import the table from Microsoft SQL Server. If you are importing tables from an Access project into an Access project, consider using Data Transformation Services (DTS), which can be a faster and more flexible way to import and transform data. For more information, see the Microsoft SQL Server documentation.

  • When you import a table into an Access project, Microsoft Access only imports the table data and data definitions, not its properties (including constraints, relationships, and indexes).

  • If the database that you want to import or link has a database password, then you must provide the password before you can continue. Linking tables from such a database may have unforeseen consequences. For more information, click [image] .

  • If you link two tables from the same Access database, then any relationship that was established between the tables in the other database remains in effect.

  • If you import a table that contains Lookup fields into an Access database, then you should also import the tables or queries that the Lookup fields refer to. If you don't do this, when you open the imported table in Datasheet view, Microsoft Accesswill display an error message for each missing table or query. To correct this problem, import the missing tables or queries. If you can't or don't want to import the missing tables or queries, open the imported table in Design view, click on a Lookup field that refers to a missing table or query, click the Lookup tab, and then set the DisplayControl property to Text Box. Repeat this procedure for each Lookup field that refers to a missing table or query.


 Import a Microsoft Works database

Import a Microsoft Works database

You can't import a Microsoft Works database (.wdb) directly into Microsoft Access. You must first use Microsoft Works to save the file to one of the file formats that Microsoft Access can import.

  1. Open the database by using Microsoft Works.

  2. On the File menu, click Save As.

  3. In the Save As Type box, select dBASE IV, and then click OK.

  4. Import the dBASE IV .dbf file that you created in step 3 into Microsoft Access.

    How?


 Import or link a delimited or fixed-width text file

Import or link a delimited or fixed-width text file

Note You can link a table only in a Microsoft Access database, not a Microsoft Access project.

Important Before you import or link data from a delimited text file or fixed-width text file, make sure that the file has the same type of data in each field and the same fields in every row.

  1. Open a database, or switch to the Database window for the open database.

  2. To import data, on the File menu, point to Get External Data, and then click Import.

    To link data, on the File menu, point to Get External Data, and then click Link Tables.

  3. In the Import (or Link) dialog box, in the Files Of Type box, select Text Files (*.txt;*.csv;*.tab;*.asc).

  4. Click the arrow to the right of the Look In box, select the drive and folder where the file is located, and then double-click its icon.

    Important If you link to a file on a local area network, make sure that you use a universal naming convention (UNC) path, instead of relying on the drive letter of a mapped network drive in Windows Explorer. A drive letter can vary on a computer, or it may not always be defined; whereas, a UNC path is a reliable and consistent way for Microsoft Access to locate the data source that contains the linked table.

  5. Follow the directions in the Import Text Wizard dialog boxes. Click Advanced to create or use an import/export specification.

Notes

  • Although you usually create a new table in Microsoft Access for the data, you can append the data to an existing table as long as the first row of your text file contains matching field names.

  • If importing a text file takes an unexpectedly long time, it might be because many errors are occurring. To cancel importing, press CTRL+BREAK.

  • In a fixed-width text file, you can ignore fields at the end of a record that contain no data. In addition, the last field with data in the record can be less than the maximum width.

  • If all the records in a fixed-width text file are the same length, there can be an embedded row separator (such as a carriage return and linefeed) in the middle of a record. If the records aren't all the same length, embedded row separators should not be used because Microsoft Access will treat the embedded row separator as the end of the record.


 Import or link data from a spreadsheet

Import or link data from a spreadsheet

Note You can link a table only in a Microsoft Access database, not a Microsoft Access project.

Before you proceed, make sure that the data in the spreadsheet is arranged in an appropriate tabular format, and the spreadsheet has the same type of data in each field (column) and the same fields in every row.

  1. Open a database, or switch to the Database window for the open database.

  2. To import a spreadsheet, on the File menu, point to Get External Data, and then click Import.

    To link a spreadsheet, on the File menu, point to Get External Data, and then click Link Tables.

  3. In the Import (or Link) dialog box, in the Files Of Type box, select Microsoft Excel (*.xls) or Lotus 1-2-3 (*.wk*).

  4. Click the arrow to the right of the Look In box, select the drive and folder where the spreadsheet file is located, and then double-click its icon.

    Important If you link to a file on a local area network, make sure that you use a universal naming convention (UNC) path, instead of relying on the drive letter of a mapped network drive in Windows Explorer. A drive letter can vary on a computer, or it may not always be defined; whereas, a UNC path is a reliable and consistent way for Microsoft Access to locate the data source that contains the linked table.

  5. Follow the directions in the Import Spreadsheet Wizard dialog boxes. If you are importing from a Microsoft Excel version 5.0 or later workbook, then you can import from one worksheet within a workbook. You cannot import from any other multiple-spreadsheet files, such as Microsoft Excel version 4.0 workbooks or Lotus notebooks. To import from these files, you must first save each spreadsheet as an individual file.

Notes

  • You can import or link all the data from a spreadsheet, or just the data from a named range of cells. Although you normally create a new table in Microsoft Access for the data, you can also append the data to an existing table as long as your spreadsheet column headings match the table's field names.

  • If importing a spreadsheet takes an unexpectedly long time, it might be because many errors are occurring. To cancel importing, press CTRL+BREAK.

  • Microsoft Access attempts to assign the appropriate data type to imported fields, but you should check your fields to make sure that they are set to the data type you want. For example in an Access database, a phone number or postal code field might be imported as a Number field, but should be changed to a Text field in Microsoft Access because it is unlikely that you will perform any calculations on these types of fields. You should also check and set field properties, such as formatting, as necessary.

  • You can import data from other programs' spreadsheets, as long as they are in the Microsoft Excel or Lotus 1-2-3 format.


 Import or link data from Microsoft Outlook or Microsoft Exchange

Import or link data from Microsoft Outlook or Microsoft Exchange

Note You can link data only in a Microsoft Access database, not a Microsoft Access project.

  1. Open a database, or switch to the Database window for the open database.

  2. To import data, on the File menu, point to Get External Data, and then click Import.

    To link data, on the File menu, point to Get External Data, and then click Link Tables.

  3. In the Import (or Link) dialog box, in the Files Of Type box, select either Outlook() or Exchange().

  4. Follow the directions in the Exchange/Outlook Wizard dialog boxes.

Notes

  • You must have Microsoft Outlook, Outlook Express, or Microsoft Exchange installed on your computer to run the Exchange/Outlook Wizard.

  • You can use the Exchange/Outlook Wizard to link to your Microsoft Outlook Contacts folder and then create form letters and mailing labels by merging the data using the Microsoft Word Mail Merge Wizard.


 Import or link dBASE files

Import or link dBASE files

Note You can link a table only in a Microsoft Access database, not a Microsoft Access project.

  1. Open a database, or switch to the Database window for the open database.

  2. To import files, on the File menu, point to Get External Data, and then click Import.

    To link files, on the File menu, point to Get External Data, and then click Link Tables.

  3. In the Import (or Link) dialog box, in the Files Of Type box, select one of the dBASE file types.

  4. Click the arrow to the right of the Look In box, select the drive and folder where the .dbf file is located, and then double-click its icon.

    Important If you link to a file on a local area network, make sure that you use a universal naming convention (UNC) path, instead of relying on the drive letter of a mapped network drive in Windows Explorer. A drive letter can vary on a computer or may not always be defined, whereas a UNC path is a reliable and consistent way for Microsoft Access to locate the data source that contains the linked table.

    • If you're importing, Microsoft Access creates a table named after the file that you selected, and then imports the data from the .dbf file. Go to step 7.

    • If you're linking, Microsoft Access displays a dialog box where you can associate dBASE index files. Go to step 5.
  5. Double-click each dBASE index (.ndx or .mdx) file that you want to use, and then click Close. If there are no indexes, click Cancel to continue.

  6. In the Select Unique Record Identifier dialog box, select an index that uniquely identifies each record. This index must contain no duplicate values, or Microsoft Access might not be able to properly update data in queries with joins.

  7. If you want to import or link another dBASE file, repeat steps 4 through 6.

Notes

  • To link (read/write) a dBASE 7 table, you must have the Borland Database Engine (BDE) version 4.x or later installed on your computer. If you do not have BDE 4.x or later installed, you can obtain it by installing dBASE 7 or Delphi. If you have an older version of the BDE that does not support dBASE 7 file format, then you can upgrade your engine from the Borland World Wide Web site. Alternatively, if you do not have the BDE installed on your computer, you can still link to dBASE III, IV and 5.0 file format.

  • After importing or linking a .dbf or .dbc file, you can set field properties for the table. If you import a .dbf or .dbc file, you might also want to set a primary key for the table. For more information, click [image] .

  • If you link a .dbf file and associate an index (.ndx or .mdx) file, then Microsoft Access needs the index file to open the linked table. If you delete or move dBASE index files or the information (.inf) file that Microsoft Access creates, you won't be able to open the linked table.

  • When you use Microsoft Access to update the data in your .dbf file, Access updates the index files to reflect your changes. If you use dBASE to update data, then you must update the associated indexes within dBASE as well. Microsoft Access can't use a linked table if the indexes that you specified aren't current.

  • If your dBASE tables are stored on a read-only drive or CD-ROM, Microsoft Access can't create an .inf file in the same folder as the .dbf files. To link a table on a read-only drive, place the .inf file on a read/write drive. You can specify the path of the .inf file in the Windows Registry. For more information, click [image] .


 Import or link Paradox tables

Import or link Paradox tables

Note You can link a table only in a Microsoft Access database, not a Microsoft Access project.

  1. Open a database, or switch to the Database window for the open database.

  2. To import tables, on the File menu, point to Get External Data, and then click Import.

    To link tables, on the File menu, point to Get External Data, and then click Link Tables.

  3. In the Import (or Link) dialog box, in the Files Of Type box, select Paradox (*.db).

  4. Click the arrow to the right of the Look In box, select the drive and folder where the .db file is located, and then double-click its icon.

    Important If you link to a file on a local area network, make sure that you use a universal naming convention (UNC) path, instead of relying on the drive letter of a mapped network drive in Windows Explorer. A drive letter can vary on a computer or may not always be defined, whereas a UNC path is a reliable and consistent way for Microsoft Access to locate the data source that contains the linked table.

  5. If the Paradox table you select is encrypted, Microsoft Access prompts you for the password. Type the password for the Paradox table, and then click OK.

  6. If you want to import or link another Paradox table, repeat steps 2 through 5. When you have finished importing or linking, click Close.

Notes

  • To link (read/write) a Paradox 8.0 table, you must have the Borland Database Engine (BDE) version 4.x or later installed on your computer. If you do not have BDE 4.x or later installed, you can obtain it by installing Paradox 8.0 or Delphi. If you have an older version of the BDE that does not support Paradox 8 file format then you can upgrade your engine from the Borland World Wide Web site. Alternatively, if you do not have the BDE installed on your computer, you can still link (read-only) to Paradox 3.x, 4.x, and 5.0 tables.

  • If you link a Paradox table that has a primary key, Microsoft Access needs the associated index (.px) file in order to open the linked table. If you link a Paradox table with a Memo field, then Microsoft Access needs the associated memo (.mb) file to open the linked table. If you delete or move these files, you won't be able to open the linked table.

  • If you link a Paradox table that doesn't have a primary key, you won't be able to update data in the table using Microsoft Access. If you want the table to be updatable, define a primary key for the table in Paradox.

  • OLE objects that are stored in a linked or imported Paradox table can't be opened from within Microsoft Access.


 Import or link SQL database tables or data from other ODBC data sources

Import or link SQL database tables or data from other ODBC data sources

Note You can link a table only in a Microsoft Access database, not a Microsoft Access project.

Important You cannot import or link an SQL or other ODBC data source unless you have installed the appropriate driver.

  1. Open a database, or switch to the Database window for the open database.

  2. To import tables, on the File menu, point to Get External Data, and then click Import.

    To link tables, on the File menu, point to Get External Data, and then click Link Tables.

  3. In the Import (or Link) dialog box, in the Files Of Type box, select ODBC Databases ().

    Important If you link to a file on a local area network, make sure to use a universal naming convention (UNC) path, instead of relying on the drive letter of a mapped network drive in Windows Explorer. A drive letter can vary on a computer or may not always be defined, whereas a UNC path is a reliable and consistent way for Microsoft Access to locate the data source that contains the linked table.

    The Select Data Source dialog box lists the defined data sources for any ODBC drivers that are installed on your computer. Click either the File Data Source or Machine Data Source tab, and then double-click the ODBC data source that you want to import. To define a new data source for any installed ODBC driver, click New, and then follow the instructions in the Create New Data Source dialog box and the dialog boxes that follow it before continuing. More information about data sources.

  4. If the ODBC data source that you selected requires you to log on, enter your logon ID and password (additional information might also be required), and then click OK.

    Microsoft Access connects to the ODBC data source and displays the list of tables that you can import or link.

  5. If you're linking a table, select the Save The Login ID And Password check box to save the information for the table in the current databaseso that users won't have to enter it. If you leave the check box cleared, all users must enter the logon ID and password every time they open the table in each new session with Microsoft Access. Your SQL database administrator can also choose to disable this check box, requiring all users to enter the logon ID and password each time they connect to the SQL database. For information on how to disable the Save The Login ID And Password check box, click [image] .

  6. Click each table that you want to import or link, and then click OK. If you're linking a table and it doesn't have an index that uniquely identifies each record, then Microsoft Access displays a list of the fields in the linked table. Click a field or a combination of fields that will uniquely identify each record, and then click OK.

Notes

  • After importing or linking an SQL database table, you can set field properties for the table. If you import a table, you might want to set a primary key for the table. For more information on setting field properties for the table, click [image] .

  • If you encounter an error while importing, linking, or using an SQL database table, there might be a problem with your account on the SQL database server or with the database itself. If you can't access an SQL database table, contact the SQL database administrator.

  • To edit a linked SQL database table, usually the table must contain a unique index on the server. If you want to edit a table that doesn't have a unique index, or if you want to edit an SQL view, then you can create an index within Microsoft Access that the SQL database isn't aware of. You do that by creating a data-definition query, using the Create Index statement. Be aware, however, that the index must be created on a field or combination of fields in which each value is unique. If the field contains any duplicate values, all updates to the table will fail. To delete the index, use another data-definition query. For more information on creating such a data-definition query, click [image] .

  • If the structure of an SQL database table changes after you link it, use the Linked Table Manager to refresh the link. For more information, click [image] .

  • If you are importing from a Microsoft SQL Server database into an Access Project, consider using Data Transformation Services (DTS), which can be a faster and more flexible way to import and transform data. For more information, see the Microsoft SQL Server documentation.


 Import or link (read-only) data on an FTP or HTTP Internet server

Import or link (read-only) data on an FTP or HTTP Internet server

Note You cannot import from or link to a Microsoft Access database, a text file, or an ODBC data source when importing or linking to an FTP or HTTP server. For a general summary of data sources you can import or link, click [image] .

  1. Open a database, or switch to the Database window for the open database.

  2. To import data, on the File menu, point to Get External Data, and then click Import.

    To link data, on the File menu, point to Get External Data, and then click Link Tables.

  3. To import or link from an HTTP server, type the Internet address in the File Name box. For example, to link the file Jansales.html on the //pubweb HTTP server, type http://pubweb/jansales.html.

    To import or link from an FTP server, either type the Internet address in the File Name box, or click the arrow to the right of the Look In box, and then click FTP Locations. In the list of FTP locations, double-click the location of the item you want, and then double-click the item.

Notes

  • Although you can't import or link a text file by using the Import command, you can use the TransferText action or method.

  • Microsoft Access copies the entire file to the Microsoft Internet Explorer cache folder on your local machine. Therefore, this process may take some time because potentially large amounts of data are being transferred through the Internet.

  • A linked table is a data snapshot of the original, remote data source at the time you linked. You will not see updates to the data made at the remote location while the table is open, but the next time you open it, Microsoft Access refreshes the local copy in the cache folder.


 Import or link (read-only) HTML tables and lists

Import or link (read-only) HTML tables and lists

  1. Open a database, or switch to the Database window for the open database.

  2. To import HTML tables or lists, on the File menu, point to Get External Data, and then click Import.

    To link HTML tables or lists, on the File menu, point to Get External Data, and then click Link Tables.

  3. In the Import or Link dialog box, in the Files Of Type box, click HTML Documents (*.html;*.htm).

  4. Click a shortcut on the Places Bar or click the arrow to the right of the Look In box.

  5. Select the drive and folder where the HTML file you want to import or link is located, and then double-click the file name.

  6. Follow the instructions for the Import HTML Wizard or the Link HTML Wizard. Click the Advanced button if you want to edit an import/export specification or specify different file and field formats.

  7. If your HTML file contains more than one table or list, repeat steps 1 through 5 for each table or list you want to import or link.

Notes

  • By default, Microsoft Access converts an HTML hyperlink address to a Hyperlink data type column, but only if all values in a table column or list contain a hyperlink address defined by an <A HREF> HTML tag. You can change the data type when using the Import HTML Wizard or the Link HTML Wizard. For more information on hyperlink addresses, click [image] .

  • Microsoft Access ignores GIF and JPEG images embedded in the HTML tables or lists.

  • A table embedded within a table cell in an HTML file is treated as a separate table when you import or link. A list embedded in a table cell is treated as the contents of a cell, and each item in the list is delimited with the carriage return/line feed characters.

  • For data that spans rows or columns in an HTML table, Microsoft Access 2000 duplicates the data in each cell, whereas Microsoft Excel 2000 stores the data in the first or upper-left cell, and then leaves other cells blank.


 Delete the link to a linked table in a Microsoft Access database

Delete the link to a linked table in a Microsoft Access database

Note You can link a table only in a Microsoft Access database, not a Microsoft Access project.

  1. In the Database window, click Tables [image] under Objects, and then click the linked table.

  2. Press the DELETE key. Microsoft Access deletes the link and removes the table's name from the list.

Note When you delete a linked table, you are deleting only the information that Microsoft Access uses to open the table, not the table itself. You can link to the same table again later if you want.


 Use the MSysConf table in a Microsoft Access database with linked SQL databases

Use the MSysConf table in a Microsoft Access database with linked SQL databases

Note You can link a table only in a Microsoft Access database, not a Microsoft Access project.

If you are administering an SQL database that uses Microsoft Access as a front end, then you can create a table in your SQL database named MSysConf to help you control communication between the two applications. The MSysConf table has two potential functions:

  • It can disable the feature that enables users to save the logon ID and password for a linked SQL database in the Microsoft Access front end.

  • It can optimize how Microsoft Access performs background population of records during idle time by setting the number of rows of data that are retrieved at one time and the number of seconds of delay between each retrieval. Microsoft Access uses a default of 100 records that are returned every 10 seconds if you don't create the MSysConf table.

The structure of the MSysConf table

The SQL database table MSysConf should have the following structure.

Column name | Data type | Allows Null?
Config | A data type that corresponds to a 2-byte integer | No
chValue | VARCHAR(255) | Yes
nValue | A data type that corresponds to a 4-byte integer | Yes
Comments | VARCHAR(255) | Yes

Note If the data source you're working with is case-sensitive, then use the table and column names exactly as shown.

All users must have permission to use the Select statement on this table, and only the system administrator should have insert/update/delete permission.

The data in the MSysConf table

There are three valid records in the MSysConf table. The following table shows what values you should enter in the Config and nValue field. The other columns are reserved for future use, and their contents are ignored.

Config | nValue | Meaning
101 | 0 | Don't allow local storage of the logon ID and password in linked tables.
101 | 1 | Allow local storage of the logon ID and password in linked tables.
102 | D | D is the delay in seconds between each retrieval.
103 | N | N is the number of rows retrieved.

Notes

  • Setting a higher delay time decreases network traffic, but increases the amount of time that read-locks are left on data (if the server uses read-locks).

  • If you create an MSysConf table, it must be set up properly or you will not be able to connect to the SQL database table at all.


 View, refresh, or change the file name and path for linked tables in a Microsoft Access database

View, refresh, or change the file name and path for linked tables in a Microsoft Access database

Note You can link a table only in a Microsoft Access database, not a Microsoft Access project.

Use this procedure to view or to refresh links when the structure or location of a linked table has changed. The Linked Table Manager lists the paths to all currently linked tables.

To view or refresh links

  1. Open the database that contains links to tables.

  2. On the Tools menu, point to Add-ins, and then click Linked Table Manager.

  3. Select the check box for the tables whose links you want to refresh.

  4. Click OK to refresh the links.

    Microsoft Access confirms a successful refresh or, if the table wasn't found, displays the Select New Location of <table name> dialog box in which you can specify it’s the table's new location.

    If several selected tables have moved to the new location that you specify, the Linked Table Manager searches that location for all selected tables, and updates all links in one step.

To change the path for a set of linked tables

  1. Open the database that contains links to tables.

  2. On the Tools menu, point to Add-ins, and then click Linked Table Manager.

  3. Select the Always Prompt For A New Location check box.

  4. Select the check box for the tables whose links you want to change, and then click OK.

  5. In the Select New Location of <table name> dialog box, specify the new location, click Open, and then click OK.

Notes

  • The Linked Table Manager doesn't move database or table files. If you want to move database or table files to a new location, use the Windows Explorer, My Computer, or the MS-DOS copy or move commands. Once you have moved a database or table, you can use the Linked Table Manager to refresh links to its linked tables.

  • The Linked Table Manager can't refresh links to Microsoft Access tables whose names were changed after they were linked. You must delete the current link, and then link such tables again.


 Import Errors table messages

Import Errors table messages

The Import Errors table contains descriptions of most error messages Microsoft Access encounters when trying to import your text file or spreadsheet in a Microsoft Access database. The table includes field names and row numbers that indicate which data has caused errors.

Note In a Microsoft Access project, no Import Errors table is created. Consider using Data Transformation Services (DTS), which can be a faster and more flexible way to import and transform data. For more information, see the Microsoft SQL Server documentation.

If Microsoft Access reports errors, open the Import Errors table and try to determine why Microsoft Access can't import all of the records. The following table lists possible import errors and describes their causes.

Error | Description
Field Truncation | A value in the file is too large for the FieldSize property setting for this field.
Type Conversion Failure | A value in the text file or spreadsheet is the wrong data type for this field.
Key Violation | This record's primary key value is a duplicate — it already exists in the table.
Validation Rule Failure | A value breaks the rule set by using the ValidationRule property for this field or for the table.
Null in Required Field | A Null value isn't allowed in this field because the Required property for the field is set to Yes.
Null value in AutoNumber field | The data that you're importing contains a Null value that you attempt to append to an AutoNumber field.
Unparsable Record | A text value contains the text delimiter character (usually double quotation marks). Whenever a value contains the delimiter character, the character must be repeated twice in the text file; for example: "10 - 3 1/2"" disks/box"

If you suspect that the problem is with your data, edit your text file or spreadsheet. If you're appending records to an existing table, you might need to change the table itself (reorder the fields or change data types, for example). When you have solved the problem, import the data again.


Set up ODBC data sources

  1. Click the Windows Start button, point to Settings, click Control Panel, and then double-click the ODBC (32bit) icon (in Microsoft Windows 95 or later) or ODBC icon (in Microsoft Windows NT Workstation 4.0 or later).

  2. Select the User DSN, System DSN, or File DSN tab, depending on the type of data source to be modified. More information about data sources.

  3. To define a new data source for a currently installed driver, click Add.

  4. To modify the definition of an existing data source:
    • Select the data source from the list. If you are modifying a file DSN, find the appropriate folder in the Look In box (use the Up control if necessary), and then select the data source from the folder.

    • Click Configure.
  5. Complete the dialog boxes. For more information about the different options, click the Help button in each dialog box.


Ways to work with data in a form

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


Ways to work with data in a table's datasheet

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


Ways to work with data in a query's datasheet

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


 Add new data in Datasheet or Form view

Add new data in Datasheet or Form view

  1. Open a Datasheet, or form in Form view.

  2. Click New Record [image] on the toolbar.

  3. Type the data you want, and then press TAB to go to the next field.

  4. At the end of the record, press TAB to go to the next record.


Save a record in Datasheet or Form view

Microsoft Access automatically saves the record you are adding or editing as soon as you move the insertion point to a different record, or close the form or datasheet you are working on.

  • To explicitly save the data in a record while you are editing it, click Save Record on the Records menu.


 Delete a record in Datasheet or Form view

Delete a record in Datasheet or Form view

  1. Open a Datasheet, or form in Form view.

  2. Click the record you want to delete.

  3. Click Delete Record [image] on the toolbar.

Note When you delete data, you might want to delete related data in other tables. For example, if you delete a supplier, you probably want to delete the products that the supplier supplies. In some cases, you can make sure the proper data is deleted by enforcing referential integrity and turning on cascade deletions.

Learn about referential integrity in a Microsoft Access database.

Learn about referential integrity in a Microsoft Access project.


 Insert a default value in a field

Insert a default value in a field

  1. Open a Datasheet.

  2. Click in the field in which you want to insert the default value.

  3. Press CTRL+ALT+SPACEBAR.

Note To see the default value in a Microsoft Access database, open the table in table Design view and look at the DefaultValue property. To see the default value in a Microsoft Access project, display the Column Properties view in a database diagram and look at the Default Value column property.


 Edit the data in a field in Datasheet or Form view

Edit the data in a field in Datasheet or Form view

  1. Open a Datasheet, or form in Form view.

  2. To edit data within a field, click in the field you want to edit.

    To replace the entire value, move the pointer to the leftmost part of the field until it changes into the plus pointer [image] , and then click.

  3. Type the text you want to insert.

Notes

  • If you make a typing mistake, press BACKSPACE. If you want to cancel your changes in the current field, press ESC. If you want to cancel your changes in the entire record, press ESC again before you move out of the field.

  • When you move to another record, Microsoft Access saves your changes.


 Specify a zero-length string in Datasheet or Form view to indicate nonexistent data

Specify a zero-length string in Datasheet or Form view to indicate nonexistent data

  1. Open a Datasheet, or form in Form view.

  2. Type double (" ") quotation marks without a space to enter a zero-length string in the field.

The field remains a zero-length string, even though the quotation marks disappear when you move to another field or object.

Notes

  • In a Microsoft Access database, if Access displays a message saying "Field can't be a zero-length string," then change the AllowZeroLength field property. To learn about changing this property, click [image] .

  • In a Microsoft Access project, you can only enter a zero-length string in a field with the varchar or nvarchar data type in a Microsoft SQL Server 7.0 database. Zero-length strings are not supported in SQL Server 6.5.


 Undo changes when adding or editing records in Datasheet or Form view

Undo changes when adding or editing records in Datasheet or Form view

  • Click Undo [image] on the toolbar to take back your most recent change.

  • Click Undo Saved Record on the Edit menu if you have already saved changes to the current record, or have moved to another record.

As soon as you begin editing another record, apply or remove a filter, or switch to another window, you can't use these methods for correcting changes.


 How a field's data type and validation checking affect data entry in Datasheet or Form view

How a field's data type and validation checking affect data entry in Datasheet or Form view

When you try to move out of a field after changing data, Microsoft Access validates the data, making sure that the value you entered is allowed in that field. If the value isn't allowed, Microsoft Access alerts you. In order to move off the field, you must either change the data to an acceptable value or undo your changes.

A value might not be allowed in a field for the following reasons:

  • The value isn't compatible with the field's data type. If you enter a value that doesn't match the data type, Microsoft Access attempts to convert the entry to the correct data type. However, some data can't be converted to other data types. For example, you can't store a name in a field with the Number data type in a Microsoft Access database or the smallint data type in a Microsoft Access project.

  • The data breaks a rule set in the ValidationRule property for the field.

  • Data is required in the field, and you've tried to leave it blank.

  • The validation macro specified for the BeforeUpdate property canceled the update.

Microsoft Access also validates data when you move out of a record. Before it saves a record, Microsoft Access makes sure it doesn't break any validation rules set in the ValidationRule property for the record. Additionally, if the table you are editing has a primary key or unique index, Microsoft Access makes sure that the record you are editing doesn't have the same value for the field or fields as another record in the table. If the record can't be saved, you must either make any necessary corrections or click Undo [image] to cancel all changes you made to the record.


 Selecting fields and records in Datasheet view

Selecting fields and records in Datasheet view

The following table lists mouse techniques for selecting data or records in Datasheet view.

To select | Click
Data in a field | Where you want to start selecting and drag across the data.
An entire field | The left edge of the field in a datasheet, where the pointer changes into [image] .
Adjacent fields | The left edge of a field and drag to extend the selection.
A column | The field selector.
Adjacent columns | The field name at the top of the column and then, without releasing the mouse, drag to extend the selection.
A record | The record selector.
Multiple records | The record selector of the first record, and then drag to extend the selection.
All records | Select All Records on the Edit menu.

The following table lists keyboard techniques for selecting data or records in Datasheet view.

To select | Do this
Data in a field | Move the insertion point to the start of the text you want to select, and then hold down SHIFT and press the arrow keys to move to the end of the selection.
An entire field | Move the insertion point to the field, and press F2.
Adjacent fields | With a field selected, hold down SHIFT and press the appropriate arrow key.
The current column | Press CTRL+SPACEBAR.
The current record | Press SHIFT+SPACEBAR.
Multiple records | Press SHIFT+SPACEBAR, and then SHIFT+UP ARROW or SHIFT+DOWN ARROW.


 Expand a field or text box to make it easier to edit

Expand a field or text box to make it easier to edit

  1. Open a Datasheet, or form in Form view.

  2. Click the field you want to edit.

  3. Press SHIFT+F2.

Note To expand a property box in a property sheet, you can also right-click the property box, and then click Zoom.


 When can I update data from a query?

When can I update data from a query?

In some cases, you can edit the data in query Datasheet view to change the data in the underlying table. In other cases, you can't. The following table shows whether a query's results can be updated, and if not, whether there is an alternative.

Query or query field | Updatable | Solution
Query based on one table | Yes |
Query based on tables with a one-to-one relationship | Yes |
Query based on tables with a one-to-many relationship | Usually | For more information, click [image] .
Query based on three or more tables in which there is a many-to-one-to-many relationship. | No | Though you can't update the data in the query directly, you can update the data in a form or data access page based on the query if the form's RecordsetType property is set to Dynaset (Inconsistent Updates).
Crosstab query | No |
SQL pass-through query | No |
Query that calculates a sum, average, count or other type of total on the values in a field, or an update query that references a field in the Update To row from either a crosstab query, select query, or subquery that contains totals or aggregate functions | No | By using a domain aggregate function in the Update To row of an update query, you can reference fields from either a crosstab query, select query, or subquery that contains totals or aggregate functions. For more information, click [image] .
Union query | No |
Query whose UniqueValues property is set to Yes | No |
Query that includes a linked ODBC table with no unique index, or a Paradox table without a primary key | No |
Query (or underlying table) for which Update Data permission isn't granted | Can delete but not update | To modify data, permissions must be assigned. For more information, click [image] .
Query (or underlying table) for which Delete Data permission isn't granted | Can update but not delete | To delete data, permissions must be assigned. For more information, click [image] .
Query that includes more than one table or query, and the tables or queries aren't joined by a join line in Design view | No | You must join the tables properly in order to update them. For more information, click [image] .
Calculated field | No |
Field is read-only; the database was opened as read-only or is located on a read-only drive | No |
Field in record that has been deleted or locked by another user | No | A locked record should be updatable as soon as it is unlocked.
Memo, Hyperlink, or OLE Object field in the query's results | Yes |


 Copy or move a field, control, text, macro action, or other item

Copy or move a field, control, text, macro action, or other item

You can copy or move items such as fields, controls, text, or macro actions. You can also copy database objects. Learn more about copying database objects.

  1. Select the items you want to copy or move.

  2. To copy the item, click Copy [image] on the toolbar.

    To move the item, click Cut [image] on the toolbar.

  3. Click the location where you want to place the item.

  4. Click Paste [image] on the toolbar.

Notes

  • When you copy a field, control, or macro action, Microsoft Access includes any associated properties, controls, or action arguments. For example, when you copy a text box control, Access copies its label as well. When you copy an action by clicking the row selector, Access copies the associated action arguments, macros, and conditional expressions.

  • Access doesn't copy event procedures associated with a control.

  • You can use the Office Clipboard to collect and paste multiple data items such as records or groups of records, or the contents of fields or controls. However, you cannot use the Office Clipboard to collect items such as controls, macro actions, or database objects. Learn more about collecting and pasting multiple items.


Delete a field, a control, text, a macro action, or another item

  1. Select the item or items you want to delete.

    Learn about selecting multiple controls.

  2. Press DELETE.


 Select fields and records in Page view

Select fields and records in Page view

The following table lists mouse techniques for selecting data or records in Page view.

To select | Click
Data in a field | Where you want to start selecting and drag across the data.
An entire field | Three times
A record | On a grouped data access page, click any field.

The following table lists keyboard techniques for selecting data or records in Page view.

To select | Do this
Data in a field | Move the insertion point to the start of the text you want to select, and then hold down SHIFT and press the arrow keys to move to the end of the selection.
An entire field | Move the insertion point to anywhere in the field and press HOME, SHIFT+END
A record | On a grouped data access page, press TAB

Note Your data access page may have a PivotTable list or spreadsheet control and they have their own methods of selection. To display Help for a PivotTable list or spreadsheet, click Help [image] on that feature's toolbar.


 Edit the data in a field in Page view

Edit the data in a field in Page view

  1. Move to the record or use a filter to find the record you want to edit.

  2. Click in the field you want to edit.

  3. Type the text you want to insert.

Notes

  • If you make a typing mistake, press BACKSPACE. If you want to cancel your changes in the current field, press ESC. If you want to cancel your changes in the entire record, click Undo Record [image] on the record navigation toolbar.

  • Changes are automatically saved your changes when you move to another record, apply or remove a filter, or switch to another Web page.


 Undo changes when adding or editing records in Page view

Undo changes when adding or editing records in Page view

  • On the record navigation toolbar, click Undo Record

As soon as you begin editing another record, apply or remove a filter, or switch to another Web page, you can't undo your changes.


 Display the most current data in Page view

Display the most current data in Page view

If other users are entering data at the same time as you are, your data access page may not be displaying the most recent changes to your Microsoft Access database or Microsoft Access project. You can reload the most recent data from the database.

  • Right-click the page, and then click Refresh, or press F5.

Caution If you click Refresh before you have saved your changes, Microsoft Access warns you that your changes may be discarded, and you must click Cancel to prevent losing your changes to the current record.

Notes

  • If reloading the data takes a long time and you want to cancel the operation, press ESC.

  • Your data access page may have a PivotTable list control, which has its own refresh method. To display Help for a PivotTable list, click Help [image] on the PivotTable list toolbar.


 Enter a hyperlink by pasting a hyperlink or hyperlink address

Enter a hyperlink by pasting a hyperlink or hyperlink address

  1. Navigate to a hyperlink or hyperlink address in one of the following ways:
    • Open a Microsoft Office document that contains a defined hyperlink.

    • Open a document that was created with any application and contains a valid hyperlink address that is not defined as a hyperlink.

    • Open a Web browser such as Microsoft Internet Explorer.
  2. Do one of the following:
    • In a Microsoft Office document, right-click the defined hyperlink. Point to Hyperlink on the shortcut menu, and then click Copy Hyperlink.

    • In any document, select the hyperlink address, and then click Copy on the Edit menu.

    • In Internet Explorer, select the address in the Address box or select a valid hyperlink address anywhere on a page, right-click, and then click Copy or Copy Shortcut.

    Note If you're copying a defined hyperlink from an Office document, make sure to copy just the hyperlink. If you copy characters that surround but aren't part of the hyperlink, then Microsoft Access will link to the text that you selected instead of the address of the hyperlink.

  3. Switch to Microsoft Access and do one of the following:
    • In a Microsoft Access database (.mdb), open the table or query in Datasheet view.

    • In an Access database or Microsoft Access project (.adp), open the form in Datasheet view or Form view,
  4. Place the insertion point in the hyperlink field in the datasheet or in the text box or other control that accepts hyperlinks on the form.

  5. Do one of the following:
    • To paste a defined hyperlink, click Paste As Hyperlink on the Edit menu.

    • To paste a hyperlink address that isn't defined as a hyperlink, click Paste on the Edit menu. When you paste an address this way, Microsoft Access recognizes the protocol in the address and converts the text to a hyperlink.

    Microsoft Access adds the hyperlink to the field or control. You can click the hyperlink to open the target document or Web page.


 Enter a hyperlink by dragging an Internet shortcut

Enter a hyperlink by dragging an Internet shortcut

  1. In Microsoft Access, do one of the following:
    • In a Microsoft Access database (.mdb), open the table or query in Datasheet view.

    • In an Access database or Microsoft Access project (.adp), open the form in Datasheet or Form view, or the data access page in Page view.
  2. Navigate to an Internet shortcut (an icon on your desktop or an item in the History subfolder of your Windows folder).

  3. Select the Internet shortcut.

  4. Right-click the selection and drag the shortcut to the hyperlink field in the datasheet or to the text box or other control that accepts hyperlinks on the form or data access page.

    Microsoft Access adds the hyperlink to the field or control. On a form or datasheet, you can click the hyperlink to open the target document or Web page. On a data access page, the text box in which you enter a hyperlink address doesn’t format the address as a hyperlink. Look for the address formatted as hyperlink elsewhere on the page.

Tip Click the Refresh button on the Internet Explorer toolbar to see the hyperlink address displayed as a formatted hyperlink.


 Type a hyperlink in a field or text box

Type a hyperlink in a field or text box

  1. Open the table, query, or form in Datasheet view, the form in Form view, or the data access page in Page view.

  2. Place the insertion point in the hyperlink field in the datasheet or in the text box or other control that accepts hyperlinks on the form or data access page.

  3. Type a valid hyperlink address. A hyperlink address can have up to four parts separated by the number sign (#):

    displaytext#address#subaddress#screentip

    The following example includes displaytext, address, and screentip. Note that it also includes the # for subaddress, which has been omitted:

    Microsoft Corporation#http://example.microsoft.com/##Example page for Microsoft Corporation

For more information on hyperlink addresses, click [image] .

Microsoft Access adds the hyperlink to the field or control.

Notes

  • In a Microsoft Access database (.mdb), you can open the target document or Web page by clicking the hyperlink in a table, query, or form in Datasheet view or a form in Form view.

  • In a Microsoft Access project (.adp), you can open the target document or Web page by clicking the hyperlink in a form in Form view or Datasheet view. In Datasheet view of a table, query, or stored procedure, the hyperlink address is displayed as a text string, not as a formatted hyperlink.

  • In a data access page, the text box in which you enter a hyperlink address displays the hyperlink address as a text string, not as a formatted hyperlink. Look for the address formatted as hyperlink elsewhere on the page.

    The ScreenTip displayed for a hyperlink on a data access page is defined for the hyperlink control, so a ScreenTip that you enter won’t be displayed on the page.

    Click the Refresh button on the Microsoft Internet Explorer toolbar to see the hyperlink address displayed as a formatted hyperlink on the data access page.


 Add, change, or delete the path to a picture in Page view

Add, change, or delete the path to a picture in Page view

Note The picture is not stored in the database. Rather, the path to the picture's location is stored in the database, and the picture is stored in a computer's file system.

  1. Move to the record or use a filter to find the record containing the path to the picture you want to add, change, or delete.

  2. Click inside the field containing the path to the picture.

  3. Do one of the following:

    To add the path to the picture, type in the path of the picture's location.

    To change the path to the picture, edit the path. Learn about editing a field.

    To delete the path to the picture, select the entire contents of the field and press the DEL key.

Notes

  • To see your results in the data access page, explicitly save the record, and then refresh the data access page.

  • The path can be a relative path, a path on your computer, a universal naming convention (UNC) path, or a uniform resource locator URL. The type of path you should use depends on the requirements of the database.

  • To delete the actual picture, you must delete it from its location in the file system. This capability may not be in the page, depending on how it was authored. See Microsoft Windows Help for more information on deleting files.


 Add a new record in Page view

Add a new record in Page view

  1. On the record navigation toolbar, click New Record [image].

  2. Type the data you want in the first field, and then press TAB to go to the next field.

  3. When you are finished adding data to each field, click Save Record [image] to save the record.

Note The record is automatically saved as soon as you begin editing another record, apply or remove a filter, or switch to another Web page.


 Save a record in Page view

Save a record in Page view

  • On the record navigation toolbar, click Save Record [image], to explicitly save the data in a record while you are editing it.

Note The record is automatically saved as soon as you move to a different record, apply or remove a filter, or switch to another Web page.


 Delete a record in Page view

Delete a record in Page view

Important Once you delete a record, you cannot undo the deletion from the database.

  1. Move to the record or use a filter to find the record you want to delete.

  2. On the record navigation toolbar, click Delete Record [image] .


 Copy or move data from one field to another

Copy or move data from one field to another

  1. Open a Datasheet, or form in Form view.

  2. Select the data you want to copy or cut.

    How?

  3. To copy the data, click Copy [image] on the toolbar.

    To move the data, click Cut [image] on the toolbar.

  4. To replace the current value of the destination field, select the whole field.

    To insert the data into the existing data, position the insertion point where you want to paste the data.

  5. Click Paste [image] on the toolbar.

    For information on troubleshooting paste problems, click [image] .


 Copy or move data from multiple fields in Datasheet view

Copy or move data from multiple fields in Datasheet view

  1. Open a Datasheet, or form in Form view.

  2. Select the fields or columns you want to copy or cut.

    How?

  3. To copy the data, click Copy [image] on the toolbar.

    To move the data, click Cut [image] on the toolbar.

  4. Select the destination fields, or switch to the application you want to paste the data into, and then select the destination.

  5. Click Paste [image] on the toolbar.

    For information on troubleshooting paste problems, click [image] .


 Copy or move records to a datasheet

Copy or move records to a datasheet

  1. Open a Datasheet, or form in Form view.

  2. Select the record or records you want to copy or move.

    How?

    Note If you're copying or moving records from another application, be sure the data is arranged in a spreadsheet or table, or separated by tab characters, before you select it.

  3. To copy records, click Copy [image] on the toolbar.

    To move records, click Cut [image] on the toolbar.

  4. Open the datasheet you want to paste the records into. If necessary, rearrange the columns of the datasheet to match the order of the data you are copying or moving.

  5. To replace records with the records you selected, select the records you want to replace, and then click Paste [image] on the toolbar.

    To append records to the end of the datasheet, click Paste Append on the Edit menu.

If the source datasheet has more fields than the destination datasheet, Microsoft Access doesn't paste the extra fields. For information on troubleshooting paste problems, click [image] .


 Copy or move records to a form

Copy or move records to a form

  1. Open a Datasheet, or form in Form view.

  2. Select the record or records you want to copy or move.

    How?

  3. To copy records, click Copy [image] on the toolbar.

    To move records, click Cut [image] on the toolbar.

  4. Open the form you want to paste the records into.

  5. To replace records with the records you selected, select the records you want to replace, and then click Paste [image] on the toolbar.

    To append records, click Paste Append on the Edit menu.

Microsoft Access pastes the records into fields with the same name as the source fields, regardless of their order on the form. If the form you are copying or moving records from has fields that don't exist in the form you are copying or moving records to, Microsoft Access asks you if you want to paste only fields with matching names. If there are no matching field names, the fields are pasted according to the tab order in the destination form, which may not be the order you intend. For that reason, it's a good idea to paste fields with different source and destination names into a datasheet instead of a form.

For information on troubleshooting paste problems, click [image] .


 Copy or move records from Microsoft Access to another application

Copy or move records from Microsoft Access to another application

  1. Open a Datasheet, or form in Form view.

  2. Select the data you want to copy or move.

    How?

  3. To copy data, click Copy [image] on the toolbar.

    To move data, click Cut [image] on the toolbar.

  4. Open the application in which you want to paste the data.

  5. To replace data with the data from Microsoft Access, select the data you want to replace.

    To insert the data into existing data, position the insertion point where you want to paste the data.

    Note If you're pasting into a Microsoft Excel spreadsheet, select the cell in which you want the first column heading to be. If you're pasting into a Microsoft Word for Windows document, move the insertion point to where you want to place the records. The records are pasted as a table in Word.

  6. Click Paste on the Edit menu. If your application doesn't have this command, use the comparable method for your application.

Notes

  • When you paste records into another application, Microsoft Access pastes the field names in the first row, followed by the data.

  • If you are copying from a datasheet that contains subdatasheets, Microsoft Access can copy only one level of datasheet at a time.


 Copy or move records from another application to Microsoft Access

Copy or move records from another application to Microsoft Access

  1. In the other application, select one or more rows you want to copy or move. If you're copying from a word-processing application, make sure the records are arranged in a table or separated by tab characters before you select them.

  2. If you are pasting to a datasheet, make sure the columns match the order of the data you want to copy or move.

    If you are pasting to a form, and the corresponding controls on the form have the same names as the column names of the data you are copying, Microsoft Access will paste the data to the matching controls. If the column names don't match, or there are no column names, Microsoft Access will paste the data in the tab order of the form.

  3. To copy records, click Copy on the Edit menu.

    To move records, click Cut on the Edit menu.

    Note If your application doesn't have these commands, use the comparable method for your application.

  4. In Microsoft Access, open the datasheet or form in which you want to paste the records.

  5. Do one of the following:
    • To replace records, select those records, and then click Paste [image] on the toolbar. In a form, if the record selector isn't visible, to select the current record, click Select Record on the Edit menu.

    • To append the data as new records, click Paste Append on the Edit menu.


 Collect and paste multiple items

Collect and paste multiple items

  1. Select the first item you want to copy.

  2. On the Clipboard toolbar, click Copy [image] .

    To display the Clipboard toolbar, point to Toolbars on the View menu, and then click Clipboard.

  3. If the next item you want to copy is in another program, switch to that program.

  4. Select the next item you want to copy.

  5. On the Clipboard toolbar, click Copy [image] .

    If the Clipboard toolbar is not available, click Copy on the Edit menu.

  6. Repeat steps 3 through 5 until you have copied all the items (up to 12) you want to copy.

  7. Click where you want the items to be pasted.

  8. To paste all the items you copied, click Paste All [image] on the Clipboard toolbar.

    If you don't want to paste all the items you copied, or if Paste All is not available, you can paste specific items.

Note If the Clipboard toolbar is not available, you are in a program or view that doesn't support showing or pasting multiple items from the Office Clipboard. However, if the Office Clipboard is shown in any Office program, any items you cut or copy in any program will be collected automatically.


 About collecting and pasting multiple items

About collecting and pasting multiple items

This topic provides reference information about:

Copying multiple items

Using the Clipboard toolbar

The Office Clipboard and Windows Clipboard

Office Clipboard capability

More information

Copying multiple items

You can use the Office Clipboard to collect and paste multiple items. For example, you can copy text in a Microsoft Word document, switch to Microsoft Excel and copy a drawing object, switch to Microsoft PowerPoint and copy a bulleted list, switch to Microsoft Access and copy a datasheet, and then switch to Microsoft Word and paste the collection of copied items. The Office Clipboard automatically copies multiple items when you do any of the following:

  • Copy or cut two different items in succession in the same program

  • Copy one item, paste the item, and then copy another item in the same program

  • Copy one item twice in succession

Return to top

Using the Clipboard toolbar

You can also copy multiple items by displaying the Clipboard toolbar (View menu, Toolbars submenu) and clicking Copy [image] . If you open the Office Clipboard in one Microsoft Office program, the Office Clipboard appears when you switch to another Office program. The Clipboard toolbar is not available in views where the Copy, Cut, and Paste commands are not available.

When the Clipboard toolbar is shown, you can click Paste All [image] to paste all the items you have copied, or you can click an individual item to paste only that item. The Paste command (Edit menu) pastes only the last item you copied. However, after you have pasted anything from the Clipboard toolbar, either an individual item or all items, the Paste command (Edit menu) pastes the last thing pasted from the Clipboard toolbar.

Note You cannot customize the Clipboard toolbar.

Return to top

The Office Clipboard and Windows Clipboard

The Office Clipboard is separate from the Windows Clipboard. When you copy multiple items to the Office Clipboard, the last item you copy is always copied to the Windows Clipboard. When you clear the Office Clipboard, the Windows Clipboard is also cleared. When you use the Paste command (Edit menu), Paste button, or the paste shortcut key (CTRL+V) you paste the contents of the Windows Clipboard.

Return to top

Office Clipboard capability

The Office Clipboard can hold up to 12 items. If you copy an additional item when the Office Clipboard already contains 12 items, you receive a message asking whether the first item should be removed or the current item, the thirteenth item, should not be copied. The collected items remain in the Office Clipboard until you quit all Office programs running on your computer.

You cannot paste multiple items or display the Office Clipboard in a program other than Microsoft Excel, Word, Access, Outlook, or PowerPoint. However, if the Office Clipboard is shown in any Office program, any items you cut or copy in any program are collected automatically.

Return to top

More information

Collect and paste multiple items

Paste specific items from the Office Clipboard

Clear all items from the Office Clipboard

Return to top


 Clear all items from the Office Clipboard

Clear all items from the Office Clipboard

  • On the Clipboard toolbar, click Clear Clipboard [image] .

    To display the Clipboard toolbar, point to Toolbars on the View menu, and then click Clipboard.


 View the contents of the Office Clipboard

View the contents of the Office Clipboard

  • On the View menu, point to Toolbars, and then click Clipboard. If the Clipboard toolbar is docked, click Items.

Tip To view the first 50 characters of text in an item on the Office Clipboard, rest the mouse pointer on the item button. If the item is a drawing object, picture, or an item with no text to view, the text "Picture n" or "Item x" appears, where n is a number indicating the location of the picture in the copy order of drawing objects and pictures only, and x is a number indicating the location of the item in the copy order of all items.


 Paste specific items from the Office Clipboard

Paste specific items from the Office Clipboard

  1. Click where you want the items to be pasted.

  2. On the Clipboard toolbar, click the item you want to paste.

    If the Clipboard toolbar is docked, click Items, and then click the item you want to paste.

    To display the Clipboard toolbar, point to Toolbars on the View menu, and then click Clipboard.

  3. Repeat step 2 for each item you want to paste.

Tip To view the first 50 characters of text in an item on the Office Clipboard, rest the mouse pointer on the item button. If the item is a drawing object, picture, or an item with no text to view, the text "Picture n" or "Item x" appears, where n is a number indicating the location of the picture in the copy order of drawing objects and pictures only, and x is a number indicating the location of the item in the copy order of all items.


 Display data from a field in a table or a query

Display data from a field in a table or a query

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. If you want to use a wizard to help you create the control, make sure that the Control Wizards tool [image] in the toolbox is pressed in.

    Notes

    • On forms and reports, you can use wizards to create command buttons, list boxes, subforms, combo boxes, and option groups. On data access pages, you can use wizards to create command buttons, list boxes, and drop-down list boxes.

    • Wizards are not available in a stand-alone data access page, or when you point a data access page to a database other than the one currently open. In this case, you will have to create the control without using a wizard.
  3. Display the field list by clicking Field List [image] on the toolbar.

  4. Do one of the following:
    • Select one or more fields in the field list on a form or report.
    To select | Do this
    One field | Click the field.
    A block of fields | Click the first field in the block, hold down the SHIFT key, and then click the last field in the block.
    Nonadjacent fields | Hold down the CTRL key and click the name of each field that you want to include.
    All fields | Double-click the field list title bar.

    • Select a field, table, or query in the field list on a data access page.
    To select | Do this
    One field | Click the field.
    A table or query | Click the Wizards tool [image] in the toolbox if it's not already pressed in, and click the table or query.

  5. Do one of the following:
    • Drag the field(s) from the field list and position them on the form or report.

    • Drag the field, table, or query from the field list and position it on the data access page. In the Layout Wizard dialog box, click Individual Controls.

    • Note You must drag the field(s), table, or query from the field list. If you click the field(s), table, or query in the field list and then click the form, report, or data access page, Microsoft Access won't create the control. Access places one text box on the form, report, or data access page for each field that you select in the field list. If you select a table or query in the data access page field list, Access places a text box for each field in the table or query on the data access page. Each text box is bound to one field in the underlying data source. Each text box also has an attached label by default.
  6. Place the upper-left corner of the icon where you want the upper-left corner of the main control (not its label) to be, and release the mouse button.

Notes

  • Access creates the appropriate control for the field and sets certain properties, based on the field's data type. If this isn't the type of control that you want to create, click the appropriate control tool in the toolbox before dragging the field from the field list. In a form or report, controls are also created based on the settings of the DisplayControl property. To read about the DisplayControl property, click [image] .

  • In forms and reports, you can also change a control to another type of control after you create it.

How?


 Display data, text, or totals on a form, report, or data access page

Display data, text, or totals on a form, report, or data access page

Everything you add to a form, report, or data access page is a control. Text boxes, labels, list boxes, option buttons, command buttons, and lines are examples of different controls. The way you create a control depends on whether you want to create a bound control, an unbound control, or a calculated control.

What do you want to do?

Learn more about bound, unbound, and calculated controls

Learn more about adding data to a data access page using the field list

Create a bound control

Create an unbound control

Create a calculated control

Create a specific type of control on a form (text box, check box, list box, and so on)

Create a specific type of control on a report (label, text box, check box, and so on)

Create a specific type of control on a data access page (text box, check box, list box, and so on)


 Enter a hyperlink address in Page view

Enter a hyperlink address in Page view

There are several ways to enter a hyperlink address in Page view of a data access page for records that each have a different hyperlink. On a data access page, the text box in which you enter a hyperlink address doesn’t format the address as a hyperlink. Look for the address formatted as hyperlink elsewhere on the page.

Paste a hyperlink or hyperlink address

Drag an Internet shortcut

Type a hyperlink address


 Follow a hyperlink

Follow a hyperlink

  1. Open the table, query, or form in Datasheet view, the form in Form view, or the data access page in Page view.

  2. Rest the pointer on the hyperlink. Click the hyperlink when the pointer changes to a hand.

    By default, a hyperlink that you haven't clicked is blue and underlined, and a hyperlink that you have clicked is purple and underlined. For information on changing the default formatting, click [image] .


 Modify a hyperlink that's stored in a table in Form view or Datasheet view

Modify a hyperlink that's stored in a table in Form view or Datasheet view

  1. Do one of the following:
    • In a Microsoft Access database (.mdb), open the table or query in Datasheet view.

    • In an Access database or Microsoft Access project (.adp), open the form in Datasheet or Form view.
  2. Right-click the hyperlink field in the datasheet. In the form, right-click the text box or combo box that contains the hyperlink.

  3. To add or modify the display text, point to Hyperlink in the shortcut menu. In the Display Text box, type the display text you want.

  4. To change a hyperlink address, point to Hyperlink in the shortcut menu, and then click Edit Hyperlink.

  5. In the Edit Hyperlink dialog box, click an option under Link to, and then fill in the information required for that option.

Note In an Access project, you can modify a hyperlink in a table or query datasheet by typing in the hyperlink field. For information on the syntax to use to type a hyperlink, click [image] .


 Delete a hyperlink that's stored in a table in Form view or Datasheet view

Delete a hyperlink that's stored in a table in Form view or Datasheet view

  1. Do one of the following:
    • In a Microsoft Access database (.mdb), open the table or query in Datasheet view.

    • In an Access database or Microsoft Access project (.adp), open the form in Datasheet or Form view.
  2. Go to the record that has the hyperlink you want to delete.

  3. Right-click the hyperlink field in the datasheet. In the form, right-click the text box or combo box that contains the hyperlink.

  4. In the shortcut menu, point to Hyperlink, and then click Remove Hyperlink.

Notes

  • In an Access project, you can delete a hyperlink in a table or query datasheet by selecting the contents of the field and pressing DELETE.

  • In both an Access database and an Access project, you can delete all the hyperlinks stored in a table by deleting the field that stores hyperlinks from the table's design.


 Enter a hyperlink address in Form view or Datasheet view

Enter a hyperlink address in Form view or Datasheet view

There are several ways to enter a hyperlink address in a form or datasheet for records that each have a different hyperlink. In a Microsoft Access database (.mdb), you can use all the following methods to enter a hyperlink in a table, query, or form in Datasheet view, or in a form in Form view. In a Microsoft Access project (.adp), you can use all these methods to enter a hyperlink in a form in Form or Datasheet view. In Datasheet view of a table, view, or stored procedure, you must type the hyperlink in the field.

What do you want to do?

Link to a document, file, or Web page

Use the Insert Hyperlink button to create a link to an existing file or Web page

Use the Insert Hyperlink button to create a link to a new data access page and create the page

Paste a hyperlink or hyperlink address

Paste text from a Microsoft Office document

Drag an Internet shortcut

Type a hyperlink address

Link to an object in the current database

Use the Insert Hyperlink button to create a link to a table, query, form, report, or data access page in the current database

Link to an e-mail address

Use the Insert Hyperlink button to create a link that opens your e-mail program and creates a message addressed to the specified e-mail address


 Check the spelling of data in Datasheet view

Check the spelling of data in Datasheet view

  1. Open a Datasheet.

  2. Select the records, columns, fields, or text within a field whose spelling you want to check.

    How?

  3. Click Spelling [image] on the toolbar.

Notes

  • In the Spelling dialog box, click Add if you want to add the word that is in the Not In Dictionary box to the custom dictionary listed in the Add Words To box.

  • If a datasheet contains subdatasheets, Microsoft Access only checks the spelling of the datasheet or subdatasheet where you have placed the insertion point.


 Check the spelling of data in Form view

Check the spelling of data in Form view

  1. Open a form in Form view.

  2. Select the field or text whose spelling you want to check.

  3. Click Spelling [image] on the toolbar.

Note In the Spelling dialog box, click Add if you want to add the word that is in the Not In Dictionary box to the custom dictionary listed in the Add Words To box.


 Check the spelling of a database object in the Database window

Check the spelling of a database object in the Database window

  1. Go to the Database window.

  2. Click the table, query, form, view, or stored procedure whose spelling you want to check.

  3. Click Spelling [image] on the toolbar.

Note In the Spelling dialog box, click Add if you want to add the word that is in the Not In Dictionary box to the custom dictionary listed in the Add Words To box.


 Choose a custom dictionary for checking spelling

Choose a custom dictionary for checking spelling

  1. Go to the Database window.

  2. Click any table, query, form, view, or stored procedure.

  3. Click Spelling [image] on the toolbar.

    Note You may need to temporarily misspell an existing word to display the Spelling dialog box.

  4. Click Options.

  5. Select the custom dictionary you want in the Dictionary box.


 Automatically correct typing when I'm entering data

Automatically correct typing when I'm entering data

Use AutoCorrect to automatically correct text that you frequently mistype, and to automatically replace abbreviations with long names. For example, you can create an entry "esq" for "Martin R. Esquivel." Whenever you type esq followed by a space or punctuation mark, Microsoft Access automatically replaces "esq" with the name Martin R. Esquivel.

  1. On the Tools menu, click AutoCorrect.

  2. Select the Replace text as you type check box.

  3. In the Replace box, type the text that you want corrected automatically.

  4. In the With box, type the corrected text.

  5. Click Add.

Notes

  • AutoCorrect won't correct text that was typed before you selected the Replace text as you type check box.

  • If in the preceding example you actually want "esq" to appear in one case, clear the Replace text as you type box, type esq in a field and save the field by moving to another record. Then select the Replace text as you type box again. Microsoft Access will not change the previously typed and saved "esq."

  • AutoCorrect works with text in a Datasheet or text in a form in Form view.


Automatically capitalize names of days when I'm entering data

  1. On the Tools menu, click AutoCorrect.

  2. Select the Capitalize names of days check box.


Correct two capital letters in a row automatically when I'm entering data

  1. On the Tools menu, click AutoCorrect.

  2. Select the Correct TWo INitial CApitals check box.


Stop the automatic correction of an entry I make when I'm entering data

  1. On the Tools menu, click AutoCorrect.

  2. Click the entry you want to delete in the box at the bottom.

  3. Click Delete.


Add an AutoCorrect entry while checking spelling

  1. In the Spelling dialog box, in the Change To box, type the corrected text.

  2. Click AutoCorrect in the Spelling dialog box.

When you type the text that is in the Not In Dictionary box as you add data to tables or forms, Microsoft Access will automatically change it to the text in the Change To box.


Stop automatic corrections that occur when I'm entering data

  1. On the Tools menu, click AutoCorrect.

  2. Clear the check boxes for the options you want to turn off.


 About finding or replacing data

About finding or replacing data

Ways to find or replace data

There are many ways in Microsoft Access to find or replace just the data you need, whether you're looking for a particular value, one record, or a group of records.

  • You can find a record by scrolling in a datasheet or form, or by typing its record number in the record number box.

  • With the Find dialog box, you can locate specific records or find certain values within fields. You can navigate through records as Access finds each occurrence of the item you're looking for. If you want to replace certain values that you find, use the Replace dialog box instead.

  • With a filter, you can temporarily isolate and view a specific set of records to work with while you have a form or datasheet displayed.

  • With a query, you can work with a specific set of records that meet criteria you specify from one or more tables in the database. You can work with this subset independent of a specific form or datasheet by running the query.

The effect of the maximum record limit in a Microsoft Access project

When you attempt to find or replace data in a Microsoft Access project, Access performs the operation only on the data that is stored on the client. If your datasheet or form has reached its maximum record limit, there is more data on the server. To ensure that you are finding or replacing all the data on the server, set the maximum record limit to no limit by using the maximum record limit button to the right of the navigation buttons.


 About using wildcard characters to search for partial or matching values

About using wildcard characters to search for partial or matching values

You use wildcard characters as placeholders for other characters when you are specifying a value you want to find and you:

  • Know only part of the value.

  • Want to find values that start with a specific letter or match a certain pattern.

In a Microsoft Access database, you can use the following characters in the Find and Replace dialog boxes, or in queries, commands, and expressions, to find such things as field values, records, or file names.

Character | Usage | Example
* | Matches any number of characters. It can be used as the first or last character in the character string. | wh* finds what, white, and why
? | Matches any single alphabetic character. | B?ll finds ball, bell, and bill
[ ] | Matches any single character within the brackets. | B[ae]ll finds ball and bell but not bill
! | Matches any character not in the brackets. | b[!ae]ll finds bill and bull but not bell
- | Matches any one of a range of characters. You must specify the range in ascending order (A to Z, not Z to A). | b[a-c]d finds bad, bbd, and bcd
# | Matches any single numeric character. | 1#3 finds 103, 113, 123

Notes

  • Wildcard characters are meant to be used with text data types, although you can sometimes use them successfully with other data types, such as dates, if you don't change the Regional Settings properties for these data types.

  • When using wildcard characters to search for an asterisk (*), question mark (?), number sign (#), opening bracket ([), or hyphen (-), you must enclose the item you're searching for in brackets. For example, to search for a question mark, type [?] in the Find dialog box. If you're searching for a hyphen and other characters simultaneously, place the hyphen before or after all the other characters inside the brackets. (However, if you have an exclamation point (!) after the opening bracket, place the hyphen after the exclamation point.) If you're searching for an exclamation point (!) or closing bracket (]), you don't need to enclose it in brackets.

  • You can't search for the opening and closing brackets ([ ]) together because Microsoft Access interprets this combination as a zero-length string. You must enclose the opening and closing brackets in brackets ([[ ]]).

  • A Microsoft Access project uses different wildcard characters than an Access database uses. For more information, search the Microsoft SQL Server Books Online index for "wildcard characters". If you're searching for values in any other data source, you may need to use different wildcard characters. Check the documentation for that data source for more information.


 Find a specific record by scrolling in a Datasheet or form

Find a specific record by scrolling in a Datasheet or form

If there are more records than fit in your Datasheet view or continuous form window, you can use the scroll box on the scroll bar to find a specific record.

  • Drag the scroll box up or down on the scroll bar.

Next to the scroll box, Microsoft Access displays the number of the record at the top of the screen.

If you have a Microsoft IntelliMouse, you can use the wheel button to scroll to a specific record depending on your current view.

View | Wheel button behavior | Cursor behavior
Datasheet, or subform displayed as a datasheet | Scrolls row by row | Does not move
Single form or subform displayed as a single form | Goes to the next or previous record | Goes to the next or previous record
Continuous form or subform displayed as a continuous form | Goes to the next or previous record | Does not move


 Find a record by record number in Datasheet or Form view

Find a record by record number in Datasheet or Form view

  1. Open a table, query, form, view, or stored procedure in Datasheet view, or a form in Form view.

  2. Double-click the number in the record number box to select it, or press F5.

  3. Type the number of the record you want, and then press ENTER.


 Move between records by using navigation buttons in Page view

Move between records by using navigation buttons in Page view

  • Use the navigation buttons located on the record navigation toolbar to quickly move between records, or a group of records on a grouped data access page.

    Record navigation buttons


 Find specific occurrences of a value in a field

Find specific occurrences of a value in a field

For information on finding Null values and zero-length strings, click [image] .

  1. In Form or Datasheet view, select the field (column) you want to search, unless you want to search all fields. (Searching a single field is faster than searching the entire form or datasheet.)

  2. Click Find Find object on the toolbar.

  3. In the Find What box, type the value you want to find.

    If you don't know the exact value you want to find, you can use wildcard characters in the Find What box to specify what you're looking for. For examples of wildcard characters and how to use them, click [image] .

  4. Set any other options you want to use in the Find dialog box. Click More for additional options.

  5. Click Find Next.

Notes

  • When looking for values in a datasheet with a subdatasheet, or form with a subform displayed as a datasheet, Microsoft Access only looks in the datasheet, subdatasheet, or form where you’ve placed the insertion point.

  • In the Code window, the Find dialog box has additional options specific to the Visual Basic Editor. You can specify the range of the search by selecting an option in the Search options group. Note that Access searches procedures based on the order they were added to the module. The Use Pattern Matching check box uses the same semantics as the Like Operator uses.


 Replace specific occurrences of a value in a field

Replace specific occurrences of a value in a field

You can replace all occurrences of the specified value at once or each occurrence one at a time. If you want to find Null values and zero-length strings, however, you must use the Find dialog box to find these occurrences, and then replace them manually. For more information, click [image] .

  1. In Form or Datasheet view, select the field (column) you want to search, unless you want to search all fields. (Searching a single field is faster than searching the entire datasheet or form.)

  2. On the Edit menu, click Replace.

  3. In the Find What box, type the value you want to find; in the Replace With box, type the value you want to replace it with.

    If you don't know the exact value you want to find, you can use wildcard characters in the Find What box to specify what you're looking for. For examples of wildcard characters and how to use them, click [image] .

  4. Set any other options you want to use in the Replace dialog box. Click More for additional options.

  5. To replace all occurrences of the specified value at once, click Replace All.

    To replace each occurrence one at a time, click Find Next, and then click Replace; to skip an occurrence and find the next one, click Find Next.

Notes

  • In a Microsoft Access database, you can replace large amounts of data more quickly or perform calculations on data (such as raising all salaries in an Employee table by 5 percent) by using an update query instead of the Replace dialog box. However, you can't confirm individual replacements when using an update query and an update query isn't as convenient when you want to search for and replace data in more than one field. In a Microsoft Access project, you can use a stored procedure to update large amounts of data.

  • When replacing data in a datasheet with a subdatasheet, or form with a subform displayed as a datasheet, Microsoft Access only replaces data in the datasheet, subdatasheet, or form where you’ve placed the insertion point.

  • In the Code window, the Replace dialog box has additional options specific to the Visual Basic Editor. You can specify the range of the search by selecting an option in the Search options group. Note that Access searches procedures based on the order they were added to the module. The Use Pattern Matching check box uses the same semantics as the Like Operator uses.


Change default behavior for find and replace operations

Change default behavior for find or replace operations

  1. On the Tools menu, click Options.

  2. Click the Edit/Find tab.

  3. Under Default Find/Replace Behavior, click the option you want to use.

Note Changes made to this setting don't take effect until the next time you start Microsoft Access. To change the behavior for a specific find or replace operation, choose Find or Replace from the Edit menu, and then set the appropriate options in the dialog box.


 Optimize find and replace performance

Optimize find and replace performance

  • For the fastest searches, search for whole field values or the first character within a single indexed field. If you search the same nonindexed field repeatedly, index the field.

    How?


 Find blank fields or zero-length strings using the Find dialog box

Find blank fields or zero-length strings using the Find dialog box

  1. In Form or Datasheet view, click in the field (column) you want to search, and then click Find Find object on the toolbar.

  2. Click More, if necessary.

  3. Do one of the following:
    • If blank fields are formatted (such as "Unknown"), type the formatted string, and make sure that the Search Fields As Formatted check box is selected. To find unformatted blank fields in a Microsoft Access database, in the Find What box, type Null or Is Null, and make sure that the Search Fields As Formatted check box is not selected.

    • To find zero-length strings, in the Find What box, type double quotation marks (""), with no spaces in between, and make sure that the Search Fields As Formatted check box is not selected.
  4. In the Search box, select Up or Down.

  5. In the Match box, make sure that Whole Field is selected.

  6. In the Look In box, select the field to search.

  7. To find one or more occurrences of a blank, click Find Next.


 Similarities and differences between select queries and filters

Similarities and differences between select queries and filters

The basic similarity between select queries and filters is that they both retrieve a subset of records from an underlying table or query. How you want to use the records that are returned determines whether you use a filter or a query.

Generally, use a filter to temporarily view or edit a subset of records while you're in a form or datasheet. Use a query if you want to do any or all of the following:

  • View the subset of records without first opening a specific table or form.

  • Choose the tables containing the records you want to work with and add more tables at a later date if necessary.

  • Control which fields from the subset of records display in the results.

  • Perform calculations on values in fields.

Note Even if you determine you need a query, consider taking advantage of the easy Filter By Form, Filter By Selection, or Filter For Input techniques for creating a filter, and then saving the filter as a query. This enables you to bypass the query's design grid altogether (unless you want to make additional changes to the query). Even so, when you open the query in Design view, you'll see how Microsoft Access filled in the design grid using the information from the filter. You can then use this information as a guide for making additional changes.

The following table identifies the similarities and differences between queries and filters.

Characteristics | Filters | Queries
Enable you to add more tables if you want to include their records in the subset that's returned | No | Yes
Enable you to specify which fields you want to display in the results from the subset of records | No | Yes
Appear as a separate object in the Database window | No | Yes
Can be used on a closed table, query, or form | No | Yes
Produce results that can be used as the source of data for a form or report | Yes | Yes
Can calculate sums, averages, counts, and other types of totals | No | Yes
Can sort records | Yes | Yes
Enable you to edit data if editing is otherwise allowed | Yes | Yes, depending on the type of query. You can also perform bulk updates with an update query.


 Comparison of filtering methods for tables, queries, or forms

Comparison of filtering methods for tables, queries, or forms

What do you want the filter to do? | Filter By Selection | Filter By Form and Filter For Input | Advanced Filter/Sort
Search for records that meet multiple criteria. | Yes (but you must specify the criteria one at a time) | Yes (and you can specify the criteria all at once) | Yes (and you can specify the criteria all at once)
Search for records that meet one criteria or another criteria. | No | Yes | Yes
Allow you to enter expressions as criteria. | No | Yes | Yes
Sort records in ascending or descending order. | No (however, after applying the filter, you can sort all filtered records by clicking Sort Ascending [image] or Sort Descending [image] on the toolbar) | No (however, after applying the filter, you can sort all filtered records by clicking Sort Ascending [image] or Sort Descending [image] on the toolbar) | Yes (you can sort some fields in ascending order and other fields in descending order)


 Create a filter in a table, query, or form

Create a filter in a table, query, or form

There are four methods you can use to filter records: Filter By Selection, Filter By Form, Filter For Input, and Advanced Filter/Sort.

What do you want to do?

See recommendations for choosing a filtering method

See a comparison of each filtering method for help in deciding which one to use

Use Filter By Selection

Use Filter By Form

Use Filter For Input

Use the Advanced Filter/Sort window


Modify a filter in a table, query, or form

If a filter isn't giving you the results you need, you can modify it. You can modify a filter by using the same technique you used to create it or the technique that works best for the modifications you want to make.

Which filtering technique do you want to use to modify a filter?

Filter By Selection or Filter Excluding Selection

Filter For Input

Filter By Form

Advanced Filter/Sort


 Switch between filter windows in a table, query, or form

Switch between filter windows in a table, query, or form

You can switch between windows to create or modify a filter by using the method that works best for your filtering needs, or to see a different view of an existing filter. Filter By Form and Advanced Filter/Sort have their own windows. However, you use Filter By Selection or Filter For Input directly in Form view or Datasheet view.

To switch to | From this window | Do this
Filter By Form | Datasheet view or Form view | On the toolbar, click Filter By Form [image] .
 | Advanced Filter/Sort | On the Filter menu, click Filter By Form.
Advanced Filter/Sort | Datasheet view or Form view | On the Records menu, point to Filter, and then click Advanced Filter/Sort.
 | Filter By Form | On the Filter menu, click Advanced Filter/Sort.

To apply a filter from either Filter By Form or the Advanced Filter/Sort window and see the results in Datasheet view or Form view, click Apply Filter [image] on the toolbar. To close either filter window and return to Datasheet view or Form view without applying the filter, click Close [image] on the toolbar.

Note After specifying the values you're searching for by using Filter By Selection, Filter By Form, or Filter For Input, you can switch to the Advanced Filter/Sort window to see how the values you specified are translated into a criteria expression in the design grid.


 Optimize performance in the Filter By Form window

Optimize performance in the Filter By Form window

If the lists in fields in the Filter By Form window take too long to display or they aren't displaying values from the underlying table, you can change Filter By Form performance for all tables, queries, and forms, or change performance for a specific form. In either case, you can prevent the lists from displaying the underlying table's field values, display field values on the list for certain types of indexed or nonindexed fields only, or change the record limit that determines if the list displays a field's values.

What do you want to do?

Optimize Filter By Form performance for all tables, queries, and forms in the database

Optimize Filter By Form performance for a specific form


 Enable or disable filtering records in a form

Enable or disable filtering records in a form

  • Set the form's AllowFilters property to Yes to enable filtering or to No to disable filtering capabilities in Form view and in form Datasheet view.

    How?

Note When you set the AllowFilters property to No, you disable Filter By Selection, Filter By Form, Filter For Input, and Advanced Filter/Sort.


Add or manipulate fields in a filter

What do you want to do?

Add fields to the design grid in an advanced filter

Move a field in the design grid of an advanced filter

Remove a field from the design grid of an advanced filter

Insert a field in the design grid of an advanced filter

Apply an existing query as a filter on a form, subform, or datasheet


Add or modify a sort order for a filter

What do you want to do?

Sort records using the design grid of an advanced filter

Specify criteria or a sort order when using the asterisk in the design grid

Read about issues to consider when sorting records

Remove a sort order from a table, query, or form


Add or modify criteria for a filter

What do you want to do?

Learn about using criteria in a filter to retrieve certain records

Enter criteria in a filter to retrieve certain records

See examples of criteria expressions for filters

Insert or delete a criteria row in an advanced filter


 Apply a filter in a table, query, or form

Apply a filter in a table, query, or form

  • In a form, datasheet, or either filter window, click Apply Filter [image] on the toolbar.

Notes

  • When you apply a filter to a datasheet, Microsoft Access also applies filters you created in any subdatasheet within it.

  • Microsoft Access can apply a filter automatically when you open a form if you set the form's OnOpen property to a macro that uses the ApplyFilter action or to an event procedure that uses the ApplyFilter method of the DoCmd object.

  • If you create a filter in a form, subform, datasheet, or subdatasheet that already contained a filter from a previous working session, the new filter replaces the previous one.


 Apply an existing query as a filter on a form or datasheet

Apply an existing query as a filter on a form or datasheet

While you can save only one filter for each datasheet, subdatasheet, form, or subform, you can use queries that you've already created as additional filters. A query must meet certain requirements if you're going to use it as a filter. For more information on those requirements, click [image] .

  1. Click in the datasheet, subdatasheet, form, or subform you want to filter.

  2. Switch to the Filter By Form window or the Advanced Filter/Sort window.

    How?

  3. On the toolbar, click Load From Query [image] .

  4. In the Filter box, select a query, and then click OK.

  5. Click Apply Filter [image] on the toolbar.

Note For information on creating a form or report based on the filtered data, click [image] .


 Remove a filter from a table, query, or form

Remove a filter from a table, query, or form

  • To remove a filter and show the records that were displayed previously in the table, query, or form, click Remove Filter [image] on the toolbar in Datasheet view or Form view.

  • To remove a filter in a multiuser (shared) database and see which records have been added, deleted, or changed since you opened the table, query, or form, click Remove Filter/Sort on the Records menu in Datasheet view or Form view.

Notes

  • Removing a filter doesn't delete it. You can reapply the filter by clicking Apply FIlter [image] on the toolbar. When you remove a filter from a datasheet, Microsoft Access also removes any filters you applied to any subdatasheet within it.

  • If you prefer, you can use the ShowAllRecords action in a macro or Visual Basic for Applications code to remove the filter.


 Delete a filter from a table, query, or form

Delete a filter from a table, query, or form

Use this procedure to delete any type of filter, regardless of what method you used to create it.

  1. Click in the datasheet, subdatasheet, form, or subform whose filter you want to delete.

  2. Switch to the Advanced Filter/Sort window.

    How?

  3. On the Edit menu, click Clear Grid.

  4. Click Apply Filter [image] on the toolbar.


 Remove or apply an inherited filter in a report

Remove or apply an inherited filter in a report

  1. Open the report in Design view, or if the report is already open, make sure it is selected.

  2. Click Properties [image] on the toolbar to display the report's property sheet.

  3. In the FilterOn property box, click No to remove the filter or Yes to apply it.

Notes

  • Microsoft Access can apply a filter automatically when you open a report if you set the report's OnOpen property to a macro that uses the ApplyFilter action or to an event procedure that uses the ApplyFilter method of the DoCmd object. You can also automatically apply a filter to a report using the OpenReport action or its corresponding method.

  • You can delete the filter if you want. For more information, click [image] .


 How a filter and sort order for a table or query affects new forms or reports

How a filter and sort order for a table or query affects new forms or reports

When you create a form or report based on a table or query that has a filter or a sort order specified in it, Microsoft Access includes the filter and sort order with the form or report. The sort order is automatically applied. Whether or not the filter is automatically applied depends on how you create the form or report.

  • If you create the form or report directly from filtered data while the data is displayed in an open table or query, the filter is applied automatically each time you view the report, but it is applied only the first time you view the form after creating it. (The next time you open the form, you'll apply the filter yourself.)

  • If you create the form or report based on a closed table or query, the filter won't be applied in the new form or report. You apply it when you need it.


 Modify an inherited sort order in a report

Modify an inherited sort order in a report

  1. Open the report in Design view, or if the report is already open, make sure it is selected.

  2. Click Properties [image] on the toolbar to display the report's property sheet.

  3. Click the OrderBy property box, and then specify the field and sort order you want to sort on.
    • To sort records in one field in ascending order, type the field name enclosed in brackets ([ ]) followed by ASC.

      [fieldname1] ASC

    • To sort records in one field in descending order, type the field name enclosed in brackets ([ ]) followed by DESC.

      [fieldname1] DESC

    • To sort records in more than one field in ascending or descending order, type the setting this way:

      [fieldname1] ASC,
      [      fieldname2] DESC

Note If you don't specify ASC or DESC after field names, Microsoft Access sorts in ascending order, the first listed field first, then the next listed field, and so on.


 Modify or delete an inherited filter in a report

Modify or delete an inherited filter in a report

  1. Open the report in Design view, or if the report is already open, make sure it is selected.

  2. Click Properties [image] on the toolbar to display the report's property sheet.

  3. In the Filter property box, modify or delete the SQL WHERE clause. If you delete the WHERE clause, set the FilterOn property to No.

Tip If you don't know SQL, change the filter in the underlying table or query, and then switch to Design view for the table or query and display its property sheet. Then copy the revised WHERE clause from its Filter property to the Filter property for the report.


 Remove or reapply an inherited sort order in a report

Remove or reapply an inherited sort order in a report

  1. Open the report in Design view, or if the report is already open, make sure it is selected.

  2. Click Properties [image] on the toolbar to display the report's property sheet.

  3. In the OrderByOn property box, click No to remove the sort order or Yes to reapply it.

Note If you specify a sort order in a report wizard or in the Sorting And Grouping dialog box in report Design view, it overrides the inherited sort order.


 About using criteria in queries or advanced filters to retrieve certain records

About using criteria in queries or advanced filters to retrieve certain records

Criteria are restrictions you place on a query or an advanced filter to identify the specific records you want to work with. For example, instead of viewing all the suppliers that your company uses, you can view just suppliers from Japan. To do this, you specify criteria that limits the results to records whose Country field is "Japan".

To specify criteria for a field in the design grid, enter an expression in the Criteria cell for that field. The expression in the preceding example would be "Japan". You can use more complicated expressions, however, such as "Between 1000 And 5000". If your query includes linked tables, the values you specify in criteria on fields from the linked tables are case-sensitive — they must match the case of the values in the underlying table.

You can enter additional criteria for the same field or different fields. When you type expressions in more than one Criteria cell, Microsoft Access combines them using either the And or the Or operator. If the expressions are in different cells in the same row, Microsoft Access uses the And operator, which means only the records that meet the criteria in all the cells will be returned. If the expressions are in different rows of the design grid, Microsoft Access uses the Or operator, which means records that meet criteria in any of the cells will be returned.

Examples of how to use multiple criteria in the design grid.

Records retrieved meet the criteria in both columns.

You can also specify criteria to affect the results of a calculation. By adding criteria, you can limit the groups for which you're performing a calculation, limit the records included in the calculation, or limit the results that are displayed after the calculation is performed. For information on where to enter criteria in a query that performs calculations, click [image] .


 Where to enter expressions in queries and filters

Where to enter expressions in queries and filters

You can use expressions — in the design grid of a query or the Advanced Filter/Sort window, in an SQL statement in a query's SQL view, or in the Filter By Form window — to specify criteria that identify the records you want to work with. In queries, you can also use expressions to update values in a group of records or to create calculated fields.

In the design grid, you enter the expression in different places depending on the operation you're trying to perform. (The following table shows where you can enter expressions.) After you type an expression in the design grid and press the ENTER key, Microsoft Access displays the expression using syntax it understands. If you don't include an operator with the expression, Microsoft Access assumes you mean the = operator. For example, if you type Denmark as the criteria in a Country field, Microsoft Access displays "Denmark", and interprets the expression as Country="Denmark". If you include references to field names in the expression, the fields must be in one of the tables added to the query (unless you are using the DLookup function or a subquery). You can't drag the fields to the expression in the design grid, however.

To do this | Type the expression in
Specify criteria for a select, crosstab, or action query, or for an advanced filter | A Criteria cell in the design grid of a query or advanced filter.
Create a calculated field | A Field cell in the design grid of a query or advanced filter.
Update records according to the results of the expression (update queries only) | An Update To cell in the design grid of an update query.
Specify the records you want to work with, how they are grouped, the criteria for the groupings, or how records are sorted | An SQL statement in SQL view.
Specify criteria when using Filter By Form | A field in the Filter By Form window for a custom expression, or select an expression from the list in the field.

Note You can see how Microsoft Access evaluates query expressions by switching to a query's SQL view to display its underlying SQL statements. To display a query in SQL view, click the arrow next to the View button on the toolbar, and then click SQL View. If your query includes linked tables, the values you specify in criteria on fields from the linked tables are case-sensitive — they must match the case of the values in the underlying table.


Create an expression

What do you want to do?

Create an expression using the Expression Builder

Create an expression on my own

Read more about what expressions are

See examples of expressions

Not sure which choice you want?


Examples of expressions used in queries and filters

What do you want to do?

See examples of expressions that perform calculations on or manipulate field values

See examples of expressions used as criteria to limit the records you work with

See examples of expressions used to update data in an update query

See examples of expressions used in SQL statements in query SQL view

Learn where to enter expressions in queries and filters

Learn how to create an expression


 Ways to filter records for a data access page

Ways to filter records for a data access page

This topic provides reference information about:

Ways to filter records before they are retrieved from the database

Ways to filter records after they are retrieved from the database

Ways to filter records before they are retrieved from the database

To filter the records before the data access page retrieves them, you can base your page on a query that includes criteria (search conditions) to limit the records. Alternatively, in a Microsoft Access project you can define a filter in the ServerFilter property in Visual Basic for Applications or Microsoft Visual Basic Scripting Edition (VBScript), and in a Microsoft Access database you can define a filter by using the Filter property in Visual Basic for Applications or Microsoft Visual Basic Scripting Edition (VBScript). On a grouped data access page, you can create a filter that retrieves data for a specific group, such as orders for a specific customer. The data access page won't display any records until you choose the group from a drop-down list in Page view or Microsoft Internet Explorer. Once you choose the group, the filter is applied and only those records are retrieved. You can create a filter for ungrouped data access pages, too. Instead of choosing the group whose records you want to see, you choose a value from a field you designated as the filter field. This is similar to using Filter By Form. All records that contain that value are retrieved.

Note Filtering records before they are retrieved can improve data access page performance because there are fewer records to download from the underlying database.

Return to top

Ways to filter records after they are retrieved from the database

To filter records after they are retrieved for the current data access page in either Page view or the browser, use Filter By Selection. With this type of filter, you select in a field the value you want the filtered records to contain. In data access page Design view, you can also add a filter to a hyperlink on a page. Then, when you click the link in Page view or the browser, only the records specified in the filter are displayed on the page you jump to.

Return to top

Return to Create a filter for a data access page


Create a filter for a data access page

With a filter, you can limit the data access page to a specific subset of records you want to view or work with.

What do you want to do?

Limit records before they are retrieved from the database

Create a filter that finds records on an ungrouped data access page

Create a filter on a grouped data access page

In a Microsoft Access project, create a filter using Visual Basic for Applications or Microsoft Visual Basic Scripting Edition (VBScript)

In a Microsoft Access database, create a filter in Visual Basic for Applications or VBScript

Limit records after they are retrieved from the database

Create a filter in Page view to limit records after they've been retrieved

Create a hyperlink that filters the records on a data access page that the link jumps to

Not sure which choice you want?


 Find specific data by using a filter on a data access page in Page view

Find specific data by using a filter on a data access page in Page view

With a filter, you can find records based on whether they contain a specific value in a particular field. For example, you can find all records that have "Germany" in the Country field. When you apply the filter, only the records that contain the value that you selected will show in the data access page. Once you remove the filter, all the records will be displayed again. For grouped data access pages, you can filter the list of groups (the group headings) or the records within groups.

  • In a field in Page view of a data access page, select the value that you want to use to filter records, and then click Filter By Selection [image] on the record navigation toolbar.

    For grouped data access pages, display the records within the group that you want to filter, select the value you want to filter for, and then click Filter By Selection [image] on the record navigation toolbar for that group. The filter only applies to the current group. In other words, if a page groups customer orders by country, and you filter the records for Brazil that have a required date of 6/2/98, that filter only applies to the records for Brazil, not to the records for the other countries.

    You can further narrow the subset of records by continuing to select values and clicking Filter By Selection [image] until you have just the records you want. For example, if you only want to see records for customers in Germany with a required date of 5/12/98, you select "Germany" in the Country field, click Filter By Selection [image], select "5/12/98" in the Required Date field, then click Filter By Selection [image] again.

Notes

  • If you only select part of the value in a field, the data access page still uses the entire field value for filtering.

  • You can remove the filter and then reapply it during the same working session.

  • This procedure doesn't apply to a PivotTable list or spreadsheet. These features can be filtered independent of the rest of the data on the data access page and may also support additional filtering capabilities. For more information, click Help [image] on the toolbar for the PivotTable list or spreadsheet, and then search for “filters.”


 Remove a filter to show all records in a data access page in Page view

Remove a filter to show all records in a data access page in Page view

  • In Page view of a data access page, click Remove Filter Filter object on the record navigation toolbar.

Notes

  • Removing a filter doesn't delete it. You can reapply the filter, even after closing and reopening the data access page, by clicking Apply Filter Filter object on the record navigation toolbar.

  • This procedure doesn't apply to a PivotTable list or spreadsheet. These features can be filtered independent of the rest of the data on the data access page and may also support additional filtering capabilities. For more information, click Help [image] on the toolbar for the PivotTable list or spreadsheet, and then search for “filters.”


 Apply an existing filter to a data access page in Page view

Apply an existing filter to a data access page in Page view

You can reapply a filter that you created in an earlier working session.

  • In Page view of a data access page, click Apply Filter Filter object on the record navigation toolbar. For grouped data access pages, display the records within the group that you want to filter, then click Apply Filter Filter object on the record navigation toolbar for that group.

Note This procedure doesn't apply to a PivotTable list or spreadsheet. These features can be filtered independent of the rest of the data on the data access page, and may also support additional filtering capabilities. For more information, click Help [image] on the toolbar for the PivotTable list or spreadsheet, and then search for “filters.”


 Sort records in a table, query, or form

Sort records in a table, query, or form

You can sort records in Form view of a form, or in Datasheet view of a table, query, or form, even if a filter is already applied. You can also sort filtered data by specifying a sort order in the Advanced Filter/Sort window, or sort a query's results by specifying a sort order in query Design view.

What do you want to do?

Sort records in Datasheet view or Form view

Sort filtered records using the Advanced Filter/Sort window, or records that a query retrieves using query Design view

Not sure which choice you want?


 Sort data on a data access page in Page view

Sort data on a data access page in Page view

You can sort the data on a data access page, including data that's grouped. For grouped data access pages, you can sort the list of groups or the records within a group.

  1. In Page view of a data access page, click in the field you want to use for sorting records. For grouped pages, display the records within a particular group that you want to sort, and then select the value you want to sort on.

  2. Do one of the following:
    • To sort in ascending order, click Sort Ascending [image].

    • To sort in descending order, click Sort Descending [image].

Notes

  • When you sort records within a group, the sort order only applies to that group. It does not affect the order of records in other groups. For example, say a data access page is grouped by region, the region names are listed in ascending order, and under each region, employees are listed in ascending order by their last name. If you display employee records for Mexico, and then sort employees in descending order by last name, the employee records for other regions will still be sorted in ascending order, as will the list of regions themselves.

  • To change the sort order, click in the field that you want to sort, and then click the sort button you want.

  • When you close the data access page, you'll lose the sort order. You can sort the records again when you open the page.

  • The order in which numbers, text, and special characters are sorted depends on the database and your regional settings in Windows Control Panel.

  • This procedure doesn't apply to a PivotTable list or spreadsheet. These features can be sorted independent of the rest of the data on the data access page and may also support additional sorting capabilities. For more information, click Help [image] on the toolbar for the PivotTable list or spreadsheet, and then search for “sorting.”


 Remove a sort order from a table, query, or form

Remove a sort order from a table, query, or form

  • In Datasheet view or Form view, click Remove Filter/Sort on the Records menu. If you specified the sort order in the Advanced Filter/Sort window where you also specified criteria for a filter, you can delete the sort order in the Sort cell in the design grid and still leave the filter's criteria intact.


 Considerations when sorting records in a table, query, form, or report

Considerations when sorting records in a table, query, form, or report

  • Sort orders are saved with a table, query, or form. If you base a new form or report on a table or query that has a sort order saved with it, the new form or report inherits the sort order.

  • Microsoft Access will sort on up to 255 characters, in one or more fields, in the results of a query or advanced filter.

  • Sort order depends on the language setting you specify in the Options dialog box at the time you create your database. To check or change this setting, click Options on the Tools menu, and then click the General tab to see the setting under New Database Sort Order. If your database contains linked tables from a database that uses a different language sort order, Microsoft Access uses the sort order of the database that contains the link to the table, not the database where the table is stored.

  • If the design grid for the query or filter contains the asterisk from the field list, you can't specify a sort order in the design grid unless you also add the fields you want to sort on to the design grid. For more information, click [image] .

  • To sort dates and times from earlier to later, use ascending order. Use descending order to sort from later to earlier.

  • Numbers stored in Text fields are sorted as strings of characters, not numeric values. Therefore, to sort them in numeric order, all text strings must be the same length with shorter numbers padded with leading zeros. For example, the result of an ascending sort of the text strings "1", "2", "11", and "22" will be "1", "11", "2", "22". You must pad the single-digit numbers with a leading zero for the strings to be sorted properly: "01", "02", "11", "22". For fields that don't contain Null values, another solution would be to sort on the numeric values of the strings by using the Val function. For example, if the Age column is a Text field that contains numeric values, specifying Val([Age]) in a Field cell and specifying a sort order in its Sort cell will put the records in the correct order. If you are only storing numbers or dates in a Text field, consider changing the field's data type to Number, Currency, or Date/Time in the table where the field is stored. Then, when you sort on the field, the numbers or dates will sort in numeric or date order without requiring leading zeros.

  • When you sort a field in ascending order, any records in which that field is blank (contains a Null value) are listed first. If a field contains records with both Null values and zero-length strings, the fields with null values appear first in the sort order, immediately followed by the zero-length strings.

  • You can't sort a field whose data type is Memo, Hyperlink, or OLE Object.


 About sharing an Access database on a network

About sharing an Access database on a network

If your computer is connected to a network, you and others can work with one Microsoft Access database at the same time. There are several ways you can share data in a multiuser environment. This topic provides reference information about:

Sharing the entire Access database

Sharing only the tables in the Access database

Sharing the Access database on the Internet

Replicating the Access database

Creating a client/server application

Share the entire Access database

You can put the entire Access database on a network server or in a shared folder. This is the easiest method to implement. Everyone shares the data and uses the same forms, reports, queries, macros, and modules. Use this strategy if you want everyone to use the Access database the same way or you can't support users creating their own objects. Learn about sharing a database on a network server.

Return to top

Share only the tables in the Access database

You can put only the tables on a network server, and keep other database objects on users' computers. In this case, the Access database's performance is faster because only data is sent across the network. Also, users can customize their forms, reports, and other objects for their individual needs and preferences without affecting other users.

You can separate the tables from the other database objects by using the Database Splitter Wizard.

Return to top

Share Access database objects or data access pages on the Internet

You can output one or more database objects to static HTML or server-generated HTML format, or create data access pages, and then display them in a browser, such as Internet Explorer, on the World Wide Web. Learn about the three types of Web pages Access creates.

Return to top

Replicate the Access database

If you use two computers, such as an office computer and a portable computer, you can use Microsoft Windows Briefcase to make replicas of your Access database and keep those replicas synchronized. Also, several users at different locations can work on their own copies at the same time and then synchronize them over the network, either through a dial-up connection or on the Internet. Learn about replicating a database.

Return to top

Create a client/server application

If you work in a client/server environment, you can take advantage of the extra power and security it provides by creating a client/server application. For more information, see Chapter 16, "Multiuser Database Applications," in the Microsoft Office 2000/Visual Basic Programmer's Guide.

Return to top


About editing data in an Access database in a multiuser environment

In a multiuser environment, more than one person might be working with the same records at the same time. Since other people can change or even delete the same data you're trying to edit, you might occasionally conflict with others as they work.

Microsoft Access helps you keep track of the status of records as you edit them, and makes sure you're using the latest data. When two or more people try to edit the same record, Microsoft Access displays messages that help you resolve conflicts. For example, if you try to save a record that another user has locked, Microsoft Access displays the name of the person who locked that record.

To help you keep track of the status of records, Microsoft Access displays the following symbols in the current record selector.

Symbol | Meaning
 | This record is the current record and hasn't been edited.
 | You have edited this record, but you haven't saved your changes yet. As long as this symbol is displayed, other users can't see the changes you've made to the record, and they won't be able to edit the record, if you have the record locked. To free the record for use by others, either save or undo your changes.
 | This record is locked by another user. You can't edit it. If you try to type in a locked record, Microsoft Access sounds a beep.

For information on choosing a record-locking strategy, click [image] .


 About saving design changes to a shared Microsoft Access database

About saving design changes to a shared Microsoft Access database

This topic provides reference information about:

Saving design changes to a shared Microsoft Access database

Differences between major and minor design changes

Strategies for sharing Access database design and development

More information

Saving design changes to a shared Microsoft Access database

You cannot save design changes to an Access database while other users are sharing the Access database with you. The only way to ensure that changes are saved is by opening the Access database in exclusive mode.

In general, when you try to make a design change to a database object (except tables and queries) or an item in shared mode, Access will temporarily promote you to exclusive mode for the Access database, if you are the only user of the Access database at that time. When you save all your design changes and close all the Design view windows, Access returns the Access database to shared mode. In the interim, other users will not be able to open the Access database.

If another user has the Access database open in shared mode and you try to make a major design change, such as modifying a form, Access alerts you that you might not be able to save your changes. If another user has the Access database open in shared mode and you try to make a minor design change, such as changing printer settings, Access doesn't alert you that you might not be able to save your design changes. In both cases, you might want to wait until you are the only user of the Access database so that you can save your major design changes and Access can save your minor design changes.

A data access page is handled differently. Although creating, renaming, moving, and deleting a data access page still requires promotion to exclusive mode (because this requires changing information in the Access database), editing a data access page does not require promotion to exclusive mode (because the corresponding HTML file exists in the file system outside the database).

Return to top

Differences between major and minor design changes

If you don't have exclusive access to an Access database, Access will alert you when you might not be able to save the following major design changes:

  • Changes to database objects (except table and queries) made in Design view

  • Changes to a form property sheet in Form view

  • Compiling the project, modifying project properties, or adding or removing a reference in the Visual Basic Editor

  • Renaming, pasting, or deleting a database object

  • Saving a database object as another type of database object

  • Adding or modifying controls on a command bar

  • Editing custom groups in the Database window

  • Creating, renaming, moving, and deleting a data access page

If you don't have exclusive access to an Access database, Access doesn't alert you when you might not be able to save the following minor design changes:

  • Changes to datasheet formatting properties, such as line styles and fonts

  • Freezing, unfreezing, hiding, and showing datasheet columns

  • Adjusting datasheet column width and row size

  • Changes to the filter or sort order for a form or datasheet

  • Changes to the state of a subdatasheet (whether expanded or collapsed)

  • Changes to the OLE/DDE link of an OLE object or changing the contents of an unbound object frame

  • Changes to printer settings

  • Changes to a command bar, such as it's location and whether or not it's visible

  • Changes to the layout of the Database window

Return to top

Strategies for sharing Access database design and development

If you are going to share the design of an Access database, consider using the following strategies:

  • Assign specific objects or groups of objects to specific developers. For example, one developer designs forms and another designs reports. Then, each developer can work on a private copy of the Access database. When your development team is ready for testing, assembly, and production, each developer can export the database objects from their private copy of the database to a main Access database.

  • Use a source code control program. For example, you can use a combination of Microsoft Visual SourceSafe version 6.0, and the Source Code Control add-in that enables Visual Source Safe Code support in Access. This add-in is available from the Microsoft Office 2000 Developer (MOD). If you do use Visual SourceSafe, it's a good idea to run the Performance Analyzer (on the Tools menu, point to Analyze, and then click Performance) on a regular basis to maintain optimum performance.

Return to top

More information

Learn about sharing Access databases on a network

Split an Access database between its data and its objects

Open an Access database

Specify whether an Access database opens in shared or exclusive mode by default

Return to top


 About choosing a record-locking strategy in an Access database in a multiuser environment

About choosing a record-locking strategy in an Access database in a multiuser environment

When you edit a record, Microsoft Access can automatically prevent other users from changing the record before you have finished editing it.

Giving one user exclusive access to a record is called locking. There are three locking strategies to choose from:

  • No Locks — Microsoft Access does not lock the record you're editing. When you try to save changes to a record that another person has also changed, Microsoft Access displays a message giving you the options of overwriting the other user's changes to the record, copying your version of the record to the Clipboard, or discarding your changes. This strategy ensures that records can always be edited, but it can create editing conflicts between users.

  • Edited Records — Microsoft Access locks the record you're editing, so no other user can change it. It might also lock other records that are stored nearby on your disk. If another user tries to edit a record that you've locked, Microsoft Access displays the locked record indicator [image] in the other user's datasheet. This strategy ensures that you can always finish making changes that you start. It is a good choice if you don't have editing conflicts often.

  • All Records — Microsoft Access locks all records in the form or datasheet (and underlying tables) you're editing for the entire time you have it open, so no one else can edit or lock the records. This strategy is very restrictive, so choose it only when you know you're the only person who needs to edit records at any one time.

For information on specifying one of these options, click [image] .

Note When you edit data in a linked SQL database table by using ODBC, Microsoft Access doesn't lock records; instead, the rules of that SQL database govern locking. In this instance, regardless of the record-locking setting you choose for your database, Microsoft Access always acts as though the No Locks setting has been selected.


 Ways to optimize multiuser performance in an Access database

Ways to optimize multiuser performance in an Access database

The following guidelines can help you optimize the performance of Microsoft Access databases that are used in a multiuser environment.

  • Put only the tables on a network server, and keep other database objects on users' computers. The database's performance will be faster because only data is sent across the network. You can separate the tables from other database objects by using the Database Splitter Wizard. For more information, click [image] .

  • Choose an appropriate record-locking strategy. For more information, click [image] .

  • Choose a locking level strategy.

  • Avoid locking conflicts by adjusting Refresh Interval, Update Retry Interval, Number Of Update Retries, and ODBC Refresh Interval settings (if applicable). For more information, click [image] .

  • Optimize table performance. For more information, click [image] .

  • Improve the performance of Access databases with linked tables. For more information, click [image] .

  • Improve the performance of Access tables linked to an SQL table. For more information, click [image] .

  • Convert the workgroup information file. For more information, click [image] .


 Share an Access database on a network server

Share an Access database on a network server

  1. Set up a shared folder on a network server. You might need assistance from your network administrator.

  2. Copy the Microsoft Access database to the network server.

  3. Make sure the Access database is set to open in shared mode, which is the default setting.

    How?

Note To access the shared Access database from another computer, you must have one of following on the other computer: a local installation of Microsoft Access, a network installation of Microsoft Access (licensed on a per-user basis), or a run-time application. You can obtain a royalty-free license to install your run-time application on each computer when you purchase Microsoft Office 2000 Developer (MOD).


 Share an Access database when a network server doesn't exist

Share an Access database when a network server doesn't exist

  1. Copy the Microsoft Access database to a shared folder. (For information on sharing folders, use the Microsoft Windows Help Index.)

  2. Make sure the Access database is set to open in shared mode, which is the default setting.

    How?

Note To access the shared Access database from another computer, you must have one of following on the other computer: a local installation of Microsoft Access, a network installation of Microsoft Access (licensed on a per-user basis), or a run-time application. You can obtain a royalty-free license to install your run-time application on each computer when you purchase Microsoft Office 2000 Developer (MOD).


 Split an existing Access database between its data and its objects

Split an existing Access database between its data and its objects

This procedure splits a Microsoft Access database into two files: one that contains the tables and one that contains the queries, forms, reports, macros, modules, and shortcuts to data access pages. This way, users who need to access the data can customize their own forms, reports, pages, and other objects while maintaining a single source of data on the network.

  1. On the Tools menu, point to Database Utilities, and then click Database Splitter.

  2. Follow the instructions in the Database Splitter Wizard dialog boxes.


 Specify whether an Access database opens in shared or exclusive mode by default

Specify whether an Access database opens in shared or exclusive mode by default

This procedure affects the way a Microsoft Access database is opened only on your computer. It does not affect the default for users on other computers.

  1. On the Tools menu, click Options.

  2. Click the Advanced tab.

  3. If you want others to be able to open the Access database at the same time you have it open, click Shared.

    If you want sole access to the Access database when you have it open, click Exclusive.

Notes

  • When you open an Access database in a multiuser environment, you can open it in exclusive and/or read-only mode, even if you specify shared mode by default. For more information, click [image] .

  • If you set up security in your multiuser environment, you can ensure that users don't open an Access database exclusively by denying them Open Exclusive permission for the database. For more information on removing permissions, click [image] .

  • When you open an Access database file (.mdb) in shared mode, Microsoft Access also creates a locking information file (.ldb) with the same file name (for example, Northwind.ldb) and in the same folder as the database file. This locking information file stores the computer name (such as mypc) and security name (such as Admin) of each shared user of the database. Microsoft Access uses this information to control concurrency. In most cases, Microsoft Access automatically deletes the locking information file when the last user closes the database file.


 Tips for editing Access database objects in a multiuser environment

Tips for editing Access database objects in a multiuser environment

  • It's a good idea to design objects before you allow other users to open the Microsoft Access database for shared access. When you want to make design changes, you can ensure that you're the only one using the Access database when you open it by clicking Open Exclusive on the Open button in the Open dialog box. Learn about saving changes to a shared Microsoft Access database.

  • If another user has a table open or is viewing data in queries, forms, or reports based on the table, you can't make any changes to the table's design. Microsoft Access informs you that it is read-only.

  • If objects are dependent on one another, update all of them at the same time so that other users don't open inconsistent versions of the objects. For example, if you want to add fields to a form, make sure to add the fields to the underlying query before you update the form.

  • If you change a query that another user has open, that user must close and reopen the changed object to use the latest version. With Visual Basic for Applications modules, other users can't run the updated Function or Sub procedures until they close and reopen the Access database.


Specify the default record-locking strategy used in a multiuser environment in an Access database

  1. On the Tools menu, click Options.

  2. Click the Advanced tab.

  3. In the Default Record Locking box, click the option you want.

    For information on these options, click [image] .


 Specify the locking level used in an Access database in a multiuser environment

Specify the locking level used in an Access database in a multiuser environment

  1. On the Tools menu, click Options.

  2. Click the Advanced tab.

  3. To make record-level locking the new default setting for the current Microsoft Access database, select the Open databases using record-level locking check box.

    To make page-level locking the new default setting for the current Access database, clear the Open databases using record level locking check box.

Notes

  • This setting takes place the next time you open the Access database, but you must use the Open command on the File menu rather than the list of most recently used files at the end of the File menu. This behavior is the same as the setting for the default open mode.

  • If you select Open databases using record level locking, this becomes the default behavior for access to data through a form, a datasheet, and code that uses a recordset object to loop through records, but not through action queries, nor through code that performs bulk operations using SQL statements. For more information, see Chapter 16, "Multiuser Database Applications," in the Microsoft Office 2000/Visual Basic Programmer's Guide.


 Ways to avoid data-locking conflicts in an Access database in a multiuser environment

Ways to avoid data-locking conflicts in an Access database in a multiuser environment

There are four settings that help you avoid data-locking conflicts with other users in a Microsoft Access database in a multiuser environment:

  • Refresh Interval (sec) — sets the number of seconds after which Microsoft Access automatically updates records in Datasheet or Form view. Valid values are 0 through 32,766 seconds. When you refresh the current datasheet or form, Microsoft Access doesn't reorder records, add new records, or remove deleted records. To view these changes, you must requery the underlying records for the datasheet or form.

  • Update Retry Interval (msec) — sets the number of milliseconds after which Microsoft Access automatically tries to save a changed record that is locked by another user. Valid values are 0 through 1,000 milliseconds.

  • Number of Update Retries — sets the number of times Microsoft Access tries to save a changed record that is locked by another user. Valid values are 0 through 10.

  • ODBC Refresh Interval (sec) — sets the interval after which Microsoft Access automatically refreshes records that you're accessing using ODBC. Valid values are 1 through 32,766 seconds.

For information on specifying one of these options, click [image] .


Specify multiuser/ODBC update retry and refresh interval settings in an Access database

  1. On the Tools menu, click Options.

  2. Click the Advanced tab.

  3. Type values in the boxes for the options you want to change.

    For information on these options, click [image] .


 Display the most current data in an Access database in Datasheet or Form view

Display the most current data in an Access database in Datasheet or Form view

If you are using a Microsoft Access database that's shared on a network, other users could be changing data while you are viewing the same data in a datasheet or form. Microsoft Access updates the data you see at regular intervals. You can change how often data is automatically updated. For more information, click [image] .

Follow this procedure to display the most current data immediately.

  1. Open a table, query, or form in Datasheet view, or a form in Form view.

  2. Click Refresh on the Records menu.

The Refresh command updates only data that already exists in your datasheet or form. It doesn't reorder records, display new records, or remove deleted records and records that no longer meet specified criteria. To perform those actions, requery the records by pressing SHIFT+F9.


 Change how often data is updated automatically in an Access database in Datasheet or Form view

Change how often data is updated automatically in an Access database in Datasheet or Form view

  1. Open a table, query, or form in Datasheet view, or a form in Form view.

  2. Click Options on the Tools menu.

  3. Click the Advanced tab.

  4. In the Refresh Interval box, type the number of seconds you want between each automatic update of data. For example, if you type 120, the data is updated every 2 minutes.

Note This setting takes effect only if the database is shared on a network. It updates only data that already exists in your datasheet or form. It doesn't reorder records, display new records, or remove deleted records and records that no longer meet specified criteria. To perform those actions, requery the records by pressing SHIFT+F9.


 Moving between records using navigation buttons in Datasheet or Form view

Moving between records using navigation buttons in Datasheet or Form view

The navigation buttons are located at the bottom of the window in Datasheet or Form view. You can use these buttons to quickly move between records.

Record navigation buttons


 Move between fields in long records with the Go To Field box in Datasheet view

Move between fields in long records with the Go To Field box in Datasheet view

Adding the Go To Field box makes it easier to move between fields in long records in Datasheet view.

  1. Open a table, query, form, view, or stored procedure in Datasheet view.

  2. Click Toolbars on the View menu.

  3. Select Formatting (Datasheet).

  4. Click Close.

The Go To Field box is the leftmost item on the Formatting (Datasheet) toolbar. Use it to click the name of the field in the current record that you want to move to.


 Move columns in Datasheet view

Move columns in Datasheet view

  1. Open a table, query, form, view, or stored procedure in Datasheet view.

  2. Select the columns you want to move.

    To select one column, click the field selector for that column.

    To select adjacent columns, click a column field selector and then, without releasing the mouse button, drag to extend the selection.

  3. Click and hold down the mouse button in the field selector(s) again.

  4. Drag the columns to a new position.

Notes

  • If the columns don't move, they may be frozen. Learn about frozen columns.

  • You can't save datasheet formatting changes to a datasheet in a Microsoft Access project unless it is a form. If you need to save formatting changes to an Access project table, view, or stored procedure datasheet, use the AutoForm Wizard to create the datasheet as a form (which quickly sets the RecordSource property to the datasheet and adds all the fields to the form), and then set the form's DefaultView and ViewsAllowed properties to Datasheet (which makes the form behave like a datasheet).


 Resize a column in Datasheet view

Resize a column in Datasheet view

  1. Open a table, query, form, view, or stored procedure in Datasheet view.

  2. Position the pointer on the right edge of the column you want to resize, as shown in the following illustration.

    Changing the column width or sizing it to fit its data

  3. Drag until the column is the desired width.

Notes

  • You can't undo changes to the width of columns using the Undo command on the Edit menu. To undo changes, close the datasheet, and then click No to All when asked if you want to save changes to the layout of the datasheet.

  • You can't save datasheet formatting changes to a datasheet in a Microsoft Access project unless it is a form. If you need to save formatting changes to an Access project table, view, or stored procedure datasheet, use the AutoForm Wizard to create the datasheet as a form (which quickly sets the RecordSource property to the datasheet and adds all the fields to the form), and then set the form's DefaultView and ViewsAllowed properties to Datasheet (which makes the form behave like a datasheet).


 Resize rows in Datasheet view

Resize rows in Datasheet view

  1. Open a table, query, form, view, or stored procedure in Datasheet view.

  2. Position the pointer between two record selectors at the left side of the datasheet, as shown in the following illustration.

    Changing the row height for all rows

  3. Drag the edge of the row until the row is the desired height.

Notes

  • This resizes all the rows in the datasheet at the same time.

  • You can't undo changes to the size of rows using the Undo command on the Edit menu. To undo changes, close the datasheet, and then click No to All when asked if you want to save changes to the layout of the datasheet.

  • You can't save datasheet formatting changes to a datasheet in a Microsoft Access project unless it is a form. If you need to save formatting changes to an Access project table, view, or stored procedure datasheet, use the AutoForm Wizard to create the datasheet as a form (which quickly sets the RecordSource property to the datasheet and adds all the fields to the form), and then set the form's DefaultView and ViewsAllowed properties to Datasheet (which makes the form behave like a datasheet).


 Freeze and unfreeze columns in Datasheet view

Freeze and unfreeze columns in Datasheet view

You can freeze one or more of the columns on a datasheet so that they become the leftmost columns and are visible at all times no matter where you scroll.

  1. Open a table, query, form, view, or stored procedure in Datasheet view.

  2. Select the columns you want to freeze.

    To select the column, click the field selector for that column.

    To select more than one of the column, click the column field selector and then, without releasing the mouse button, drag to extend the selection.

  3. To freeze the selected columns, click Freeze Columns on the Format menu.

    To unfreeze all columns, click Unfreeze All Columns on the Format menu.

Note You can't save datasheet formatting changes to a datasheet in a Microsoft Access project unless it is a form. If you need to save formatting changes to an Access project table, view, or stored procedure datasheet, use the AutoForm Wizard to create the datasheet as a form (which quickly sets the RecordSource property to the datasheet and adds all the fields to the form), and then set the form's DefaultView and ViewsAllowed properties to Datasheet (which makes the form behave like a datasheet).


 Hide columns in Datasheet view

Hide columns in Datasheet view

  1. Open a table, query, form, view, or stored procedure in Datasheet view.

  2. Select the column(s) you want to hide.

    To select one column, click the field selector for that column.

    To select adjacent columns, click a column field selector and then, without releasing the mouse button, drag to extend the selection.

  3. On the Format menu, click Hide Columns.

Notes

  • For information on showing hidden columns, click [image] .

  • You can't save datasheet formatting changes to a datasheet in a Microsoft Access project unless it is a form. If you need to save formatting changes to an Access project table, view, or stored procedure datasheet, use the AutoForm Wizard to create the datasheet as a form (which quickly sets the RecordSource property to the datasheet and adds all the fields to the form), and then set the form's DefaultView and ViewsAllowed properties to Datasheet (which makes the form behave like a datasheet).


 Show hidden columns in Datasheet view

Show hidden columns in Datasheet view

  1. Open a table, query, form, view, or stored procedure in Datasheet view.

  2. Click Unhide Columns on the Format menu.

  3. In the Unhide Columns dialog box, select the names of the columns that you want to show.

Note You can't save datasheet formatting changes to a datasheet in a Microsoft Access project unless it is a form. If you need to save formatting changes to an Access project table, view, or stored procedure datasheet, use the AutoForm Wizard to create the datasheet as a form (which quickly sets the RecordSource property to the datasheet and adds all the fields to the form), and then set the form's DefaultView and ViewsAllowed properties to Datasheet (which makes the form behave like a datasheet).


 Set defaults for the appearance of Datasheet view

Set defaults for the appearance of Datasheet view

  1. Open a table, query, form, view, or stored procedure in Datasheet view.

  2. Click Options on the Tools menu.

  3. Click the Datasheet tab.

  4. Click the options you want.

Note These options do not override any changes you have previously made to specific datasheets using the Format menu commands. If you want those specific datasheets to also have the same format, you must make the changes in the specific datasheets using the Format menu commands or remove the saved properties using Visual Basic code.


 Change font, or font style, size, and color in Datasheet view

Change font, or font style, size, and color in Datasheet view

  1. Open a table, query, form, view, or stored procedure in Datasheet view.

  2. Click Font on the Format menu.

  3. Click the options you want.

Notes

  • Changing the format of a specific datasheet overrides the default datasheet format defined in the Datasheet tab of the Options dialog box on the Tools menu.

  • You can't save datasheet formatting changes to a datasheet in a Microsoft Access project unless the datasheet is a form. If you need to save formatting changes to an Access project table, view, or stored procedure datasheet, use the AutoForm Wizard to create the datasheet as a form (which quickly sets the RecordSource property to the datasheet and adds all the fields to the form), and then set the form's DefaultView and ViewsAllowed properties to Datasheet (which makes the form behave like a datasheet).


 Change the gridline style and background color in Datasheet view

Change the gridline style and background color in Datasheet view

  1. Open a table, query, form, view, or stored procedure in Datasheet view.

  2. Click Datasheet on the Format menu.

  3. Click the options you want.

Notes

  • Changing the format of a specific datasheet overrides the default datasheet format defined in the Datasheet tab of the Options dialog box on the Tools menu.

  • You can't save datasheet formatting changes to a datasheet in a Microsoft Access project unless it is a form. If you need to save formatting changes to an Access project table, view, or stored procedure datasheet, use the AutoForm Wizard to create the datasheet as a form (which quickly sets the RecordSource property to the datasheet and adds all the fields to the form), and then set the form's DefaultView and ViewsAllowed properties to Datasheet (which makes the form behave like a datasheet).


 Add a field (column) to a table in Datasheet view

Add a field (column) to a table in Datasheet view

  1. Open the table in Datasheet view.

  2. Click in the column to the right of where you want to insert a new column, and then on the Insert menu, click Column.

  3. Double-click the new column's name, and then type a name for the column following Microsoft Access object-naming rules.

    If you want to customize a field's definition further — for example, to change its data type, or define a validation rule, use table Design view.

Note If this is a linked table, the Column command will be unavailable. If the linked table is a Microsoft Access table, you must open its source database to add a field. If the linked table is from another application, you must open the source file with that application to add a field.


 About using subdatasheets

About using subdatasheets

This topic provides reference information about:

What is a subdatasheet?

Ways to use a subdatasheet

Table and query subdatasheets

Nesting subdatasheets

Forms, subforms, and subdatasheets

Comparing subdatasheets in a Microsoft Access database and a Microsoft Access project

More information

What is a subdatasheet?

In a subdatasheet, you can view and edit related or joined data in a table, query, or form datasheet, or in a subform. For example, in the Northwind sample database the Suppliers table has a one-to-many relationship with the Products table; so for each row of the Suppliers table in Datasheet view, you can view and edit the related rows of the Products table in a subdatasheet.

Suppliers table in Datasheet view containing a subdatasheet of the Products table

Return to top

Ways to use a subdatasheet

Access automatically creates a subdatasheet in a table that is in a one-to-one relationship, or is on the "one" side of a one-to-many relationship, when the SubdatasheetName property of the table is set to Auto. A relationship is defined by matching primary key and foreign key fields in the related tables. Learn about defining relationships.

However, you can add a subdatasheet to any table, query, or form. A subdatasheet can have as its source object a table or query (specified in the SubdatasheetName property). A subdatasheet corresponding to a subform control can have as its source object a table, query, or form (specified in the subform control's SourceObject property).

Return to top

Table and query subdatasheets

Both a table and a query in Datasheet view can contain either a table or query subdatasheet. If a table has a one-to-many relationship with more than one other table, you can choose which table to add as a subdatasheet by clicking the expand indicator icon (+) and selecting a table in the Insert Subdatasheet dialog box.

By default, Access does not display the foreign key or matching field(s) in the subdatasheet. You can temporarily show the foreign key or matching field(s) by using the Unhide Columns command (Format menu), but the next time you open the datasheet containing the subdatasheet, the column(s) will be hidden again. Hiding or showing these fields changes only the appearance of the subdatasheet; it does not modify any relationship or source object.

You can add a subdatasheet to a table or query in Datasheet view, or modify a subdatasheet, by using the Subdatasheet command (Insert menu). You specify the matching fields between the datasheet and subdatasheet in the List Child Fields and Link Master Fields boxes in the Insert Subdatasheet dialog box. These boxes correspond to the LinkChildFields and LinkMasterFields properties of the table or query containing the subdatasheet. If you leave these boxes blank, Access displays all rows of the subdatasheet under every row in the datasheet, not just the rows in the subdatasheet that match.

Return to top

Nesting subdatasheets

You can nest (up to eight levels) a subdatasheet within a subdatasheet. However, each datasheet or subdatasheet can have only one nested subdatasheet. For example, in the Northwind sample database, the Customers table can contain one Orders table subdatasheet, and the Orders table subdatasheet can contain one Orders Details subdatasheet. But the Customers table can't contain both an Orders table subdatasheet and a Salespeople query subdatasheet.

Return to top

Forms, subforms, and subdatasheets

A form in Form view or Datasheet view can also have a subdatasheet, but there are differences between a form subdatasheet and a table or query subdatasheet:

  • You insert a subdatasheet into a form by adding a subform control, and then defining a source object by setting the subform control's SourceObject property to a table, query, or form. A form's subdatasheet corresponds to a subform. If the subform's source object is a form, its DefaultView property can be set to Datasheet, Single View, or Continuous Form. Therefore, in form Datasheet view, you can also see the subdatasheet displayed as a single or continuous form. You can switch between Datasheet view and Form view in a subdatasheet by clicking Subform Datasheet on the View menu. As with table and query subdatasheets, if the LinkChildFields and LinkMasterFields properties of the subform are not defined, Access displays all rows of the source object, not just the rows that match.

  • Although a form can have more than one subform, each of which can be nested for up to two levels, in form Datasheet view only one subdatasheet is displayed. Access displays the subdatasheet corresponding to the first subform in the tab order of the form. However, if a subform has a table or query as its source object and its DefaultView property is set to Datasheet, then you can insert another subdatasheet into the subdatasheet that corresponds to the subform and nest up to eight levels either in form Datasheet view or in Form view.

  • When you first open a table, query, or form in Datasheet view, its subdatasheet is not expanded; however, when you first open a form in Form view, the subdatasheet corresponding to the subform is expanded.

  • You can permanently display the foreign key or matching field(s) in the subdatasheet corresponding to the subform if the subform's source object is a form.

Learn about subforms.

Return to top

Comparing subdatasheets in a Microsoft Access database and a Microsoft Access project

You can use a table or query subdatasheet only in a Microsoft Access database, not in a Microsoft Access project. However, you can use a subdatasheet in a subform or in form Datasheet view in both an Access database and an Access project.

Return to top

More information

Insert or modify a subdatasheet in a table or query in an Access database

Return to top


 Insert or modify a subdatasheet in a table or query in an Access database

Insert or modify a subdatasheet in a table or query in an Access database

Note You can use a table or query subdatasheet only in a Microsoft Access database, not a Microsoft Access project.

  1. Open a table or query in Datasheet view.

  2. On the Insert menu, click Subdatasheet.

  3. Click the Tables, Queries, or Both tab, depending on which kind of object you want to insert as a subdatasheet.

  4. Click a table or query in the list.

  5. In the Link Child Fields box, click the field to be the foreign key or matching field for the table or query that is the subdatasheet you chose in step 4.

  6. In the Link Master Fields box, click the field to be the primary key or matching field for the table or query that is the main datasheet you opened in step 1.

Notes

  • If you want to specify two or more fields in the Link Child Fields or Link Master Fields box, enter the field names separated by a semicolon (;) — for example, Last Name;First Name.

  • You can create a self-join when you insert or modify a subdatasheet. For example, suppose you want to see the employees who report to each manager as a subdatasheet of the Employees table in the Northwind sample database. Open the Employees table, click Subdatasheet on the Insert menu, click the Tables tab, click the Employees table, click ReportsTo in the Link Child Fields box, and then click EmployeeID in the Link Child Fields box.


 Expand or collapse a subdatasheet

Expand or collapse a subdatasheet

After opening the table, query, or form containing the subdatasheet in Datasheet view, you can do the following:

To expand a subdatasheet for a row of a datasheet or subdatasheet

  • Click the expand indicator (+) to the left of the row.

To expand all subdatasheets in the datasheet or subdatasheet that currently has focus

  • On the Format menu, point to Subdatasheet, and then click Expand All.

To collapse a subdatasheet for a row of a datasheet or subdatasheet

  • Click the expand indicator (-) to the left of the row.

To collapse all subdatasheets in the datasheet or subdatasheet that currently has focus

  • On the Format menu, point to Subdatasheet, and then click Collapse All.


 Remove a subdatasheet from a table or query in an Access database

Remove a subdatasheet from a table or query in an Access database

Note You can use a table or query subdatasheet only in a Microsoft Access database, not a Microsoft Access project.

  1. Open the table or query containing the subdatasheet in Datasheet view.

  2. On the Format menu, point to Subdatasheet, and then click Remove.

Note Removing a subdatasheet does not delete the table or query, nor does it modify any relationship.


Create one or more subforms

What do you want to do?

Create a form and a subform at the same time

Create a subform and add it to an existing form

Add an existing form to another existing form to create a form with a subform

Create a form with two subforms

Create a form with a subform that contains another subform


Queries: What they are and how they work

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


 Open or run a query

Open or run a query

You can open a select, crosstab, or action query in Design view. You can also open a select or crosstab query in Datasheet view, to view the query's results.

You can't open an action query in Datasheet view to view its results. However, in Datasheet view you can preview the data that will be affected when you run the action query.

What do you want to do?

Open a query in Design view

View the results of a select or crosstab query in Datasheet view

Switch between views of a query

Preview in Datasheet view the records that will be affected by a make-table, delete, append, or update query

Run a make-table, append, delete, or update query


Create a query

Microsoft Access can often create a query for you so you don't have to design one from scratch.

What do you want to do?

Learn about the different types of queries I can create

Learn about AutoLookup queries

Save an existing SQL statement as a query

Create a filter that I'll save as a query

Use a wizard to create a:

Simple select query

Crosstab query

Find Duplicates query

Find Unmatched query

Work on my own to create a:

Select query

Parameter query

Crosstab query

SQL query (union, pass-through, data-definition, subquery)

Action query (make-table, delete, append, update)

AutoLookup query


 Create a query from a filter in a table, query, or form

Create a query from a filter in a table, query, or form

Instead of designing a query from scratch in query Design view, you can create it automatically by saving an existing filter in a table, query, or form as a query. A query offers more flexibility than a filter. For more information, click [image] .

  1. With the filter displayed in the Filter By Form window or the Advanced Filter/Sort window, click Save As Query [image] on the toolbar.

  2. Type a name for the query, and then click OK.

    The new query appears in the Database window. It automatically includes all the fields from the underlying table because the query's OutputAllFields property is automatically set to Yes, but you can change the query's design if necessary. For more information on modifying a query, including setting its properties, click [image] .

Note You can use the query as a filter, too. You might do this if you already saved one filter with the form or datasheet, and you want to use the query as a second filter.


 Find duplicate records or field values in a table using a query wizard

Find duplicate records or field values in a table using a query wizard

From the results of a Find Duplicates query, you can determine if there are duplicate records in a table, or determine which records in a table share the same value. For example, you might search for duplicate values in an address field to determine if you have duplicate records for the same supplier, or you might search for duplicate values in a city field to see which suppliers are in the same city.

Note Microsoft Access can automatically delete all the duplicate records in a table, although you can't use the Find Duplicates Wizard to do it. For more information, click [image] .

  1. In the Database window, click Queries [image] under Objects, and then click New on the Database window toolbar.

  2. In the New Query dialog box, click Find Duplicates Query Wizard.

  3. Click OK.

  4. Follow the directions in the wizard dialog boxes. If you don't choose to show fields in addition to those with duplicate values, the query results will sum the instances of each duplicate value. In the last dialog box, you can choose to run the query or see the query's structure in Design view.

    If the resulting query isn't exactly what you want, you can rerun the wizard or change the query in Design view. For more information on changing a query in Design view, click [image] .

You can manually delete each duplicate record that the wizard finds. For more information, click [image] .


Ways to customize a query

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


 Design or modify a query

Design or modify a query

In query Design view, you can do any of the following procedures to complete the design of a new query you just created or modify an existing query. You can also use these procedures to modify an SQL statement that's the source of records for a form, report, or data access page. Changes you make in query Design view are reflected in the SQL statement.

If you're designing or modifying queries in a multiuser environment, there are certain things you should consider. For more information, click [image] .

What do you want to do?

Work with a table or a query in a query

Add a table or query

Remove a table or query

Work with joins

Join multiple tables

Change the type of join between two tables

Delete a join between two tables

Work with fields

Add a field

Remove a field

Move a field

Insert a field between other fields

Change a field name

Show or hide a field in the query's results

Set properties

Work in the query design grid

Change column widths

Clear the design grid

Add a column to the design grid in a query

Set criteria or a sort order

Insert or delete a criteria row

Set or change criteria

Specify a sort order for the result set

Perform calculations on data

Work with SQL in a query

Modify the SQL statement directly


About using the asterisk in the query design grid

  • Selecting the asterisk (*) in a query has an advantage over selecting all the fields. When you use the asterisk, the query results automatically include any fields that are added to the underlying table or query after the query is created; and automatically exclude fields that are deleted.

  • When you use the asterisk, you can't sort records or specify criteria for fields unless you add those fields along with the asterisk to the design grid. For more information, click [image] .

  • If you type an asterisk in the Field row rather than dragging it, you must type the table name also. For example, type Customers.*.

    Asterisks include all fields from a table in a query


 About working with blank fields in queries

About working with blank fields in queries

When a field contains no values, it contains a Null value or, for Text, Memo, or Hyperlink fields, a Null value or a zero-length string. If Null values exist in a field, they can affect the query's results. Following are some guidelines for working with Null values and zero-length strings in queries. (For information on the differences between Null values and zero-length strings, click [image] .)

This topic provides information about:

Joining fields that contain Null values

Searching for Null values or zero-length strings

Understanding how Null values affect numeric calculations

Converting Null values to zero

Combining Text fields that contain Null values

Sorting on fields containing Null values and zero-length strings

Using the asterisk (*) wildcard character to return non-Null values

Joining fields that contain Null values

When you join tables in a query, the result includes only records that don't have Null values in the matching fields. For example, to list Suppliers and Customers who live in the same region, you create a query that includes the Suppliers and Customers tables, and the tables are joined on the Region field. When you view the results, you'll see only the values for records that contain a value in the Region field in both tables.

Return to top

Searching for Null values or zero-length strings

If you're using a query to search for Null values or zero-length strings, type Is Null into the Criteria cell to search for Null values, or type two double quotation marks (" ") into the Criteria cell to search for zero-length strings (don't type a space between the quotation marks).

Return to top

Understanding how Null values affect numeric calculations

If you use an aggregate function to calculate the sum, average, count, or another amount on a field's values, records with Null values in that field won't be included in the calculation. This is true whether you calculate the aggregate using the Total row in the query design grid, the Simple Query Wizard, or a custom expression. For example, if you use the Count function to count the number of values in a field, it will return a count of all the records with non-Null values. If you want to find the total number of records including those with Null values, use Count with the asterisk (*) wildcard character.

Include records with Null values using the Count function

If you use an arithmetic operator (such as +, -, *, /) in an expression (such as [UnitsInStock]+[UnitsOnOrder]), and one of the fields in the expression contains a Null value, then the result of the entire expression will be a Null value.

Return to top

Converting Null values to zero

When you have fields that contain Null values, you can create an expression that converts the Null values to zero. You might do this if you want the records containing Null values to be included in an aggregate calculation, or if you want to prevent an expression from resulting in a Null value when a field that's referenced in the expression contains Null values. Use the Nz function, for example, to convert Null values to zero:

Nz([Subtotal],0)+Nz([Freight],0)

For more information about the Nz function, click [image] .

Return to top

Combining Text fields that contain Null values

If you're using an expression to combine two fields containing text values and one or both of the fields includes Null values, use the & operator instead of the + operator to combine the values. The & operator will combine the values even if they contain Null values, while the + operator will return a Null if either of the two values is a Null. For example:

FullName: [LastName] & " " & [FirstName]

Return to top

Sorting on fields containing Null values and zero-length strings

When you sort a field in ascending order, any records in which that field contains a Null value are listed first. If a field contains both Null values and zero-length strings, the Null values appear first in the sort order, immediately followed by the zero-length strings.

Return to top

Using the asterisk (*) wildcard character to return non-Null values

If you use the expression Like "*" when defining query criteria for a field, the query results will include zero-length strings in that field, but not Null values.

Return to top

More information

Ways to perform calculations in a query

About aggregate functions and other options in the query design grid’s Total row

Specify a sort order for a query


Prevent duplicate records from displaying in query results

What do you want to do?

Prevent duplicate records in a query based on fields in the underlying table

Prevent duplicate records in a query based on fields in the query design grid

Not sure which choice you want?


 Display only the highest or lowest values in the query's results

Display only the highest or lowest values in the query's results

The query can display, for example, those records with the 10 highest or lowest values in a specific field or the records with the highest or lowest 10 percent of values in the field.

  1. Open the query in Design view.

  2. Add to the design grid the fields you want to display in the query's results, including the field you want to display top values for.

  3. In the Sort cell of the field you want to display top values for, click Descending to display the highest values or Ascending to display the lowest values. If you're sorting on other fields in the query's design grid, too, those fields must be to the right of the top values field.

  4. Click in the Top Values box [image] on the toolbar.

  5. Enter the percentage or the number of highest or lowest values you want the query results to display.

    Note To display a percentage, enter a number followed by a percent sign (%).

    Specify the percentage of the highest or lowest values to display

  6. To view the query's results, click View [image] on the toolbar.

Note Setting the TopValues property in the query's property sheet works the same as using the Top Values button on the toolbar.


 Ways to bring together data from multiple tables or queries in a query

Ways to bring together data from multiple tables or queries in a query

The power of queries lies in being able to bring together or perform an action on data from more than one table or query. For example, you might want to view a customer's information with the orders the customer placed. To see this information, you need data from the Customers and Orders tables.

When you add more than one table or query to a query, you need to make sure their field lists are joined to each other with a join line so that Microsoft Access knows how to connect the information.

Join lines show relationship between tables

If tables in a query aren't joined to one another, either directly or indirectly, Microsoft Access doesn't know which records are associated with which, so it displays every combination of records (called a "cross-product" or "Cartesian product") between the two tables. Therefore, if each table had 10 records in it, the query's results will contain 100 records (10X10). It also means the query might take a long time to run and ultimately might produce less meaningful results.

If you previously created relationships between tables in the Relationships window, Microsoft Access automatically displays join lines when you add related tables in query Design view. If referential integrity is enforced, Microsoft Access also displays a "1" above the join line to show which table is on the "one" side of a one-to-many relationship and an infinity symbol [image] to show which table is on the "many" side.

Even if you haven't created relationships, Microsoft Access automatically creates joins if you add two tables to a query and the tables each have a field with the same or compatible data type and if one of the join fields is a primary key. The "one" and "many" symbols are not displayed in this case, because referential integrity is not enforced.

Sometimes the tables you add to the query don't include any fields that can be joined. In this situation, you have to add one or more extra tables or queries to serve solely as a bridge between the tables whose data you want to use. For example, if you add the Customers and Order Details tables to a query, they won't have a join line between them because they don't have any fields that can be joined. But the Orders table is related to both tables, so you can include the Orders table in your query to provide a connection between the other two.

Extra table in a join provides relationship between tables

Once tables and queries are joined, and you've added fields from both tables or queries to the design grid in query Design view, the default join tells the query to check for matching values in the join fields. (This is called an inner join in database terminology.) When it finds matches, it combines those two records and displays them as one record in the query's results. If one table or query doesn't have a matching record in the other table or query, neither record appears in the query's results. If you want the query to select all the records from one table or query whether or not it has matching records in the other table or query, you can change the join type.

Examples of different join types and how they affect query results If you want the query to select records based on the value in the join field being greater than, less than, not equal to, greater than or equal to, or less than or equal to the value in the other join field, you must create an SQL statement in SQL view.

Note Once you create a multiple-table query, you may or may not be able to update the data. For more information, click [image] .


Join types and how they affect query results

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


 Enable or disable automatic joins between tables and queries in queries

Enable or disable automatic joins between tables and queries in queries

Even if you haven't created relationships between tables, Microsoft Access automatically creates joins if you add two tables to a query and the tables each have a field with the same or compatible data type and if one of the join fields is a primary key. You can enable or disable these automatic joins.

  1. On the Tools menu, click Options.

  2. Click the Tables/Queries tab.

  3. Select or clear the Enable AutoJoin check box.

Notes

  • If you disable automatic joins, you can still create joins yourself.

  • This setting applies to new queries only.


 Join multiple tables and queries in a query

Join multiple tables and queries in a query

  • In query Design view, drag a field from the field list for one table or query to the equivalent field (a field of the same or compatible data type containing similar data) in the field list for the other table or query.

    With this type of join, Microsoft Access selects records from both tables or queries only when the values in the joined fields are equal.

Drag the field to join the tables

Notes

  • Join numeric fields only if the FieldSize property settings for both are Byte, Integer, or Long Integer.

  • You can change the type of join so that Microsoft Access selects all the records from one table or query whether or not it has matching records in the other table or query. For more information, click [image] .


 Join two copies of the same table in a query

Join two copies of the same table in a query

By joining two copies of the same table, you create a self-join that combines records from the same table when there are matching values in the joined fields. For example, say you have an Employees table in which the ReportsTo field for each employee's record displays his or her manager's ID instead of name. You could use a self-join to display the manager's name in each employee's record instead.

  1. In query Design view, add the table to the query twice.

  2. Create the join by dragging a field in the first table's field list to the field you want to relate it to in the second field list.

Notes

  • To read about how to complete the self-join in the preceding example, click [image] .

  • Microsoft Access appends "_1" to the table name in the second field list. For example, if you add the Employees table twice, the first field list is titled "Employees," and the second field list is titled "Employees_1." You can rename the table to something more descriptive by setting the Alias property for the field list. For more information, click [image] .


 Change the type of join between tables and queries in a query

Change the type of join between tables and queries in a query

  1. Open a query in Design view.

  2. Double-click the join line between the field lists for the tables or queries.

    Double-click the join line to open the Join Properties dialog box

  3. In the Join Properties dialog box, click the join option you want, and then click OK.

Examples of different join types and how they affect query results

Notes

  • From the Relationships window, you can change the default join type for tables. For more information, click [image] .

  • All of the joins created using the Join Properties dialog box select records only if the values in the joined fields are equal. You can create joins that select records only if the value in one join field is greater than, less than, not equal to, greater than or equal to, or less than or equal to the value in the other join field; to do so, you must create an SQL statement in SQL view.


 Delete a join line between tables and queries in a query

Delete a join line between tables and queries in a query

  • In query Design view, select the join line, and then press the DEL key.

Select the join line to delete it

Note You can prevent Microsoft Access from automatically creating joins between tables in a query. For more information, click [image] .


Show or hide table names in the query design grid by default

  1. On the Tools menu, click Options.

  2. Click the Tables/Queries tab.

  3. Select or clear the Show Table Names check box.

Note This setting applies to new queries only.


 Create an AutoLookup query that automatically fills in data

Create an AutoLookup query that automatically fills in data

For AutoLookup to work on new records, certain conditions must be met. For more information, click [image] .

  1. Create a select query, adding two tables that have a one-to-many relationship.

    How?

  2. Add the fields for the query to the design grid.

    You must include the join field from the "many" side of the one-to-many relationship.

    Include the join field to create an AutoLookup query

  3. If you want, specify criteria in the Criteria row to select specific records.

    How?

  4. To view the query's results, click View [image] on the toolbar.

    When you enter new data in the join field on the "many" side of the relationship, Microsoft Access will automatically look up and fill in the corresponding data from the "one" side.

Note For information on troubleshooting an AutoLookup query, click [image] .


Add or modify criteria

What do you want to do?

Learn about using criteria in queries to retrieve certain records

Enter criteria in a query to retrieve certain records

Specify multiple criteria in a query

See common ways to use criteria

See examples of criteria expressions for queries

Learn about where to specify criteria to affect when calculations are performed

Specify criteria when using the asterisk in the design grid

Create a parameter query that prompts for criteria each time it's run

Insert or delete a criteria row in a query


See common ways to use criteria

What do you want to do?

Retrieve records containing values between, greater or less than, equal to, or not equal to specified values

Retrieve records with values that start or end with certain characters or words, or contain certain characters or words

Retrieve records that don't match a value

Retrieve records that contain a value, not blanks (Null values)

Retrieve records that don't contain a value

Retrieve records that contain the current date

Retrieve records that contain one value from a list of possible values


 Enter criteria in a query or advanced filter to retrieve certain records

Enter criteria in a query or advanced filter to retrieve certain records

To learn more about using criteria, click [image] .

  1. Open a query in Design view, or display the Advanced Filter/Sort window for a table, query, or form.

  2. Click the first Criteria cell for the field you want to set criteria for.

  3. Enter the criteria expression by typing it or by using the Expression Builder. To display the Expression Builder, right-click in the Criteria cell, and then click Build. For more information on using the Expression Builder, click [image] .

    Records retrieved meet the criteria in both columns.

    If your query includes linked tables, the values you specify in criteria on fields from the linked tables are case-sensitive — they must match the case of the values in the underlying table.

    When you view a subdatasheet in a query, the Advanced Filter/Sort window contains the record source only for the selected subdatasheet. To filter on fields contained in the main datasheet or in a different subdatasheet, close the Advanced Filter/Sort window, select the main datasheet or the subdatasheet on which you want to set filter criteria, and then reopen the Advanced Filter/Sort window.

  4. To enter another expression in the same field or in another field, move to the appropriate Criteria cell and enter the expression.

Notes

  • For examples of criteria expressions, click [image] .

  • For information on where to enter criteria in a query that performs calculations, click [image] .


Ways to specify multiple criteria in a query

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


 Specify criteria or a sort order when using the asterisk in the design grid

Specify criteria or a sort order when using the asterisk in the design grid

  1. Open a query in Design view.

  2. Drag the asterisk (*) from the field list to the Field row in the design grid.

  3. Add the fields you want to sort or set criteria for by dragging them from the field list to the Field row.

  4. Select a sort order in the Sort cell for the fields you want to sort.

    How

  5. Enter criteria in the Criteria row for the appropriate fields.

    How?

  6. Clear the Show check box for all fields except the asterisk; otherwise those fields will appear twice in the query's results.

  7. Click the View button on the toolbar to view the results.


 Insert or delete a criteria row in a query or advanced filter

Insert or delete a criteria row in a query or advanced filter

  • To insert a criteria row, in query Design view or in the Advanced Filter/Sort window, click in the row that is below where you want the new row to appear, and then click Insert Row on the Insert menu. A new row is inserted above the row that you clicked.

  • To delete a criteria row, click anywhere in the row, and then click Delete Rows on the Edit menu.


 Use a subquery to define a field or define criteria for a field

Use a subquery to define a field or define criteria for a field

You can use subqueries to, for example, test for the existence of some result from the subquery, find any values in the main query that are equal to, greater than, or less than values returned by the subquery, or to create subqueries within subqueries.

  1. Create a new query.

  2. In query Design view, add the fields you want to the design grid, including the fields you want to use the subquery for.

  3. If you're using a subquery to define criteria for a field, type a SELECT statement in the Criteria cell of the field for which you want to set criteria. Place the SELECT statement in parentheses.

    SELECT statement in the Criteria cell defines a subquery.

    If you're using a subquery to define a Field cell, type a SELECT statement enclosed in parentheses in a Field cell. After you leave the cell, Microsoft Access automatically inserts "Expr1:", "Expr2:", and so on, before the SELECT statement.

    Note For more space in which to enter the SELECT statement while in a Field or Criteria cell, press SHIFT+F2 and enter the statement in the Zoom box.

    Zoom box displays long subquery statements.

    To rename the field, replace "Expr1:" with a field name — for example, "Cat:".

  4. To see the results, click View [image] on the toolbar.

Notes

  • For more examples of subqueries used to define criteria, click [image] .

  • You can't use a field that you define with a subquery to group records.

  • A subquery's SELECT statement can't define a union or crosstab query.


 Retrieve records containing values between, >, <, >=, <=, or <> specified values

Retrieve records containing values between, >, <, >=, <=, or <> specified values

  1. In query Design view, create a query. Add the tables whose records you want to use, and then add the fields you want to include in the results to the query design grid.

  2. In an expression in the Criteria cell of the appropriate field, identify a range by using the Between...And operator or the comparison operators (<, >, <>, <=, and >=). For example, you can find orders placed before 1-Jan-93 or products that have between 10 and 35 units in stock. The following table shows some examples of operators used in expressions.
    Expression | Meaning
    >234 | Numbers greater than 234
    Between #2/2/93# And #12/1/93# | Dates from 2-Feb-93 through 1-Dec-93
    <1200.45 | Numbers less than 1200.45
    >="Callahan" | All names from Callahan through the end of the alphabet

Note Dates and numbers are displayed in the query design grid in the format appropriate for the country selected in the Regional Settings of Windows Control Panel. For example, the date sequence is month/day/year for the United States, day/month/year for the United Kingdom, and year/day/month for Sweden.


 Retrieve records that don't match a value using a query

Retrieve records that don't match a value using a query

  1. In query Design view, create a query. Add the tables whose records you want to use, and then add the fields you want to include in the results to the query design grid.

  2. In the Criteria cell of the appropriate field, enter an expression using the Not operator. For example, you can type the expression Not T* in the Criteria cell of the CompanyName field to find all customers whose names don't begin with T, or Not 2 in the ShipID field to find shippers whose ID isn't 2.


 Retrieve records except those containing Null values using a query

Retrieve records except those containing Null values using a query

  1. In query Design view, create a query. Add the tables whose records you want to use, and then add the fields you want to include in the results to the query design grid.

  2. In the Criteria cell of the appropriate field, type the expression Not Null or Is Not Null. For example, to see a list of suppliers who have fax numbers from a table containing supplier information, type Not Null or Is Not Null in the Criteria cell of the Fax Number field.


 Retrieve records that contain the current date using a query

Retrieve records that contain the current date using a query

The current date is the system date Microsoft Access takes from your computer's system clock.

  1. In query Design view, create a query. Add the tables whose records you want to use, and then add the fields you want to include in the results to the query design grid.

  2. In the Criteria cell of the appropriate field, type Date(), with no space between the parentheses. For example, you can find all orders that were shipped on the current date by typing Date() in the ShipDate field.


 Retrieve records that include one value from a list of values using a query

Retrieve records that include one value from a list of values using a query

  1. In query Design view, create a query. Add the tables whose records you want to use, and then add the fields you want to include in the results to the query design grid.

  2. In the Criteria cell of the appropriate field, type an expression using the In operator. For example, to find suppliers located in France, Germany, or Japan, type the following expression in the Criteria cell for the Country field of the Suppliers table:

    In(France,Germany,Japan)

    You can also enter:

    France Or Germany Or Japan


 Retrieve records that don't contain values using a query

Retrieve records that don't contain values using a query

  1. In query Design view, create a query. Add the tables whose records you want to use, and then add the fields you want to include in the results to the query design grid.

  2. In the Criteria cell of the appropriate field, type the expression Is Null. For example, to see a list of suppliers who have fax numbers from a table containing supplier information, type Is Null in the Criteria cell of the Fax Number field.


 Extract part of existing text values using a calculated field

Extract part of existing text values using a calculated field

  1. In query Design view, create a query. Add the tables whose records you want to use.

  2. To find values in part of a field, use the Left, Right, or Mid function in an expression in an empty cell in the Field row in the query design grid.

    The syntax for these functions is:

    Left(stringexpr,n)
    Right(stringexpr,n)
    Mid(stringexpr,start,n)

    The stringexpr argument can be either a field name (enclosed in brackets) or a text expression; n is the number of characters you want to extract; start is the position of the first character you want to extract.

    The following table shows examples of these functions.

    If the value in
    Part ID is
    This expression
    Returns
    BA-7893-R12 | Left([PartID],2) | BA
    BA-7893-R12 | Right([PartID],3) | R12
    BA-7893-R12 | Mid([PartID],4,4) | 7893
  3. Add any other fields you want to include in the query to the query design grid.


 Extract part of existing date values using a calculated field

Extract part of existing date values using a calculated field

  1. In query Design view, create a query. Add the tables whose records you want to use.

  2. Use the DatePart function in an expression in an empty cell in the Field row in the query design grid.

    The syntax for this function is:

    DatePart(datepart,date)

    The datepart argument is the abbreviation for the part of the date you want returned. Examples are "yyyy" for a four-digit year and "q" for a calendar quarter. The date argument is either a field name with the Date/Time data type or a literal date such as "7-Nov-93".

    The following table lists examples of expressions that apply the DatePart function to the OrderDate field from the Orders table.

    If the value in
    OrderDate is
    This expression
    Returns
    3-Jun-93 | DatePart("m",[OrderDate]) | 6 (month of year)
    28-Mar-92 | DatePart("yyyy",[OrderDate]) | 1992 (four-digit number of year)
  3. Add any other fields you want to include in the query to the query design grid.


 Ways to perform calculations in a query

Ways to perform calculations in a query

There are many types of calculations you can perform in a query. For example, you can calculate the sum or average of the values in one field, multiply the values in two fields, or calculate the date three months from the current date.

When you display the results of a calculation in a field, the results aren't actually stored in the underlying table. Instead, Microsoft Access reruns the calculation each time you run the query so that the results are always based on the most current data in the database. Therefore, you can't manually update the calculated results.

To display the results of a calculation in a field, you can use a predefined calculation that Microsoft Access provides or custom calculations you define. Use the predefined calculations, called "totals," if you want to compute the following amounts for groups of records or for all the records combined: sum, average, count, minimum, maximum, standard deviation, or variance. You choose one totals calculation for each field you want to calculate.

Calculations that display in a query

You can calculate some types of totals using the Simple Query Wizard. Or, you can calculate all types of totals using the Total row in the query design grid, where you select the aggregate function for the calculation you want to perform on a field.

In the query design grid, you can also specify criteria to limit the groups for which totals are calculated, limit the records included in the calculation, or limit the results that are displayed after the calculation is performed.

A custom calculation enables you to perform numeric, date, and text calculations on each record using data from one or more fields. For example, with a custom calculation, you can multiply one field's values by a set amount, find the difference between two dates stored in separate fields, combine several values in a Text field, or create subqueries. Using the options in the Total row in the design grid, you can perform the calculation on groups of records and calculate a sum, average, count, or other type of total on the calculated field.

For custom calculations, you need to create a new calculated field directly in the design grid. You create a calculated field by entering an expression into an empty Field cell in the query design grid.

Calculated fields in the query design grid

The expression can be made up of multiple calculations — for example, Sum([UnitsInStock]+[UnitsOnOrder]). You can also specify criteria for a calculated field to affect the results of the calculation.

You don't have to display the results of a calculation in a field, however. Instead, you can use them as criteria to determine the records the query selects or to determine which records to perform an action on. For example, you can specify the following expression in the Criteria row to tell the query to return only records that have values in the RequiredDate field that are between today's date and three months from today's date.

Calculation to define criteria for selecting records

You can also use a calculation to update data from an update query. For example, you can enter the following expression in the Update To cell to increase all the values in the UnitPrice field by 5 percent.

Calculation to update data


Perform calculations in a query

What do you want to do?

Learn more about the ways to perform calculations in a query

Learn what each type of totals calculation (aggregate function) does

Use the Simple Query Wizard to create a query that calculates a sum, average, count, minimum, or maximum total on one or more groups of records

Use the query design grid to calculate a sum, average, count, or other total

Create a calculated field for custom calculations

See examples of calculations used as criteria

See examples of calculations used to update data

Not sure which choice you want?


What is a select query and when would you use one?

A select query is the most common type of query. It retrieves data from one or more tables and displays the results in a datasheet where you can update the records (with some restrictions). You can also use a select query to group records and calculate sums, counts, averages, and other types of totals.

Examples of select queries

Return to Types of queries


 Create a simple select query with a wizard

Create a simple select query with a wizard

The Simple Select Query Wizard creates queries that retrieve data from the fields you specify in one or more tables or queries. If you want, the wizard can also sum, count, and average values for groups of records or all records, and it can calculate the minimum or maximum value in a field. You can't limit the records it retrieves by setting criteria, however.

  1. In the Database window, click Queries [image] under Objects, and then click New on the Database window toolbar.

  2. In the New Query dialog box, click Simple Query Wizard.

  3. Click OK.

  4. Click the name of the table or query you want to base your query on, and then select the fields whose data you want to retrieve.

  5. Click an additional table or query if desired, and then select the fields you want to use from it. Repeat this step until you have all the fields you need.

  6. Follow the directions in the wizard dialog boxes. In the last dialog box, you can choose either to run the query or to see the query's structure in Design view.

    If the resulting query isn't exactly what you want, you can rerun the wizard or change the query in Design view. For more information on changing a query in Design view, click [image] .

To troubleshoot problems with the query, click [image] .


Create a select query without a wizard

You can use the steps in this topic to guide you through creating a select query from start to finish. You’ll use many of these steps in creating every query. The others you’ll use when you design a query that specifies criteria used to select information, perform calculations, or set a sort order. You need to use only the steps that are relevant to the data you wish to retrieve. For other tasks related to creating queries, ask the Answer Wizard.

See examples of what select queries are and how they work
  1. Add a table to a query

    Ways to bring together data from multiple tables or queries in a query

    Add a table or query to a query

    Join multiple tables and queries in a query

    Change the type of join between tables and queries in a query

  2. Add fields to a query

    Add fields to the design grid in a query

    Add a column to the design grid in a query

  3. Set query criteria to select specific information

    About using criteria in queries to retrieve certain records

    Enter criteria in a query to retrieve certain records

    Insert or delete a criteria row in a query to retrieve certain records

  4. Perform calculations in a query

    Create a field that performs custom calculations or manipulates field values in a query

    Examples of expressions that calculate on or manipulate values by using a calculated field

  5. Refine a query

    Set properties for a query, its fields, or its field lists

    Sort records by using the design grid of a query

    Create an AutoLookup query that automatically fills in data

    About AutoLookup queries that enter data automatically


 What is an action query and when would you use one?

What is an action query and when would you use one?

An action query is a query that makes changes to many records in just one operation. There are four types of action queries: delete, update, append, and make-table.

This topic provides examples of:

Delete query

Update query

Append query

Make-table query

Delete query

Deletes a group of records from one or more tables. For example, you could use a delete query to remove products that are discontinued or for which there are no orders. With delete queries, you always delete entire records, not just selected fields within records.

For information on creating delete queries, click [image] .

Return to top

Update query

Makes global changes to a group of records in one or more tables. For example, you can raise prices by 10 percent for all dairy products, or you can raise salaries by 5 percent for the people within a certain job category. With an update query, you can change data in existing tables.

For information on creating update queries, click [image] .

Return to top

Append query

Adds a group of records from one or more tables to the end of one or more tables. For example, suppose that you acquire some new customers and a database containing a table of information on those customers. To avoid typing all this information in, you'd like to append it to your Customers table. Append queries are also helpful for:

  • Appending fields based on criteria. For example, you might want to append only the names and addresses of customers with outstanding orders.

  • Appending records when some of the fields in one table don't exist in the other table. For example, in the Northwind sample database, the Customers table has 11 fields. Suppose that you want to append records from another table that has fields that match 9 of the 11 fields in the Customers table. An append query will append the data in the matching fields and ignore the others.

For information on creating append queries, click [image] .

Return to top

Make-table query

Creates a new table from all or part of the data in one or more tables. Make-table queries are helpful for:

  • Creating a table to export to other Microsoft Access databases. For example, you might want to create a table that contains several fields from your Employees table, and then export that table to a database used by your personnel department.

  • Creating data access pages that display data from a specified point in time. For example, suppose you want to display a data access page on 15-May-96 that displays the first quarter's sales totals based on the data that was in the underlying tables as of 9:00 A.M. on 1-Apr-96. A data access page based on a query or SQL statement extracts the most up-to-date data from the tables (the data as of 15-May-96), rather than the records as of a specific date and time. To preserve the data exactly as it was at 9:00 A.M. on 1-Apr-96 , create a make-table query at that point in time to retrieve the records you need and store them in a new table. Then use this table, rather than a query, as the basis for the data access page.

  • Making a backup copy of a table.

  • Creating a history table that contains old records. For example, you could create a table that stores all your old orders before deleting them from your current Orders table.

  • Improving performance of forms, reports, and data access pages based on multiple-table queries or SQL statements. For example, suppose you want to print multiple reports that are based on a five-table query that includes totals. You may be able to speed things up by first creating a make-table query that retrieves the records you need and stores them in one table. Then you can base the reports on this table or specify the table in an SQL statement as the record source for a form, report, or data access page, so you don't have to rerun the query for each report. However, the data in the table is frozen at the time you run the make-table query.

For information on creating make-table queries, click [image] .

Return to top


 Create a new table from the results of a query with a make-table query

Create a new table from the results of a query with a make-table query

  1. Create a query, selecting the tables or queries that contain the records you want to put in the new table.

    How?

  2. In query Design view, click the arrow next to Query Type [image] on the toolbar, and then click Make Table. The Make Table dialog box appears.

  3. In the Table Name box, enter the name of the table you want to create or replace.

  4. Click Current Database to put the new table in the currently open database. Or click Another Database and type the name of the database you want to put the new table in. Type the path if necessary.

  5. Click OK.

  6. Drag from the field list to the query design grid the fields you want in the new table.

  7. In the Criteria cell for the fields that you've dragged to the grid, type the criteria.

    For information on specifying criteria, click [image] .

  8. To preview the new table before you create it, click View [image] on the toolbar. To return to query Design view and make changes or run the query, click View [image] on the toolbar.

  9. To create the new table, click Run [image] on the toolbar.

Notes

  • To stop a query after you start it, press CTRL+BREAK.

  • The data in the new table you create does not inherit the field properties or the primary key setting from the original table.


 Change records as a group using an update query

Change records as a group using an update query

  1. Create a query, selecting the tables or queries that include the records you want to update and the fields you want to use for setting criteria.

    How?

  2. In query Design view, click the arrow next to Query Type [image] on the toolbar, and then click Update Query.

  3. Drag from the field list to the query design grid the fields you want to update or you want to specify criteria for.

  4. In the Criteria cell, specify the criteria if necessary.

    For information on specifying criteria, click [image] .

  5. In the Update To cell for the fields you want to update, type the expression or value you want to use to change the fields, as shown in the following illustration.

    Specifying an expression to change a group of records

    For examples of expressions, click [image] .

  6. To see a list of the records that will be updated, click View [image] on the toolbar. This list won't show the new values. To return to query Design view, click View [image] on the toolbar again. Make any changes you want in Design view.

  7. Click Run [image] on the toolbar to update the records.

Note To stop a query after you start it, press CTRL+BREAK.


 Examples of expressions in update queries

Examples of expressions in update queries

Use expressions such as the following in the Update To cell in the query design grid for the field you want to update.

Expression | Result
"Salesperson" | Changes value to Salesperson
#8/10/96# | Changes date values to 10-Aug-96
Yes | Changes No values in a Yes/No field to Yes
"PN"&[PartNumber] | Adds PN to the beginning of each specified part number
[UnitPrice]*[Quantity] | Calculates the product of UnitPrice and Quantity
[Freight]*1.5 | Increases freight charges by 50 percent
DSum("[Quantity]*[UnitPrice]", "Order Details","[ProductID]=" & [ProductID]) | Where the Product IDs in the current table match the Product IDs in the Order Details table, updates sales totals based on the product of Quantity and UnitPrice
Right([ShipPostalCode],5) | Truncates the leftmost characters in a field, leaving the five rightmost characters


 Append records from one table to another table using an append query

Append records from one table to another table using an append query

  1. Create a query that contains the table whose records you want to append to another table.

    How?

  2. In query Design view, click the arrow next to Query Type [image] on the toolbar, and then click Append. The Append dialog box appears.

  3. In the Table Name box, enter the name of the table you want to append records to.

  4. Click Current Database if the table is in the currently open database. Or click Another Database and type the name of the database where the table is stored. Type the path if necessary.

    You can also enter a path to a Microsoft FoxPro, Paradox, or dBASE database, or a connection string to an SQL database.

  5. Click OK.

  6. Drag from the field list to the query design grid the fields you want to append and any fields you want to use for setting criteria. Also, you may or may not want to add the primary key field if it has an AutoNumber data type. For more information, click [image] .

    If all the fields in both tables have the same names, you can just drag the asterisk (*) to the query design grid. However, if you're working in a database replica, you'll need to add all the fields instead.

  7. If the fields you've selected have the same name in both tables, Microsoft Access automatically fills the matching name in the Append To row. If the fields in the two tables don't have the same name, in the Append To row, enter the names of the fields in the table you're appending to.

  8. In the Criteria cell for the fields that you have dragged to the grid, type the criteria on which additions will be made.

    For information on specifying criteria, click [image] .

  9. To preview the records that the query will append, click View [image] on the toolbar. To return to query Design view, click View [image] on the toolbar again. Make any changes you want in Design view.

  10. Click Run [image] on the toolbar to add the records.

Note To stop a query after you start it, press CTRL+BREAK.


Delete a group of records with a query

What do you want to do?

Delete records from a single table or multiple tables that have a one-to-one relationship

Delete records by using a query that includes only the "one" table in a one-to-many relationship

Delete records by using a query that includes both tables in a one-to-many relationship

Not sure which choice you want?


 What is a crosstab query and when would you use one?

What is a crosstab query and when would you use one?

A crosstab query displays summarized values (sums, counts, and averages) from one field in a table and groups them by one set of facts listed down the left side of the datasheet and another set of facts listed across the top of the datasheet.

For information on creating a crosstab query with a wizard, click [image] . For information on creating a crosstab query from scratch, click [image] .

Tip You can display crosstab data without creating a separate query in your database either by using the PivotTable Wizard in a form or by creating a PivotTable list in a data access page. With a PivotTable form or PivotTable list, you can change row and column headings on demand to analyze your data in different ways. For information on creating a PivotTable form, click [image] .

For information on creating a PivotTable list on a data access page, click [image] .


Example of a crosstab query

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


 Create a crosstab query without using a wizard

Create a crosstab query without using a wizard

To see an example of a crosstab query before you begin, click [image] .

  1. In the Database window, click Queries [image] under Objects, and then click New on the Database window toolbar.

  2. In the New Query dialog box, click Design View, and then click OK.

  3. In the Show Table dialog box, click the tab that lists the tables or queries whose data you want to work with.

  4. Double-click the name of each object you want to add to the query, and then click Close.

  5. Add fields to the Field row in the design grid and specify criteria.

  6. On the toolbar, click Query Type [image] , and then click Crosstab.

  7. For the field or fields whose values you want to appear as row headings, click the Crosstab row, and then click Row Heading.

    You must leave the default Group By in the Total row for these fields.

  8. For the field whose values you want to appear as column headings, click the Crosstab row, and then click Column Heading. You can choose Column Heading for one field only, and you must leave Group By in the Total row for this field.

    By default, the column headings are sorted in alphabetic or numeric order. If you want them to appear in a different order, or if you want to limit which column headings display, set the query's ColumnHeadings property.

    How?

  9. For the field whose values you want to use in the cross-tabulation, click the Crosstab row, and then click Value.

    Only one field can be set to Value.

  10. In the Total row for this field, click the type of aggregate function you want for the cross-tabulation (such as Sum, Avg, or Count).

  11. To specify criteria that limit row headings before the calculation is performed, enter an expression in the Criteria row for a field with Row Heading in the Crosstab cell. For example, you might display sales totals for products in certain categories, such as meat and seafood.

    To specify criteria that limit records before the row headings are grouped and before the cross-tabulation is performed, add the field you want to set criteria for to the design grid, click Where in the Total cell, leave the Crosstab cell blank, and then enter an expression in the Criteria row. (The query results won't display fields that have Where in the Total row.) For examples of how criteria affect calculations in queries, click [image] .

  12. To view the query's results, click View [image] on the toolbar.

    To stop the query after you start it, press CTRL+BREAK.

Notes

  • The query Quarterly Orders by Product in the Northwind sample database is an example of a crosstab query. To view this query, open the Northwind database in your Office folder's Samples folder, and then open Quarterly Orders by Product in Design view. For information on opening Northwind, click [image] .

  • If you include a field in the query design grid, but click the (Not Shown) option in the Crosstab cell and Group By in the Total cell, Microsoft Access groups on it as a Row Heading, but doesn't display the row in the query's results.

  • The values in your Column Heading field may include characters usually not allowed in field names, such as decimals. If they do, Microsoft Access replaces the character with an underscore in the datasheet.

  • For information on troubleshooting your crosstab query, click [image] .

  • For information on creating a PivotTable list in a data access page, click [image] .


 Create a crosstab query using a wizard

Create a crosstab query using a wizard

For an example of a crosstab query, click [image] .

  1. In the Database window, click Queries [image] under Objects, and then click New on the Database window toolbar.

  2. In the New Query dialog box, click Crosstab Query Wizard.

  3. Click OK.

  4. Follow the directions in the wizard dialog boxes. In the last dialog box, you can choose to run the query or see the query's structure in Design view.

    If the resulting query isn't exactly what you want, you can rerun the wizard or change the query in Design view. For more information on changing a query in Design view, click [image] .

To troubleshoot problems with the query, click [image] .

Tip You can display crosstab data without creating a separate query in your database either by using the PivotTable Wizard in a form or by creating a PivotTable list in a data access page. With a PivotTable form or PivotTable list, you can change row and column headings on demand to analyze your data in different ways. For information on creating a PivotTable form, click [image] .

For information on creating a PivotTable list on a data access page, click [image] .


 Sort or limit column headings displayed in a crosstab query

Sort or limit column headings displayed in a crosstab query

In column headings containing, for example, the months of the year, you can display the months chronologically rather than alphabetically, and you can display only the columns for January through June.

  1. Design your crosstab query either with or without the help of a wizard.

  2. Display the query in Design view.

  3. Click the background of query Design view, outside the design grid and the field lists.

  4. On the toolbar, click Properties [image] to display the query's property sheet.

  5. In the ColumnHeadings property box, enter the column headings you want to display, in the order in which you want to display them. Between the column headings, type a comma or the list separator for your country. (To find the list separator for your country, double-click Regional Settings in the Windows Control Panel.)

    The column headings you enter must exactly match the column headings in the query datasheet. For example, if a column heading in the datasheet is "USA," you must enter a column heading of "USA" — not "US." (After you press ENTER or move the pointer to a different location, Microsoft Access places quotation marks around each heading.)

  6. To view the query's results, click View [image] on the toolbar.

Notes

  • If you run a crosstab query often, or if you use it as the basis for a form, report, or data access page, you can speed up the query by using the preceding procedure to specify fixed column headings.

  • If you frequently use the same column headings in different queries, consider creating a table with one Text field to store the column headings. Then open the table and copy the headings into the ColumnHeadings property box as needed.


 What is a parameter query and when would you use one?

What is a parameter query and when would you use one?

A parameter query is a query that when run displays its own dialog box prompting you for information, such as criteria for retrieving records or a value you want to insert in a field. You can design the query to prompt you for more than one piece of information; for example, you can design it to prompt you for two dates. Microsoft Access can then retrieve all records that fall between those two dates.

Parameter queries are also handy when used as the basis for forms, reports, and data access pages. For example, you can create a monthly earnings report based on a parameter query. When you print the report, Microsoft Access displays a dialog box asking for the month that you want the report to cover. You enter a month and Microsoft Access prints the appropriate report. For information on creating a parameter query, click [image] .

You can also create a custom form or dialog box that prompts for a query's parameters instead of using the parameter query's dialog box. For more information, click [image] .


 Create a parameter query that prompts for criteria each time it's run

Create a parameter query that prompts for criteria each time it's run

A parameter query displays one or more predefined dialog boxes that prompt you for the parameter value (criteria). You can also create a custom dialog box that prompts for the query's parameters. For more information, click [image] .

  1. Create a select or crosstab query.

  2. In query Design view, drag the fields from the field list to the query design grid.

  3. In the Criteria cell for each field you want to use as a parameter, type a prompt enclosed in square brackets. Microsoft Access will display this prompt when the query is run. The text of the prompt must be different from the field name, although it can include the field name.

    Text in Criteria cell appears as prompt when the query runs

    For a field that displays dates, you can display the prompts "Type the beginning date:" and "Type the ending date:" to specify a range of values. In the field's Criteria cell, type Between [Type the beginning date:] And [Type the ending date:].

  4. To view the results, click View [image] on the toolbar, and then type a value for the parameter. To return to query Design view, click View [image] on the toolbar again.

Notes

  • You must specify a data type for parameters in a crosstab query or in a parameter query that a crosstab query or chart is based on. In the crosstab query, you must also set the ColumnHeadings property. In other parameter queries, specify a data type for a field with the Yes/No data type and fields that come from a table in an external SQL database. For information on specifying a data type for a parameter, click [image] . For information on setting the ColumnHeadings property, click [image] .

  • To prompt the user for one or more characters to search for, and then find records that begin with or contain the characters the user specifies, create a parameter query that uses the LIKE operator and the wildcard symbol (*). For example, the statement:

    LIKE [Enter the first character to search by: ] & "*"

    searches for words that begin with a specified letter. The statement:

    LIKE "*" & [Enter any character to search by: ] & "*"

    searches for words that contain the specified character.

  • You can print parameters in a report. For more information, click [image] .


 What is an SQL query and when would you use one?

What is an SQL query and when would you use one?

An SQL query is a query you create using an SQL statement. Examples of SQL-specific queries are the union query, pass-through query, data-definition query, and subquery.

This topic provides examples of:

Union query

Pass-through query

Data-definition query

Subquery

Union query

This type of query combines fields (columns) from one or more tables or queries into one field or column in the query's results. For example, if you have six vendors that send new inventory lists each month, you can combine these lists into one result set using a union query, and then create a make-table query based on the union query to make a new table. For examples of union queries, click [image] .

For information on creating a union query, click [image] .

Return to top

Pass-through query

This type of query sends commands directly to ODBC databases, such as Microsoft FoxPro, using commands that are accepted by the server. For example, you can use a pass-through query to retrieve records or change data.

For information on creating a pass-through query, click [image] .

Return to top

Data-definition query

This type of query creates, deletes, alters tables, or creates indexes in a database , such as Microsoft Access or Microsoft FoxPro tables.

For information on creating a data-definition query, click [image] .

Return to top

Subquery

This type of query consists of an SQL SELECT statement inside another select query or action query. You can enter these statements in the Field row of the query design grid to define a new field, or in the Criteria row to define criteria for a field. You can use subqueries to:

  • Test for the existence of some result from the subquery (using the EXISTS or NOT EXISTS reserved words).

  • Find any values in the main query that are equal to, greater than, or less than values returned by the subquery (using the ANY, IN, or ALL reserved words).

  • Create subqueries within subqueries (nested subqueries).

For information on creating a subquery, click [image] .

Return to top


Work with SQL in queries, forms, reports, macros, and modules

What do you want to do?

View or modify an SQL statement for an existing query

Generate an SQL statement for copying and pasting elsewhere by creating a query in Design view

Change the SQL statement underlying a form or report

Use an SQL statement as the row source for a list box or combo box

Create an SQL-specific query (union query, pass-through query, data-definition query, subquery)

Perform action query and data-definition query operations from a macro instead of a saved query

Learn how to use SQL in code

Not sure which choice you want?


 Use query Design view to generate an SQL statement to paste elsewhere

Use query Design view to generate an SQL statement to paste elsewhere

You can use SQL statements and clauses in many expressions, as arguments of procedures, and as property settings. For example, you can use an SQL statement to set the RowSource property of a list box in a form or report to generate a list of items.

  1. In query Design view, create the query from which you want to generate the SQL statement.

  2. Click the arrow next to the View button [image] on the toolbar, and then click SQL View.

  3. Select all or part of the SQL statement, and then press CTRL+C to copy the selected text onto the Clipboard.

  4. Place the insertion point where you want to paste the SQL statement, such as in a property box or in the Code window of the Visual Basic Editor.

  5. Press CTRL+V.

Notes

  • You can create or edit a query in SQL view instead of Design view. To do so, switch to SQL view and type or modify the SQL statement for your query. If you then switch back to Design view, the SQL statement will be represented in the design grid.

  • Most query properties in the property sheet in query Design view have equivalent clauses and options available in SQL view.

  • If you use a wizard to create a form, report, or data access page based on more than one table or to create a list box or combo box, Microsoft Access automatically creates an SQL statement to use as the record source for the form, report, or page or the row source for the list box or combo box. Without using a wizard, you can generate an SQL statement for the RecordSource or RowSource properties by clicking the Build button [image] next to either of these properties, and then creating a query in query Design view.

  • You can't use the design grid to create SQL-specific queries. For these types of queries, you must use SQL view. For more information, click [image] .


 View or modify the SQL statement behind an existing query

View or modify the SQL statement behind an existing query

If you're familiar with SQL, you may want to work directly with a query's underlying SQL statement.

  1. Create a query or open an existing query.

  2. Click the arrow next to View [image] on the toolbar, and then click SQL View.

    Microsoft Access displays the SQL statement that is equivalent to what you created in Design view.

  3. If you want to make changes, type your changes in the SQL statement.

  4. To see the changes in the design grid, click the arrow next to the View button on the toolbar, and then click Design View.


 About using expressions in SQL

About using expressions in SQL

You type expressions in SQL statements when you edit a query in SQL view, and in certain property settings and arguments. For example, you can use an SQL statement to set the RowSource property of a list box in a form or report to generate a list of items.

Entering an expression in SQL view

To type an expression in a query's SQL view, click the arrow next to View [image] on the toolbar, and then click SQL View. Microsoft Access displays the SQL statement that describes the active query.

You can type an expression in an SQL SELECT statement, or in WHERE, ORDER BY, GROUP BY, or HAVING clauses.

For examples of expressions in SQL statements, click [image] .

Entering an SQL expression in property settings and arguments

You can type an SQL expression in several arguments and property settings. You can also copy and paste from SQL view. For example, you can use an SQL expression as a Where Condition argument of the OpenForm or ApplyFilter action, as a domain or criteria argument in a domain aggregate function, or as a setting for the RecordSource or RowSource properties in forms and reports.


 Modify the underlying query or SQL statement for a form or report

Modify the underlying query or SQL statement for a form or report

  1. Open the form in Design view or the report in Design view.

  2. Double-click the form selector or the report selector to open the property sheet.

  3. Click the Build button [image] next to the RecordSource property to open the query. You can modify an SQL statement in the same way that you modify a query — just drag fields and set the criteria and sort order in the design grid.

Note If you just want to change from one table or query to another, click the arrow in the RecordSource property box to select from a list of tables and queries.


 Permit others to view or run my query but not change data or query design

Permit others to view or run my query but not change data or query design

In a secure workgroup, you can assign others permission to view the data your query returns or, in the case of an action query, to run the query, even if they are otherwise restricted from viewing the query's underlying table or query.

  1. Open the query in Design view.

  2. Select the query by clicking anywhere in query Design view outside the design grid and the field lists.

  3. Click Properties [image] on the toolbar to display the query's property sheet.

  4. Set the RunPermissions property to Owner's.

    The following are true for this setting:

    • All users have the query owner's permission to view or run the query.

    • Only the query owner can save changes to the query.

    • Only the query owner can change the ownership of the query.

Note You can also set default permissions for all new queries. Click Options on the Tools menu. Click the Tables/Queries tab, and then click the Run Permissions option you want to use.


 Change default permissions for all new queries

Change default permissions for all new queries

You can change the default permissions that allow others to view data returned from queries or, in the case of action queries, to run the queries, even if they are otherwise restricted from viewing the underlying table or query. Changing the default permissions affects only new queries.

  1. On the Tools menu, click Options.

  2. Click the Tables/Queries tab.

  3. Click the Run Permissions option you want to use.

    If you select Owner's:

    • All users have the query owner's permission to view or run the query.

    • Only the query owner can save changes to the query.

    • Only the query owner can change the ownership of the query.

    If you select User's, the permissions that are defined for that classification of users are in effect instead, and any user with Administer permissions for the query can save changes to the query, or change its ownership.


 Set properties for a query, its fields, or its field lists

Set properties for a query, its fields, or its field lists

You can set properties for queries, field lists in a query, and fields you add to the design grid in a query.

  1. Open a query in Design view.

  2. Select a field, field list, or query.
    • To select a field, click the cell in the Field row.

    • To select a field list, click anywhere in the list.

    • To select the whole query, click anywhere in query Design view outside the design grid and the field lists.
  3. Click Properties [image] on the toolbar to display the property sheet for the selected object.

  4. In the property sheet, click the property you want to set, and then do one of the following:
    • If an arrow appears in the property box, click the arrow and then click a value from the list.

    • Type a setting or expression in the property box.

    • If the Build button [image] appears next to the property box, click it to display a builder.

      If you need more space to enter or edit a property setting, press SHIFT+F2 to open the Zoom box.

Tip To get more information on a property and its settings, click the property in the property sheet, and then press F1.


 How field properties in a query and its underlying table or query are related

How field properties in a query and its underlying table or query are related

By default, a field in a query inherits all the properties that it has in the underlying table or query. For instance, if you've set the Format property of an OrderDate field to Medium Date, the OrderDate field is formatted in the query results as Medium Date. Only the field properties you can change are displayed on a field's property sheet in a query.

If you change a field property in table Design view, any new or existing query automatically inherits the change unless you previously changed that property in query Design view. Settings you change in query Design view aren't affected by subsequent changes in table Design view, nor is table Design view affected by the changes you make to the properties in query Design view.

Because calculated fields display data that isn't stored in any table, they don't inherit table properties. For example, your query might include a field that calculates a currency value, but the values in this field aren't displayed in currency format unless you set the Format property for this field to Currency.

When you create a form or report based on a query, the form or report fields take on the field properties you've set in the query or underlying table. If you subsequently change the property setting for a control in the form or report, the change doesn't affect the setting of that property for the field in the underlying query. Likewise, if you change the property setting for a field in a query after you've created a form using that field, the property setting for the control isn't updated; you must update this manually.


 Show or hide table names for each field in the query design grid

Show or hide table names for each field in the query design grid

When you add fields from multiple tables to the design grid, you might want to track which table each field came from by displaying the table names under the field names.

  • In query Design view, click Table Names on the View menu.

To control whether the table names are shown or hidden by default for new queries, click Options on the Tools menu, click the Tables/Queries tab, and then select or clear the Show Table Names check box.


Change the default setting for the OutputAllFields property

Changing this option only affects the property setting for new queries you create, not existing queries.

  1. On the Tools menu, click Options.

  2. Click the Tables/Queries tab, and then select or clear the Output All Fields check box.

Note This option determines whether the query's results automatically include all the fields from the underlying tables or queries (without adding them to the design grid), or only the fields you add to the design grid.


 Open or close a field list for a form, report, or data access page

Open or close a field list for a form, report, or data access page

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click Field List [image] on the toolbar.

You can use the field list to add bound controls to a form, report, or data access page.


 Display or hide the grid on a form, report, or data access page

Display or hide the grid on a form, report, or data access page

  1. Open a form in Design view,a report in Design view, or a data access page in Design view.

  2. On the View menu, click Grid.


Lock down a toolbox tool

  • Double-click the tool you want to lock down.

When a toolbox tool is locked down, you don't have to click the button each time to perform a repeated action. For example, if you want to add several labels to a form, you can lock down the Label tool in the toolbox.

To release the lock, press ESC.


 Open or close the toolbox

Open or close the toolbox

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click Toolbox [image] on the toolbar.


 What is a property sheet?

What is a property sheet?

In Microsoft Access, you use properties to determine the characteristics of tables, queries, fields, forms, reports, and data access pages. Every section and control on a form, report, or data access page has properties as well. Control properties determine the structure, appearance, and behavior of a control, as well as the characteristics of the text or data it contains. You set properties by using the property sheet. For example, the following illustration shows the property sheet for a TotalSales control on a report. The Format property for this control is set to Currency.

Property sheet for the TotalSales text box


 Paste Special options on forms and reports

Paste Special options on forms and reports

When you copy a selection from another application, and click Paste Special on the Edit menu, Microsoft Access displays the Paste Special dialog box. The following table describes the entries in the As list in the Paste Special dialog box.

Click this entry in the As box | If you want to
Application name (for example, Microsoft Excel Worksheet) | Display the object in an unbound object frame. You can edit the object directly from the form or report if you click this entry.
Picture or Bitmap | Display the object in an image control. Click one of these entries if you want to optimize the performance of your form or report. You can't edit the object from the form or report if you click one of these entries.

Text Display the text that you copy (for example, the text in a Microsoft Excel cell) in a label if the object is inserted, or a text box if the object is linked. When you link a text box this way, Microsoft Access creates a DDE link in the text box. When you switch to Form view or Print Preview, you'll see the actual linked text.


 About charts in forms, reports, and data access pages

About charts in forms, reports, and data access pages

This topic provides reference information about:

Why you use charts

Charts in a form or report

Charts in a data access page

Why you use charts

Charts are visually appealing and make it easy for users to see comparisons, patterns, and trends in data. In Microsoft Access, you can create two different kinds of charts: charts in a form or report, and charts in a data access page.

The creation, formatting, and presentation processes differ slightly for each type of chart. For example, each type uses a different Chart Wizard to step you through the process of creating a chart, and both types are meant to be used for specific purposes. Chart types and formatting options also vary.

Return to top

Charts in a form or report

You can use Microsoft Graph 2000 to create a chart in a form or report linked to data from the available tables, queries, or other record sources. The charts can be global (including all data) or record-bound (the chart reflects data only from the current record, and the chart updates as you move from record to record).

Several chart types, including two-dimensional (2-D) and three-dimensional (3-D) types, are available for you to choose from. Formatting options include adding text and graphics to the charts, changing colors, and adding trendlines and error bars.

Learn about creating a chart for a form or report.

Return to top

Charts in a data access page

You can use Microsoft Office Chart, a Microsoft Office Web Component, to create dynamic, interactive charts in a data access page that you can make available on Web sites for viewing in a browser. For example, you can create a chart using data in a table that stores sales figures. When you update the sales figures, the chart updates — so users can always see the latest information on their Web pages.

You can create a chart in a page by using data from tables or queries, or from a spreadsheet or PivotTable list. You can choose from a variety of 2D chart types to which you can add text, change colors, and take advantage of other formatting options such as adding trendlines and error bars.

You can also modify a chart in a page that was published as an interactive chart from Microsoft Excel. When you publish an interactive chart in Microsoft Excel, the data for the chart is published with it as a spreadsheet or PivotTable list. For more information on publishing charts from Excel, see Excel Help.

Microsoft Internet Explorer 5 or later is required to create a chart on a page, but users with Internet Explorer version 4.x or later can view the chart and see the chart updated in response to changes to data.

Learn about creating a chart in a page.

Return to top


 About making changes to a chart in a form or report

About making changes to a chart in a form or report

There are two types of changes you can make when editing a chart: cosmetic or data.

Cosmetic changes include changing the size of the chart on the form or report, or changing the appearance of the chart with Microsoft Graph, such as the location of its parts, the text format, the colors and patterns, and the axis scaling.

Data changes include modifying the underlying table or other record source, or the query in the RowSource property.

When you use the Chart Wizard to create a chart that displays data from Microsoft Access, you choose the table or other record source that includes the fields that are displayed in the chart. This underlying table or other record source contains the data, such as sales figures or customer lists. After you have finished making selections in the Chart Wizard, Microsoft Access creates a query in the RowSource property, which is based on the underlying table or other record source. The query in the RowSource property reflects the choices you made in the Chart Wizard to restrict the data, such as a range of dates or orders from a specific region.

For example, if you notice that the sales figures in your chart are wrong, the problem may be in the data stored in the underlying table, or in the design of the underlying record source. In this case, correct the underlying table or other record source. However, if you left out a field that you want to appear in your chart, either you can use the Chart Wizard to create the chart again or you can edit the query in the RowSource property.

More information

Change the appearance of the chart

Change the data in the underlying table or other record source

Customize the format of a chart


 Add a new chart to a form or report

Add a new chart to a form or report

  1. Open the form in form Design view or report in report Design view.

  2. Click Chart on the Insert menu.

    Tip If you create a lot of charts, you may want to add Chart [image] to the toolbar.

    How?

  3. On the form or report, click where you want to place the chart.

  4. Follow the directions in the Chart Wizard, which creates the chart based on available tables or other record sources and the fields you select.

    Note At least one of the fields must have a data type that stores only numbers, such as Currency.

  5. Switch to Form view or Print Preview to see the chart with current data.

Notes

  • In a Microsoft Access project, you can't use the Chart Wizard, but you can add a chart by inserting the Microsoft Graph 2000 Chart object (Insert menu, Object command).

  • In form or report Design view, the chart shows sample data when you first create it. To see current data, switch to Form view or Print Preview, or close the form or report and then open it. Learn about customizing a chart.

  • The Chart Wizard creates a query for the record source in the RowSource property, which reflects the data restrictions that you specified when you filled out the Chart Wizard dialog boxes. If the chart doesn't look the way you want it to look, click [image] .

  • You can't create a radar, surface, or combination chart by using the Chart Wizard. However, in Microsoft Graph you can change the chart you created with the Chart Wizard to any chart type, including a radar, surface, or combination chart. Learn about using Microsoft Graph.


 Link an existing chart in a form or report to a specific record

Link an existing chart in a form or report to a specific record

If the Chart Wizard creates one global chart, and you want a record-bound chart, you can link the chart to a specific record by following this procedure.

  1. Open the form in form Design view or report in report Design view.

  2. Make sure the chart is selected, and then click Properties [image] .

  3. In the LinkChildFields and LinkMasterFields property boxes, type the name of a field that appears in the RowSource property box and uniquely identifies each record, such as a primary key.

    The values in these property boxes must match record for record the values in a field in the underlying table or other record source for the form or report. For example, suppose the form's underlying table includes the ProductID field. You want to link your chart on this field, so you type ProductID in the LinkChildFields and LinkMasterFields property boxes.

  4. To see whether your chart displays only the data for the current record, display the form in Form view, or look at the report in Print Preview.


 Add an existing chart to a form or report

Add an existing chart to a form or report

Use this procedure to add an existing chart that was created in another Microsoft Access database or another program. When you do this, you will not be able to change the chart by changing data in your database.

  1. Open the form in form Design view or report in report Design view.

  2. Click Unbound Object Frame [image] in the toolbox.

  3. On the form or report, click where you want to place the chart.

  4. In the Insert Object dialog box, click Create From File, and then specify a path to the file. If you don't know the path, click Browse.

  5. If you want to link rather than embed the chart, select the Link check box.

  6. Select the Display As Icon check box if you want the chart to appear as an icon.


 Add the Chart button to a toolbar in Design view of a form or report

Add the Chart button to a toolbar in Design view of a form or report

Note You can add the Chart button only in a Microsoft Access database, not a Microsoft Access project.

  1. Switch to the appropriate view, and make sure the toolbar you want to put the Chart button on is displayed.

  2. Right-click anywhere on the toolbar.

  3. Click Customize.

  4. Click the Commands tab.

  5. In the Categories box, click Toolbox.

  6. From the Commands box, drag the Chart [image] button to the toolbar on which you want it to appear.


 Change the size of a chart in a form or report

Change the size of a chart in a form or report

  1. Open the form in form Design view or report in report Design view.

  2. Click the chart.

  3. Move the mouse pointer over any of the sizing handles until the pointer becomes a double-headed arrow.

  4. Drag the handle to where you want the edge of the object to be, and then release the mouse button.


 Change the appearance of a chart in a form or report

Change the appearance of a chart in a form or report

  1. Open the form in form Design view or report in report Design view.

  2. Double-click the chart to open Microsoft Graph.

  3. Make the changes you want.

    Learn about customizing a chart.

    For information about using Microsoft Graph, click Microsoft Graph Help on the Help menu.

  4. When you finish editing, click Exit on the Microsoft Graph File menu.

  5. When the application prompts you to update the object, click Yes.

Note Although you can change the data that appears in your chart by editing the datasheet in Microsoft Graph, changes to the data as well as some formatting changes will be overwritten by Microsoft Access. To change the data that is displayed in your chart, you should change the underlying table or other record source, or the query in the RowSource property. For information on changing this query, click [image] .


 Change the data in the underlying table or other record source for a chart in a form or report

Change the data in the underlying table or other record source for a chart in a form or report

To change the data in an underlying table

  • Open the underlying table in Datasheet view and then edit the data.

To change the data in an underlying record source

  • Open the underlying record source in Design view and then edit the data.

When you have changed the data in the underlying table or other record source, you must open the form in Form view or report in Print Preview to see the chart with current data.

If changing the data in the underlying table or other record source doesn't work, you can try changing the query in the RowSource property. For information on changing the RowSource query, click [image] .


 Convert a chart in a form or report to a picture to save disk space

Convert a chart in a form or report to a picture to save disk space

If you need to save disk space, you can convert the chart to a picture, as long as the chart isn't a record-bound chart. Once you do this, you can no longer edit the chart.

  1. Open the form in form Design view or report in report Design view.

  2. Click the chart.

  3. On the Format menu, point to Change To, and then click Image.


 Graphic filters and file formats Microsoft Access can use

Graphic filters and file formats Microsoft Access can use

You can insert many popular graphics file formats into a form, report, or data access page either directly or with the use of separate graphics filters by using the Picture command on the Insert menu. For forms and reports, you don't need a separate graphics filter installed to insert Enhanced Metafile (.emf), Windows bitmap (.bmp, .rle, .dib), Windows Metafile (.wmf), and icon (.ico) graphics. However, you do need a graphics filter installed to insert all other graphics file formats listed below.

Graphics file formats requiring separate graphics filters
Computer Graphics Metafile (.cgm) | Kodak Photo CD (.pcd)
CorelDRAW (.cdr) | Macintosh PICT (.pct)
Encapsulated PostScript (.eps) | PC Paintbrush (.pcx)
FlashPix (.fpx) | Portable Network Graphics (.png)
Graphic Interchange Format (.gif) | Tagged Image File Format (.tif)
Hanako (.jsh, .jah, .jbh) | WordPerfect Graphics (.wpg)
JPEG File Interchange Format (.jpg) | X-Bitmap (.xbm)

For pages, you don't need a separate graphics filter installed to insert Windows bitmap (.bmp, .rle, .dib) graphics. However, you do need a graphics filter installed to insert Graphic Interchange Format (.gif), JPEG File Interchange Format (.jpg), Portable Network Graphics (.png), and X-Bitmap (.xbm) graphics.

The separate graphics filters are not supplied with the stand-alone version of Microsoft Access 2000. To use the filters, you need to install Microsoft Office 2000 Professional Edition, Microsoft Office 2000 Premier Edition, or a stand-alone version of Microsoft Word 2000 along with your stand-alone version of Access 2000.

Note For more information on each separate graphics filter, see your Word documentation.


Forms: What they are and how they work

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


Create a form

What do you want to do?

Create a form by using AutoForm. With AutoForm, you select one record source and either columnar, tabular, or datasheet layout; AutoForm creates a form that uses all the fields from the record source you selected and all the fields from its related record sources.

Create a form with a wizard. The wizard asks you detailed questions about the record sources, fields, layout, and format you want and creates a form based on your answers.

Create a form on my own

Create a form based on more than one table


Ways to customize a form

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


Add a picture or other object to a form, report, or data access page

What do you want to do?

Add an unbound picture to a form, report, or data access page

Add an unbound object (for example, a Microsoft Excel or Microsoft Word document) to a form or report

Add a bound picture or object (for example, an Excel or Word document) to a form or report

Add a bound picture to a data access page

Not sure which choice you want?


 Create a form or report from filtered records

Create a form or report from filtered records

  1. With the filtered records displayed, click the arrow next to the New Object button on the toolbar.
    • To use the AutoForm or AutoReport Wizard, click AutoForm or AutoReport.

    • To specify the type of form or report you want to create, click Form or Report, and then make your selection.

      The new object uses as its record source the table or query in which the filter was created, and it inherits the filter.

  2. Complete the design or make any other changes you want to the form or report, and then save it.

Notes

  • If a sort order was specified in the underlying table or query, the new form or report will use it.

  • If you subsequently change the filter in a table or query, it has no effect on a form or report that was based on a filter you created previously in that table or query.


 Open a form

Open a form

  1. In the Database window, click Forms [image] under Objects.

  2. Click the form you want to open.

  3. Click the Open button to open the form in Form view, or the Design button to open the form in Design view.

Tip You can also open a form in Form view by dragging the form from the Database window to the application background.

Once you've opened a form, you can easily switch among the three views of the form by clicking the View button on the toolbar.


 Switch between views of a form

Switch between views of a form

  • Click the View button on the toolbar. To change to the view indicated by the graphic, click the button itself. To see a list of other views to choose from, click the arrow next to the button.

To learn more about what the different views are used for, click [image] .


Views of a form

Forms have three views: Design view, Form view, and Datasheet view.

To create a form, you work in Design view. Viewing a form in Design view is like sitting at a workbench surrounded by useful tools.

A form in Design view

After you've created a form in Design view, you can view it in Form view or Datasheet view.

A form in Form view and Datasheet view


 Select a form or report

Select a form or report

  1. Open a form in Design view or a report in Design view.

  2. Click the form selector or report selector.

    Form selector or report selector

    If the rulers aren't displayed, you can click Select Form or Select Report on the Edit menu, or you can click the gray background to the right of the form to select it.


 Select a section on a form or report

Select a section on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Click the section selector or anywhere in the section bar.

    Section selector and section bar

    You can also click anywhere in the background of the section to select it.


 Change the distance between dots on the form or report grid

Change the distance between dots on the form or report grid

  1. Open a form in Design view or a report in Design view.

  2. Double-click the form selector or the report selector to open the property sheet.

  3. To change the horizontal dots, type a new value for the GridX property. To change the vertical dots, type a new value for the GridY property. Higher numbers indicate less distance between dots.

Note The grid is preset to 24 dots per inch horizontally and 24 dots per inch vertically. If you're using centimeters as your unit of measure, the grid is set to 10 x 10. You can change these settings to any integer value from 1 to 64. Dots on the grid are invisible if you choose a setting that is greater than 24 dots per inch or 9 dots per centimeter.


 Set properties for a form, report, section, or control

Set properties for a form, report, section, or control

  1. Open a form in Design view or a report in Design view. If the AllowDesignChanges property of a form is set to All Views, you can also set properties in Form view and Datasheet view.

  2. Do one of the following:
    • To set properties for a form or report, double-click the form selector or the report selector to open the property sheet for the form or report.

    • To set properties for a section on a form or report, double-click the section selector to open the property sheet for the section.

    • To set properties for a control, make sure the control is selected, and then click Properties [image] on the toolbar. You can also double-click a control to open its property sheet.
  3. In the property sheet, click the property you want to set, and then do one of the following:
    • If an arrow appears in the property box, click it and then select a value from the list.

    • Type a setting or expression in the property box.

    • If a Build button [image] appears next to the property box, click it to display a builder or to display a dialog box giving you a choice of builders. For example, you can use the Query Builder to change the design of an underlying query for a form or report.
  4. If you need more space to enter or edit a property setting, press SHIFT+F2 (or right-click and then click Zoom) to open the Zoom box.

If the property sheet is blank or if you don't see the properties you expect in the property sheet, click [image] .

Tip To get Help on any property in the property sheet, click the property and then press F1.


 Set the size of a form when it's first opened

Set the size of a form when it's first opened

  1. Open a form in Form view.

  2. Size the form by dragging the borders of the Form window.

  3. Click Save [image] on the toolbar.

Note If the AutoResize property is set to Yes, Microsoft Access automatically sizes the form to display complete records. To set the form to the size you want, make sure the AutoResize property is set to No.


 Revert to saved version of a form or report

Revert to saved version of a form or report

You can discard any changes — including changes to Microsoft Visual Basic code — that you have made in Design View of a form or report and revert to the last saved version of the form or report.

Caution Once you have reverted to the last saved version of the form or report, you cannot recover the changes that you have made to the form or report since you last opened it.

To revert to the last saved version, do the following:

  • On the File menu, click Revert.

Note This command is not available unless you have opened a form or report in Design view and have made changes to it. The Revert command is not available in Design view of a data access page.


 Preview a form

Preview a form

To preview a form from Design view, Form view, or Datasheet view

  1. Click Print Preview [image] on the toolbar.

  2. To return to Design view, Form view, or Datasheet view, click the View button on the toolbar.

To preview a form from the Database window

  1. Click Forms [image] under Objects.

  2. Select the form you want to preview.

  3. Click Print Preview [image] on the toolbar.

How Microsoft Access displays a form in Print Preview depends on the view from which you preview it.

From | You see the form
Design view | In Form view.
Form view | In Form view.
Datasheet view | As a datasheet.
Database window | In the view specified by the DefaultView property of the form.

For information on viewing a form at different magnifications, click [image] .

For information on viewing two or more pages at one time, click [image] .


Print a form

What do you want to do?

Set the page orientation or other page setup options

Print a form from Design view, Form view, or Datasheet view

Print a form from the Database window

Print selected records in a form or datasheet

Print the current record

Print a form using a shortcut


 Print selected records in a form or datasheet

Print selected records in a form or datasheet

  1. Open the form in Form view or Datasheet view.

  2. Select the record you want to print by clicking the record selector or by pressing SHIFT+SPACEBAR (if you're in Edit mode, press F2 before pressing SHIFT+SPACEBAR). If you want to select multiple records, click the first record selector and drag through to the last record you want to print.

  3. On the File menu, click Print.

  4. In the Print dialog box under Print Range, click Selected Record(s).


 Allow changes to a form's properties in Form and Datasheet views

Allow changes to a form's properties in Form and Datasheet views

  1. Open the form in Design view.

  2. Double-click the form selector to open the property sheet for the form.

  3. Set the AllowDesignChanges property to All views.

When the AllowDesignChanges property is set to All views, you can modify the properties of the form and its controls by displaying the property sheet in Form view and Datasheet view.


 Specify whether a form opens for data entry only

Specify whether a form opens for data entry only

  1. Open the form in Design view.

  2. Double-click the form selector to open the form's property sheet.

  3. In the DataEntry property box, click Yes if you want the form to open for data entry (blank record); click No if you want the form to open with all records showing.


 Set the opening view of a form (one record, more than one, or datasheet)

Set the opening view of a form (one record, more than one, or datasheet)

  1. Open the form in Design view.

  2. Double-click the form selector to open the form's property sheet.

  3. In the DefaultView property box, click one of the following settings.
    Setting | Description
    Single Form | Displays one complete record at a time. (Form view only)
    Continuous Forms | Displays as many complete records as will fit in the detail section of the form. (Form view only)
    Datasheet | Displays records arranged as rows and columns. Records may scroll off the screen.

Note If you want to disable Form view or Datasheet view, you can set the ViewsAllowed property.


Sections of a form

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


 Add or remove a form header and footer or a page header and footer

Add or remove a form header and footer or a page header and footer

  1. Open the form in Design view.

  2. Click Form Header/Footer or Page Header/Footer on the View menu.

Notes

  • Form headers and footers appear at the top and bottom of a form in Form view and at the beginning and end of a printed form. Page headers and footers appear at the top and bottom of each printed page — they don't appear in Form view.

  • If you remove a header and footer, Microsoft Access deletes the controls in the header and footer.

  • You can only add a header and footer as a pair. If you don't want both a header and a footer, you can size the one you don't want so that it has no height, or you can set its Visible property to No. You can also set the DisplayWhen property of a form header and footer to specify when you want the header and footer to be displayed ? always, in print only, or on the screen only.
Example of using different types of sections in forms


 Hide section divider lines in a form

Hide section divider lines in a form

  1. Open a form in Design view.

  2. Double-click the form selector to open the property sheet.

  3. In the DividingLines property box, click No.


 Size a form to fit its contents

Size a form to fit its contents

  1. Open a form in Form view.

  2. Click Size To Fit Form on the Window menu.

    Note If the Form window is maximized, the Size To Fit Form command is unavailable.

  3. Click Save [image] on the toolbar to save the size of the form.

When you click Size To Fit Form, Microsoft Access adjusts the size of the form depending on whether the form's DefaultView property setting is set to Single Form or Continuous Forms.

  • Single Form. If the displayed record is smaller than the Form window, Size To Fit Form crops the window to the size of the record. If the record is larger than the Form window, Size To Fit Form expands the Form window to show as much of the record as possible.

  • Continuous Forms. If only part of the bottom record is displayed, Size To Fit Form crops that record. If only one record is partially displayed, Size To Fit Form enlarges the window to show as much of the record as possible.


 Center a form in the application window when it's first opened

Center a form in the application window when it's first opened

  1. Open a form in Design view.

  2. Double-click the form selector to open the property sheet.

  3. Set the AutoCenter property to Yes.

    The next time you open the form, it will be centered in the application window.


Change the ruler's unit of measure in a form or report

  1. Click the Windows Start button, point to Settings, and then click Control Panel.

  2. Double-click the Regional Settings icon.

  3. Click the Number Tab.

  4. In the Measurement System list, click Metric or U.S.


 Change tab order in a form

Change tab order in a form

  1. Open the form in Design view.

  2. On the View menu, click Tab Order.

  3. Under Section, click the section you want to change.

  4. Do one of the following:
    • If you want Microsoft Access to create a left-to-right and top-to-bottom tab order, click Auto Order.

    • If you want to create your own custom tab order, click the selector for the control you want to move. (Click and drag to select more than one control at a time.) Click the selector again and drag the control to the desired location in the list.
  5. Click OK.

  6. Switch to Form view to test the tab order. (In Design view, the tab order is always the order in which you created the controls.)

Notes

  • If you want to be able to select a control on a form, but you don't want to include that control in the tab order, set its TabStop property to No.

  • You can also specify which record or page to move the focus to when you press the TAB key in the last field in the current record.

    How?


 Change the tab behavior for the last field on a form

Change the tab behavior for the last field on a form

  1. Open a form in Design view.

  2. Double-click the form selector to open the form's property sheet.

  3. In the Cycle property box, click one of the following settings.
    Setting | Description
    All Records | When you press TAB in the last field in the record, the focus moves to the first field in the next record.
    Current Record | When you press TAB in the last field in the record, the focus moves back to the first field in the current record.
    Current Page | When you press TAB in the last field in the form page, the focus moves back to the first field in the current page.


 Remove the shortcut menu from a form

Remove the shortcut menu from a form

  1. Open the form in Design view.

  2. Double-click the form selector to open the form's property sheet.

  3. In the ShortcutMenu property box, click No.


 Remove record selectors from a form

Remove record selectors from a form

  1. Open the form in Design view.

  2. Double-click the form selector to open the form's property sheet.

  3. In the RecordSelectors property box, click No.


 Remove the navigation buttons from a form

Remove the navigation buttons from a form

  1. Open the form in Design view.

  2. Double-click the form selector to open the form's property sheet.

  3. In the NavigationButtons property box, click No.


 Disable the Close button on a form

Disable the Close button on a form

  1. In form Design view, double-click the form selector to open the property sheet.

  2. In the CloseButton property box, click No.

Notes

  • When you set the CloseButton property to No, Microsoft Access disables the Close button [image] and also disables the Close command on the Control menu.

  • If you want to remove the Close button completely, you may want to use the BorderStyle property. For more information, click [image] .


 Add or remove scroll bars for a form or text box

Add or remove scroll bars for a form or text box

  1. Open the form in Design view.

  2. Open the property sheet for the text box or form. To open the property sheet for the text box, click it, and then click Properties [image] on the toolbar. To open the property sheet for the form, double-click the form selector.

  3. In the ScrollBars property box, click one of the settings.


 Hide record divider lines in a continuous form

Hide record divider lines in a continuous form

  1. Open a form in Design view.

  2. Double-click the form selector to open the property sheet.

  3. In the DividingLines property box, click No.


 Hide the Control menu on a form

Hide the Control menu on a form

  1. Open the form in Design view.

  2. Double-click the form selector to open the form's property sheet.

  3. In the ControlBox property box, click No.

Notes

  • If the BorderStyle property for the form is set to None, the form won't have a Control menu even if the ControlBox property is set to Yes.

  • When you set the ControlBox property to No, the Minimize, Maximize, and Close buttons are also hidden.


 Hide the Maximize and Minimize buttons on a form

Hide the Maximize and Minimize buttons on a form

  1. Open the form in Design view.

  2. Double-click the form selector to open the form's property sheet.

  3. In the MinMaxButtons property box, click a setting.

Note If the BorderStyle property for the form is set to None or Dialog, the form won't have Minimize and Maximize buttons even if the MinMaxButtons property is set to Min Enabled, Max Enabled, or Both Enabled.


 Temporarily open any form as a dialog box

Temporarily open any form as a dialog box

  1. Create a macro or event procedure that uses an OpenForm action to open the form.

  2. Set the Window Mode argument of the OpenForm action to Dialog (acDIALOG for an event procedure).

    When you open a form that has its Window Mode argument set to Dialog, Microsoft Access sets the form's PopUp and Modal properties to Yes until the form is closed. It also disables user-defined key combinations and some other Microsoft Access function keys and suspends the macro or event procedure until you close or hide the form. You can hide a form by setting its Visible property to No using the SetValue action.


Work with groups of controls on a form or report

What do you want to do?

Group text boxes or other controls

Ungroup text boxes or other controls

Resize a text box or other control in a group

Move a text box or other control in a group

Select a single text box or other control in a group

Add a text box or other control to an existing group

Remove a text box or other control from a group

Delete a text box or other control that is in a group


Conditional formatting in a text box or other control on a form or report

What do you want to do?

Change the color of a control that has focus on a form

Change the format of the value in a control when it meets certain criteria

Change, add, or remove conditional formatting for a control

Not sure which choice you want?


 Copy the conditional formatting of a text box or other control on a form or report

Copy the conditional formatting of a text box or other control on a form or report

  1. Open the form in Design view or the report in Design view.

  2. Select the control that has the conditional formatting that you want to copy.

  3. Click Format Painter [image] on the toolbar.

  4. Click the control you want to copy the formatting to.


 Subforms: What they are and how they work

Subforms: What they are and how they work

A subform is a form within a form. The primary form is called the main form, and the form within the form is called the subform. A form/subform combination is often referred to as a hierarchical form, a master/detail form, or a parent/child form.

Subforms are especially effective when you want to show data from tables or queries with a one-to-many relationship. For example, you could create a form with a subform to show data from a Categories table and a Products table. The data in the Categories table is the "one" side of the relationship. The data in the Products table is the "many" side of the relationship — each category can have more than one product.

Main form with a subform

The main form and subform in this type of form are linked so that the subform displays only records that are related to the current record in the main form. For example, when the main form displays the Beverages category, the subform displays only the products in the Beverages category.

When you use a form with a subform to enter new records, Microsoft Access saves the current record in the main form when you enter the subform. This ensures that the records in the "many" table will have a record in the "one" table to relate to. It also automatically saves each record as you add it to the subform.

A subform can be displayed as a datasheet, as in the preceding illustration, or it can be displayed as a single or continuous form. A main form can be displayed only as a single form.

A main form can have any number of subforms if you place each subform on the main form. You can also nest up to ten levels of subforms. This means you can have a subform within a main form, and you can have another subform within that subform, and so on. For example, you could have a main form that displays customers, a subform that displays orders, and another subform that displays order details.

More information

See examples of different types of subforms

Create one or more subforms


 Types of subforms

Types of subforms

When you create a subform, you can design it to be displayed in Datasheet view only; in Form view only as a single or continuous form; or in either view. A subform displayed as a single or continuous form can be simple or it can be customized extensively to include a header, footer, and so on.

Subform displayed as a datasheet

Subform displayed as a simple continuous form

Subform displayed as a continuous form that looks like a datasheet

More information

Subforms: What they are and how they work

Create one or more subforms

Make a continuous subform look like a datasheet that displays a header and footer


 Change the layout of a subform

Change the layout of a subform

How you change the layout of a subform depends on whether the subform is displayed in Datasheet view or in Form view as a single or continuous form.

What do you want to do?

Change the layout of a subform displayed in Datasheet view

Change the layout of a subform displayed as a single or continuous form

Change the view that the subform is displayed in


 How Microsoft Access links main forms and subforms

How Microsoft Access links main forms and subforms

You usually use a subform to display data from tables or queries that have a one-to-many relationship. For example, a Categories table and a Products table have a one-to-many relationship — each category can have more than one product.

When you create a form and subform based on tables that have a one-to-many relationship, the main form shows the "one" side of the relationship and the subform shows the "many" side of the relationship. The main form is synchronized with the subform so that the subform shows only records related to the record in the main form. If you use a wizard to create a subform, or if you drag a form, table, or query from the Database window to another form to create a subform, Microsoft Access automatically synchronizes the main form with the subform if both of the following are true:

  • You have defined relationships for the tables you select, or you have defined relationships for the tables underlying the queries you select.

  • The main form is based on a table with a primary key and the subform is based on a table that contains a field with the same name as that primary key and with the same or a compatible data type and field size. For example, if the primary key of the table underlying the main form is an AutoNumber field and its FieldSize property is set to Long Integer, the corresponding field in the table underlying the subform should be a Number field with its FieldSize property set to Long Integer. If you select a query or queries, the underlying tables for the query or queries must meet these conditions.

Note Microsoft Access uses the LinkMasterFields and LinkChildFields properties of the subform control to link the main form and subform. If, for some reason, Microsoft Access doesn't link the form and subform, you can link the forms yourself.


 Link a main form and a subform

Link a main form and a subform

If you create a subform with the Form Wizard or the Subform Wizard, Microsoft Access automatically links the main form with the subform under certain conditions. For more information, click [image] . If your main form and subform don't meet these conditions, you can use this procedure to link them.

  1. Open the main form in Design view.

  2. Make sure the subform control is selected, and then click Properties [image] on the toolbar to display the property sheet for the subform control.

  3. Type the linking fields or controls in the LinkChildFields and LinkMasterFields properties. To enter more than one linking field or control, separate the field or control names with a semicolon. If you enter more than one field or control name, you must enter the names in the same order in both properties.
    • In the LinkChildFields property box, enter the name of each linking field in the subform. (You can’t use the name of a control in this property.)

    • In the LinkMasterFields property box, enter the name of each linking field or control in the main form.

      If you're unsure what the linking field or control is for either property, click the Build button next to the property box to open the Subform/Subreport Field Linker.

  4. Switch to Form view to test the link.

Notes

  • The linking fields don't have to appear in the main form or the subform, but they must be included in the underlying record source. If you use the Form Wizard to create the subform, Microsoft Access automatically includes the linking fields in the underlying record source even if you don't pick them in the wizard.

  • The linking fields must contain the same kind of data and have the same or a compatible data type or field size. For example, an AutoNumber field with its FieldSize property set to Long Integer is compatible with a Number field with its FieldSize property set to Long Integer.

  • Make sure that the LinkChildFields property is set to the name of a field (as specified in the ControlSource property), not the name of a control (as specified in the Name property). The LinkMasterFields property can be set to the name of either a field or a control.

  • For information on troubleshooting subforms, click [image] .


 Specify the view for a subform

Specify the view for a subform

If you use the Form Wizard or the Subform Wizard to create a subform, Microsoft Access sets the DefaultView property of the subform according to the choices you make in the wizard dialog boxes. Use this procedure if you're creating a subform on your own or if you want to change the view you specified in the wizard.

  1. Open the main form in Design view. The subform is displayed in Design view in the subform control.

  2. Make sure the subform control is selected. After it’s selected, you can click again inside the control to set the properties of the form, just as you would if you opened the subform in Design view from the Database window.

  3. Double-click the form selector to open the subform's property sheet.

  4. In the DefaultView property box, click Single Form, Continuous Forms, or Datasheet.

  5. In the ViewsAllowed property box, click the Form setting if you don't want to be able to switch to Datasheet view. Click the Datasheet setting if you don't want to be able to switch to Form view. If you want to be able to switch back and forth between Datasheet and Form views, click the Both setting.

Notes

  • To see examples of different types of subforms, click [image] .

  • You can also change the default view of the subform by opening the subform directly from the Database window.


 Move between a main form and a subform in Form view

Move between a main form and a subform in Form view

Using the TAB key

  • To move from the last field in the main form to the first field in the subform, press TAB.

  • To move from the first field in the subform back to the last field in the main form, press CTRL+SHIFT+TAB.

  • To move from the last field in the subform to the next field on the main form or to the first field in the next record or next page of the main form, press CTRL+TAB. If the Cycle property of the form is set to Current Record or Current Page, you must use the navigation buttons or other methods provided on the form to move to the next record.

Using the mouse

  • To switch from the main form to the subform, click anywhere in the subform.

  • To switch from the subform back to the main form, click a control on the main form (not the background of the main form).


 Switch between Datasheet view and Form view in a subform

Switch between Datasheet view and Form view in a subform

  1. Open the main form in Form view.

  2. Click anywhere in the subform.

  3. On the View menu, click Subform Datasheet.

Note The ViewsAllowed property for the subform must be set to Both in order to switch views.


 Make a subform look like a datasheet that displays a header and footer

Make a subform look like a datasheet that displays a header and footer

You can display a form header and footer on a subform and arrange the text boxes and other controls so that the subform looks like a datasheet when you open the form in Form view.

  1. Open the form that you want to use as the subform in Design view.

  2. Add a form header and footer if you haven’t already done so. (On the View menu, click Form Header/Footer.)

  3. In the detail section, arrange the text boxes and other controls that display data in a single row.

  4. In the form header, arrange the labels for the text boxes and other controls. Make sure that you align the labels in the form header with their associated controls in the detail section.

  5. In the form footer, if you want to total the records in the subform, create calculated controls.

  6. Size each section appropriately. For example, make the detail section the size of one row in a datasheet. If you don’t have any controls in the form footer, set its Height property to 0 or set its Visible property to No.

  7. Double-click the form selector to open the property sheet for the form.

  8. In the DefaultView property box, click Continuous Forms. This setting displays records in a form one after another, similar to a datasheet.

Notes

  • When you set DefaultView to Datasheet, Microsoft Access hides the header and footer when you display the form in Form view.

  • The Quarterly Orders form in the Northwind sample database has a continuous subform that has a form header and footer and looks like a datasheet. To view this form, open the Northwind database in the Samples subfolder of your Office folder, and then open the Quarterly Orders form in Design view. For information on opening the Northwind database, click [image] .


 Create a calculated control on a form or report

Create a calculated control on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Click the tool in the toolbox for the type of control you want to use as the calculated control.

    Note A text box is the most common type of control to use to display a calculated value, but you can use any control that has a ControlSource property.

  3. On the form or report, click where you want to place the control.

  4. Do one of the following:
    • If the control is a text box, you can type the expression directly in the text box.

    Expression in a text box

    • For any control, make sure the control is selected, click Properties [image] on the toolbar to display the control's property sheet, and type the expression in the ControlSource property box. To use the Expression Builder to create the expression in a Microsoft Access database (.mdb), click the Build button [image] next to the ControlSource property box.

Notes

  • In a calculated control, precede each expression with the = operator.

  • If you need more room to type an expression in the ControlSource property box, press SHIFT+F2 to open the Zoom box.

  • For more information about creating expressions in a Microsoft Access database (.mdb), click [image] .

  • For more information about creating expressions in a Microsoft Access project (.adp), click [image] .

  • If a form is based on a query, you may want to put the expression in the query instead of in a calculated control. For information on creating a calculated field in a query in a Microsoft Access database (.mdb), click [image] . For information on creating a calculated field in a query in a Microsoft Access project (.adp), click [image] .


 Calculate a total for one record in a form

Calculate a total for one record in a form

  1. Open the form in Design view.

  2. Click the Text Box tool Text Box control in the toolbox.

  3. In the form's detail section, click where you want to place the text box.

  4. Do one of the following:
    • Place the insertion point in the text box and type an expression that calculates a total. To see examples of expressions you can use to compute values for one record, click [image] .

    • Make sure the text box is selected, click Properties [image] on the toolbar to open its property sheet, and type the expression in the ControlSource property box. In a Microsoft Access database (.mdb), to use the Expression Builder to create the expression, click the Build button [image] next to the ControlSource property box.

Notes

  • If you need more room to type an expression in the ControlSource property box, press SHIFT+F2 to open the Zoom box.

  • For more information about creating expressions in a Microsoft Access database (.mdb), click [image] .

  • For more information about creating expressions in a Microsoft Access project (.adp), click [image] .

  • If a form is based on a query, you may want to put the expression in the query instead of in a calculated control. For information on creating a calculated field in a query in a Microsoft Access database (.mdb), click [image] . For information on creating a calculated field in a query in a Microsoft Access project (.adp), click [image] .


 About calculating a total in a subform and displaying it on a form

About calculating a total in a subform and displaying it on a form

You can use a form with a subform to calculate a total for a group of records. The main form and the subform are based on tables with a one-to-many relationship. The main form shows records from the "one" side of the relationship; the subform shows records from the "many" side of the relationship. For example, the following illustration shows an Orders form that includes a subform.

The main form and subform in Form view

To calculate the order subtotal, you add a text box to the form footer of the subform and specify an expression in the ControlSource property box for the text box. The expression uses the Sum function. For example, the following expression calculates the total amount for all the products in the Orders form:

=Sum([Quantity]*[UnitPrice])

In the subform's Design view, the calculated control is in the form footer

To display the order subtotal on the main form, create a text box on the main form that uses an expression to refer to the control on the subform that contains the calculated value. For example, you could specify the following expression in the ControlSource property box of the text box on the main form:

Expression on the main form that references the calculated control on the subform

Notes

  • If you want to use the value from a calculated control when computing a total, you can't use the name of the control in the Sum function. For example, if you had a control that calculated quantity * unit price, you'd still have to specify the full syntax =Sum([Quantity]*[UnitPrice]) in the expression. For this reason, when you use an expression that requires an aggregate function such as Sum, it's best to define the expression in the form's underlying query or SQL statement. Then you can use the name of the calculated field in the Sum function. For example, you could define a calculated field such as ExtendedPrice: [Quantity]*[UnitPrice] in an underlying query, and then use the field name in the expression that calculates the sum: =Sum([ExtendedPrice]). For information on creating a calculated field in a query in a Microsoft Access database (.mdb), click [image] . For information on creating a calculated field in a query in a Microsoft Access project (.adp), click [image] .

  • The Orders form in the Northwind sample database has an example of a subform that calculates a subtotal that's displayed on the main form. To view this form, open the Northwind database in the Samples subfolder of your Office folder, and then open the Orders form in Design view. For information on opening Northwind, click [image] .


Validate or restrict data in forms

By validating or restricting data, you can give users immediate feedback about the data just entered and ensure that they get the correct information into a text box or other control on a form.

What do you want to do?

Create an input mask for a control

Disable or lock a control

Create a validation rule for a control

Read about the order in which different kinds of validation are applied

Read about complex validation you can do with macros or event procedures


 Disable Form view or Datasheet view for a form

Disable Form view or Datasheet view for a form

  1. Open the form in Design view.

  2. Double-click the form selector to open the form's property sheet.

  3. In the ViewsAllowed property box, click Form to disable Datasheet view, or click Datasheet to disable Form view.

Note You can use this property together with the DefaultView property to determine how users see a form and whether they can see it in different views. To see different combinations of these properties, click [image] .


 Make a form read-only

Make a form read-only

  1. Open the form in Design view.

  2. Double-click the form selector to open the form's property sheet.

  3. In the AllowEdits property box, click No.

  4. In the AllowAdditions property box, click No.

  5. In the AllowDeletions property box, click No.


 Specify whether a user can add or delete a record with a form

Specify whether a user can add or delete a record with a form

  1. Open the form in Design view.

  2. Double-click the form selector to open the form's property sheet.

  3. In the AllowDeletions and/or the AllowAdditions property boxes, click Yes or No.


 Specify whether a user can edit saved records with a form

Specify whether a user can edit saved records with a form

  1. Open the form in Design view.

  2. Double-click the form selector to open the form's property sheet.

  3. In the AllowEdits property box, click Yes or No.


Create a pop-up form or custom dialog box

What do you want to do?

Create a modeless pop-up form

Create a custom dialog box

Temporarily open a form as a dialog box

Read about properties that you can use to customize a pop-up form or custom dialog box

Not sure which choice you want?


 Properties for creating or customizing pop-up forms and custom dialog boxes

Properties for creating or customizing pop-up forms and custom dialog boxes

The following table lists properties you can use to create or customize pop-up forms and custom dialog boxes. For more information on any of these properties, click the property in the property sheet and press F1.

This property | Determines
PopUp | Whether a form opens as a pop-up form. A pop-up form always remains on top of other Microsoft Access windows.
Modal | Whether a form opens as a modeless form (you can switch to other windows) or a modal form (the form retains the focus until it's closed).
BorderStyle | The type of border and border elements (title bar, Close button [image] , Control menu, Maximize and Minimize buttons) to use for the form. It also determines whether the form is sizable.
ControlBox | Whether a form has a Control menu in Form view.
MinMaxButtons | Whether a form has Minimize and Maximize buttons in Form view. If you set the BorderStyle property to Dialog, Microsoft Access automatically removes the Minimize and Maximize buttons.
CloseButton | Whether the Close button is disabled.
ScrollBars | Whether a form has scroll bars.
NavigationButtons | Whether a form has navigation buttons.
RecordSelectors | Whether a form has record selectors.
ShortcutMenu | Whether a shortcut menu is displayed when you right-click a form.
AutoCenter | Whether a form is centered automatically in the application window when the form is opened.
AllowEdits | Whether a user can make any editing changes to saved records in a form.
AllowDeletions | Whether a user can delete records using a form.
AllowAdditions | Whether a user can add records using a form.
DataEntry | Whether a form shows all records or a blank (new) record when it opens.
DefaultView | Whether a form is displayed in Datasheet view, as a single form (one record), or as a continuous form (multiple records).
ViewsAllowed | Whether you can switch between Form view and Datasheet view.


 Use a form to enter report criteria

Use a form to enter report criteria

Create an unbound form that prompts for report criteria

  1. Create an unbound form.

  2. In Design view, set the following form properties.
    Property | Setting
    Caption | Name you want to appear in the title bar of the form
    DefaultView | Single Form
    ViewsAllowed | Form
    ScrollBars | Neither
    RecordSelectors | No
    NavigationButtons | No
    BorderStyle | Dialog
  3. Add an unbound text box for each criteria you want to enter.

  4. Set the properties for the text boxes as follows.
    Property | Setting
    Name | Name that describes the type of criteria; for example, BeginningDate.
    Format | Format that reflects the data type of the criteria. For example, for a date criteria, select a format such as Medium Date.
  5. Save the form and give it a name, such as Sales Dialog.

    You'll add OK and Cancel command buttons to the form after you create macros for them.

Create the macros for the form in a macro group

  1. In the Database window, click Macros [image] , and then click the New button on the Database window toolbar.

    For this procedure, you'll create four macros in a macro group.

  2. Create a macro that opens the unbound form. Begin by clicking Macro Names [image] to display the Macro Name column. Type a macro name, such as Open Dialog, in the Macro Name column, and then click the OpenForm action. Then set the action arguments as follows.
    Argument | Setting
    Form Name | Name of the unbound form; for example, Sales Dialog
    View | Form
    Data Mode | Edit
    Window Mode | Dialog

    Add a second action, CancelEvent, that cancels previewing or printing the report when the Cancel button on the form is clicked. Then click Conditions [image] to display the Condition column, and type the following expression in the Condition column:

    Not IsLoaded("Sales Dialog")

    IsLoaded is a function defined in the Utility Functions module in the Northwind sample database. It's used to check whether a form is open in Form view or Datasheet view. You must define the IsLoaded function in your database before you can use it. (You can copy and paste this function into a utility module in your database.) For information on defining a function, click [image] . For information about opening Northwind, click [image] .

  3. Create a macro that closes the form. Give the macro a name, such as Close Dialog. Click the Close action. Then set its action arguments as follows.
    Argument | Setting
    Object Type | Form
    Object Name | Name of the unbound form
    Save | No
  4. Create a macro for the OK button. This macro hides the form. Give the macro a name, such as OK, and click the SetValue action. Then set its action arguments as follows.
    Argument | Setting
    Item | [Visible]
    Expression | No
  5. Create a macro for the Cancel button. This macro closes the form. Give the macro a name, such as Cancel, and click the Close action. Then set its action arguments as follows.
    Argument | Setting
    Object Type | Form
    Object Name | Name of the unbound form
    Save | No
  6. Save and close the macro group. Give the macro group a name — for example, the same name that you gave the unbound form.

Add OK and Cancel command buttons to the form

  1. Reopen the unbound form in Design view.

  2. Create an OK command button, and set its properties as follows. (Make sure Control Wizards [image] in the toolbox isn't pressed in.)
    Property | Setting
    Name | OK
    Caption | OK
    Default | Yes
    OnClick | Name of the macro; for example, Sales Dialog.OK
  3. Create a Cancel command button, and set its properties as follows.
    Property | Setting
    Name | Cancel
    Caption | Cancel
    OnClick | Name of the macro; for example, Sales Dialog.Cancel
  4. Save and close the form.

Enter the criteria in the underlying query or stored procedure for the report

  1. Open the underlying query or stored procedure for the report in Design view.

  2. Enter the criteria for the data. In the expression, use the Forms object, the name of the form, and the names of the controls in the criteria.
    • For example, in a Microsoft Access database (.mdb), for a form called Sales Dialog, you would use the following expression to refer to controls named Beginning Date and Ending Date in the query:

      Between [Forms]![Sales Dialog]![Beginning Date] And [Forms]![Sales Dialog]![Ending Date]

    • In a Microsoft Access project (.adp), you must first explicitly name the parameters in the stored procedure; for example:

      @Beginning_Date datetime, @Ending_Date datetime

      and then use those parameters in the WHERE clause; for example:

      WHERE Sales.ShippedDate Between @Beginning_Date And @Ending_Date

      In an Access project, you set the reference to the controls on the form in the InputParameters property in the report, as shown in the next procedure.

Set the InputParameters property in the main report (Access project only)

  1. Open the report in Design view.

  2. Set the report's InputParameters property to a string that specifies the parameters that are passed to the stored procedure that the report is bound to. As in the following example, the string must be an expression that includes the parameters you specified in the stored procedure and the reference to the controls on the dialog box:

    @Beginning_date datetime = [Forms]![Sales Dialog]![Beginning Date], @Ending_date datetime = [Forms]![Sales Dialog]![Ending Date]

Attach the macros to the main report

  1. Open the report in Design view.

  2. Set the following report properties.
    Property | Setting
    OnOpen | Name of the macro that opens the unbound form; for example, Sales Dialog.Open Dialog
    OnClose | Name of the macro that closes the unbound form; for example, Sales Dialog.Close Dialog


Reports: What they are and how they work

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


 Open a report

Open a report

  1. In the Database window, click Reports [image] under Objects.

  2. Click the report you want to open.

  3. On the Database window toolbar, click the Design button to open the report in Design view, or click the Preview button to open the report in Print Preview.

Tip You can also open a report in Print Preview by dragging the report from the Database window to the application background.


Create a report

What do you want to do?

Create a report by using AutoReport. With AutoReport, you select one record source and either columnar or tabular layout; AutoReport uses all the fields from the record source and applies the last autoformat you used to the report.

Create a report with a wizard. The wizard asks you detailed questions about the record sources, fields, layout, and format you want and creates a report based on your answers.

Create a report on my own


 Switch between views of a report

Switch between views of a report

Reports have three views: Design view, Print Preview, and Layout Preview. You use Design view to create a report or change the structure of an existing report. You use Print Preview to view the report's data as it will appear on every page. You use Layout Preview to view the report's layout, which includes just a sample of the data in the report.

  1. Open the report in any view.

  2. Click the View button on the toolbar to change to the view indicated by the graphic. To see a list of other views to choose from, click the arrow next to the button.


Ways to customize a report

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


Sections of a report

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


 Form and report templates

Form and report templates

When you create a form or report without using a wizard, Microsoft Access uses a template to define the default characteristics of the form or report.

The template determines which sections a form or report will have and defines each section's dimensions. The template also contains all the default property settings for the form or report and its sections and controls.

The default templates for forms and reports are called Normal. However, you can use any existing form or report as a template. You can also create a form or report to use only as a template. For information on specifying a new template, click [image] .

Notes

  • Changing the template doesn't have any effect on existing forms or reports.

  • A template doesn't create controls on a new form or report.

  • Microsoft Access saves the settings for the Form Template and Report Template options in your Microsoft Access workgroup information file, not in your Microsoft Access database (the .mdb file) or Microsoft Access project (the .adp file). When you change an option setting, the change applies to any database or Access project you open or create. To see the name of the template that is currently used for new forms or reports, click Options on the Tools menu, and then click the Forms/Reports tab.

  • To use your templates in other databases or Access projects, copy or export the templates to them. If your templates are not in a database or Access project, Microsoft Access uses the Normal template for any new forms and reports you create. However, the names of your templates appear in the Form Template and Report Template options in every database or Access project in your database system, even if the templates are not in every database or Access project.


Specify a new template for forms and reports

  1. On the Tools menu, click Options.

  2. Click the Forms/Reports tab.

  3. Type the name of the new template in the Form Template or Report Template box.

    Note You can use an existing form or report as a template, or you can create a form or report specifically for use as a template.

  4. Click OK.

    For more information about templates, click [image] .


Set margins, page orientation, and other page setup options

What do you want to do?

Set page setup options for a table, query, form, or report

Set page setup options for a data access page


Preview a report

Previewing a report shows you how it will look on the printed page. You can take a quick look at the layout, which includes just a sample of the data in the report. Or you can verify the data by reviewing every page in the report.

What do you want to do?

Preview just the report's layout

Preview all the data in the report page by page


 Print a report

Print a report

Before you print a report for the first time, you might want to check the margins, page orientation, and other page setup options. For more information, click [image] .

  1. Select the report in the Database window, or open the report in Design view, Print Preview, or Layout Preview.

  2. On the File menu, click Print.

  3. Enter the settings you want in the Print dialog box.
    • Under Printer, specify a printer.

    • Under Print Range, specify all pages or a range of pages.

    • Under Copies, specify the number of copies and whether they should be collated.
  4. Click OK.

Tip To print a report without bringing up the dialog box, click Print [image] on the toolbar.


 Preview a table, form, or report at different magnifications

Preview a table, form, or report at different magnifications

  • On the Print Preview toolbar, click the arrow next to the Zoom box, and then click a magnification percentage or type the percentage of magnification you want.

Notes

  • When you choose Fit, Microsoft Access adjusts the magnification of the page to best fit in the size of the window.

  • You can switch between the magnification you selected and Fit by placing the pointer on the table, form, or report, and then clicking when the pointer turns into a magnifying glass.

  • You can use the navigation buttons at the bottom of the Print Preview window to move between pages. You can move around the current page using the scroll bars, or, if you have a Microsoft IntelliMouse, using the wheel button.


 Preview two or more pages at a time

Preview two or more pages at a time

To view two pages

  1. Open the table, query, form, report, or module in Print Preview.

  2. Click Two Pages [image] on the toolbar.

To view more than two pages

  1. Open the table, query, form, report, or module in Print Preview.

  2. Click Multiple Pages [image] on the toolbar.

  3. Drag to select the number of pages to display.

To view one page again

  1. Open the table, query, form, report, or module in Print Preview.

  2. Click One Page [image] on the toolbar.

Note You can use the navigation buttons at the bottom of the Print Preview window to move between pages. You can move around the current page using the scroll bars, or, if you have a Microsoft IntelliMouse, using the wheel button.


 Print each record, group, or section on a separate page on a form or report

Print each record, group, or section on a separate page on a form or report

  1. Open the form in Design view or the report in Design view.

  2. Double-click the section selector to open the property sheet.

  3. Set the ForceNewPage property of the section to one of the following settings:
    • None. (Default) Prints the section on the current page.

    • Before Section. Prints the section at the top of a new page.

    • After Section. Prints the following section at the top of a new page.

    • Before & After. Prints the section at the top of a new page, and prints the following section at the top of a new page.

Notes

  • The ForceNewPage property is available for all sections except page headers and footers.

  • To print each record on a separate page, set the ForceNewPage property of the detail section to After Section. To print each group on a separate page, set the ForceNewPage property of the group header to Before Section or the ForceNewPage property of the group footer to After Section.


 Format a form, report, or control by using predefined formats

Format a form, report, or control by using predefined formats

  1. Open a form in Design view or a report in Design view.

  2. Do one of the following:
    • If you want to format the entire form or report, click the form selector or the report selector.

    • If you want to format an individual section, click the section selector.

    • If you want to format one or more controls, select the controls.
  3. Click AutoFormat [image] on the toolbar.

  4. Click one of the formats in the list.

  5. If you want to specify which attributes to apply (font, color, or border), click Options.

Note You must select the entire form or report to apply a background picture.


 Customize an autoformat for a form or report

Customize an autoformat for a form or report

  1. Open an existing form in Design view or report in Design view.

  2. On the Format menu, click AutoFormat.

  3. In the AutoFormat dialog box, click an autoformat in the list.

  4. Click the Options button, and then make sure the attributes you want to modify are selected.

  5. Click the Customize button, and then click a customization option. You can do one of the following:
    • Create a new autoformat based on the open form or report.

    • Update the selected autoformat based on the open form or report.

    • Delete the selected autoformat from the list.
  6. Click OK twice to close the dialog boxes.


 Add a background picture to a report

Add a background picture to a report

By adding a background picture to a report, you can simulate a watermark. A background picture in a report applies to the entire page.

  1. Open the report in Design view.

  2. Double-click the report selector to open the property sheet.

  3. Set the Picture property to a .bmp, .ico, .wmf, .dib, or .emf file. If you've installed graphics filters for other applications, you can use any file supported by those filters. If you're not sure of the path or file name, click the Build button [image] .

  4. In the PictureType property box, specify whether you want the picture to be embedded or linked. When you embed a picture, it's stored in the database file. If you embed the same picture in another form or report, it's added to the database file again. When you link a picture, you don't store it in the database file, but you must keep a copy of it on your hard disk. If you want to use your hard disk space efficiently, specify the Linked setting.

  5. You can determine the proportions of the picture by setting the PictureSizeMode property. This property has three settings:
    • Clip. Displays the picture at actual size. If the picture is larger than the area within the margins, the image is cut off.

    • Stretch. Sizes the picture to fit the area within the margins. This setting may distort the image.

    • Zoom. Sizes the picture to fill either the height or width of the area within the margins. This setting won't clip the picture or distort its proportions.
  6. You can specify the position of the picture on the page by setting the PictureAlignment property. Microsoft Access aligns the picture within the margins of the report. The available settings are Top Left, Top Right, Center, Bottom Left, and Bottom Right.

  7. You can repeat the picture across the page by setting the PictureTiling property to Yes. Tiling starts at the position specified in the PictureAlignment property.

    Note Background pictures look best tiled when the PictureSizeMode property is set to Clip.

  8. You can determine which pages of the report the picture will appear on by setting the PicturePages property. The available settings are All Pages, First Page, and No Pages.

Notes

  • If the colors in the background picture don't look the same as the original colors, you can specify that Microsoft Access use the colors from the application you used to create the graphic.

  • How?

  • If you're creating your own background pictures and you have access to a graphics program that creates metafiles, you may want to use a metafile as a background picture rather than a bitmap. For more information, click [image] .

  • The Employee Sales by Country report in the Northwind sample database has an example of a background picture. To view this report, open the Northwind database in your Office folder's Samples folder, and then open the Employee Sales by Country report in Design view. For information on opening Northwind, click [image] .


 Add a page break to a report

Add a page break to a report

In reports, you use a page break control to mark where you want to start a new page within a section. For example, if you want a report's title page and introductory message printed on separate pages, place a page break in the report header after the controls that you want to appear on the title page and before the controls for the second page.

  1. Open the report in Design view.

  2. Click the Page Break tool [image] in the toolbox.

  3. Click the report where you want to place the page break. Place the page break above or below a control to avoid splitting data in that control.

    Microsoft Access marks the page break with a short dotted line on the left edge of the report.

    If you want each group or record in a report to start on a new page, set the ForceNewPage property of the group header, group footer, or detail section.

    How?

Note The Catalog report in the Northwind sample database has an example of using a page break in the report header. To view this report, open the Northwind database in your Office folder's Samples folder, and then open the Catalog report in Design view. For information on opening Northwind, click [image] .


 Add page numbers to a form or report

Add page numbers to a form or report

  1. Open the form in Design view or the report in Design view.

  2. Click Page Numbers on the Insert menu.

  3. In the Page Numbers dialog box, select the format, position, and alignment for the page number. For alignment, the following options are available:
    • Left. Adds a text box at the left margin.

    • Center. Adds a text box centered between the left and right margins.

    • Right. Adds a text box at the right margin.

    • Inside. Adds text boxes at the left and right margins. Odd page numbers print on the left, and even page numbers print on the right.

    • Outside. Adds text boxes at the left and right margins. Even page numbers print on the left and odd page numbers print on the right.
  4. To show a number on the first page, select the Show Number On First Page check box.

Microsoft Access uses an expression to create the page numbers. For examples of other page number expressions, click [image] .


 Add the current date and time to a form or report

Add the current date and time to a form or report

  1. Open the form in Design view or the report in Design view.

  2. Click Date And Time on the Insert menu.

  3. To include a date, select the Include Date check box, and then click a date format.

  4. To include the time, select the Include Time check box, and then click a time format.

Microsoft Access adds a text box to the form or report and sets its ControlSource property to an expression. If there is a form or report header, Microsoft Access adds the text box to that section. Otherwise, it adds the text box to the detail section.


 Examples of expressions for page numbers

Examples of expressions for page numbers

The following table lists examples of page number expressions you can use in form or report Design view and the results that you see in other views.

Expression | Result
=[Page] | 1, 2, 3
="Page " & [Page] | Page 1, Page 2, Page 3
="Page " & [Page] & " of " & [Pages] | Page 1 of 3, Page 2 of 3, Page 3 of 3
=[Page] & " of " & [Pages] & " Pages" | 1 of 3 Pages, 2 of 3 Pages, 3 of 3 Pages
=[Page] & "/"& [Pages] & " Pages" | 1/3 Pages, 2/3 Pages, 3/3 Pages
=[Country] & " - " & [Page] | UK - 1, UK - 2, UK - 3
=Format([Page], "000") | 001, 002, 003


 Add or remove a report header and footer or a page header and footer

Add or remove a report header and footer or a page header and footer

  1. Open the report in Design view.

  2. Click Report Header/Footer or Page Header/Footer on the View menu.

Notes

  • You can add a header and footer only as a pair. If you don't want both a header and a footer, set the Visible property to No for the section you don't want. Or remove all controls from the section, and then size the section to zero height or set its Height property to 0.

  • If you remove a header and footer, Microsoft Access also removes the controls in the header and footer.

  • See an example of using different types of sections in reports.


 Omit the page header or footer on pages with the report header or footer

Omit the page header or footer on pages with the report header or footer

  1. Open the report in Design view.

  2. Double-click the report selector to open the property sheet.

  3. Set the PageHeader or PageFooter property to one of the following settings:
    • All Pages. (Default) Prints the page header or footer on all pages.

    • Not With Rpt Hdr. Doesn't print the page header or footer on the page that has the report header.

    • Not With Rpt Ftr. Doesn't print the page header or footer on the page that has the report footer.

    • Not With Rpt Hdr/Ftr. Doesn't print the page header or footer on a page that has either a report header or footer.

Note When you set the PageHeader property to Not With Rpt Ftr or Not With Rpt Hdr/Ftr, Microsoft Access prints the report footer on a new page.


 Change the size of a header, footer, or other section on a form or report

Change the size of a header, footer, or other section on a form or report

You can increase or decrease the height of form and report sections individually. However, a form or report has only one width. When you change the width of one section, you change the width of the entire form or report.

Change either height or width

  1. Open the form in Design view or the report in Design view.

  2. Change either the height or width by placing the pointer on the bottom edge or right edge of the section.

  3. Drag the pointer up or down to change the height of the section. Drag the pointer left or right to change the width of the section.

Change height of section

Change width of section

Change both height and width

  • Place the pointer in the lower-right corner of the section and drag it diagonally in any direction.

Change height and width of section


 Keep data in a record together on a page or in a column on a form or report

Keep data in a record together on a page or in a column on a form or report

  1. Open the form in Design view or the report in Design view.

  2. Double-click the section selector to open the property sheet.

  3. Set the KeepTogether property to 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. If the section is longer than the print area on the page, the KeepTogether property setting is ignored.

    The KeepTogether property is available for all sections except page headers and footers.

Tip If you want to keep the data in a group together — for example, the group header, detail records, and group footer — set the KeepTogether property for the group.

How?


 Create mailing and other types of labels

Create mailing and other types of labels

  1. In the Database window, click Reports [image] .

  2. Click the New button on the Database window toolbar.

  3. In the New Report dialog box, click Label Wizard.

  4. Click the table or query that contains the data for the labels, and then click OK.

  5. Follow the directions in the wizard dialog boxes.

    If the resulting label report doesn't look the way you want, you can delete the report and run the Label Wizard again.

Notes

  • For information on creating labels for a dot-matrix printer, click [image] .

  • The Customer Labels report in the Northwind sample database shows three-across mailing labels. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Customer Labels report in Design view. For information on opening Northwind, click [image] .


 Create mailing and other types of labels for a dot-matrix printer

Create mailing and other types of labels for a dot-matrix printer

Creating labels that print on a dot-matrix or tractor-feed printer usually requires some adjustment to the user-defined page size. Before you create a label report for this type of printer, you must first set the default printer and paper size in Microsoft Windows Control Panel.

Set the default printer and paper size

  1. Click the Windows Start button, point to Settings, and then click Control Panel.

  2. Double-click Printers, click the icon for the dot-matrix printer, and then click Set As Default on the File menu.

  3. On the File menu, click Properties, and then click the Paper tab.

  4. Under Paper Size, click the Custom icon.

  5. In the User Defined Size dialog box, select the unit of measurement, and then type the width and the length of a label.

    To determine the width, measure from the left edge of the leftmost label to the right edge of the rightmost label. To determine the length, measure from the top of the first label to the top of the second. For example, if you use two-across labels that measure 3-by-5 inches, with 0.25 inch between them, set Unit to 0.01 inch, and set Width to 625 and Length to 525.

  6. Click OK to save the settings in the User Defined Size dialog box.

  7. Click OK to save the settings in the printer's Properties dialog box.

Once you set the printer and paper size, you can create a label report for a dot-matrix printer with the Label Wizard or without a wizard in report Design view. For information on using the Label Wizard, click [image] .

Create a label report without a wizard

  1. Create a blank report bound to the table or query that contains the data you want to use.

    How?

  2. In report Design view, click Page Header/Footer on the View menu to remove the page header and footer. (You need only the detail section for this report.)

  3. Adjust the height and width of the detail section to match the height and width of one label.

    How?

  4. Add text boxes to the detail section, making sure that they don't overlap. (To create margins for the labels, place the text boxes at least 0.2 inch from all edges of the detail section.)

    How?

  5. On the File menu, click Page Setup.

  6. Set the following values in the Page Setup dialog box:
    • On the Page tab, if the dot-matrix printer isn't the default printer, click Use Specific Printer. Then click the Printer button, and click the dot-matrix printer in the list.

    • On the Page tab, under Paper, set Size to User-Defined Size, and set Source to Tractor.

    • On the Margins tab, set all the margins to 0.0 inches.

    • On the Columns tab, under Column Size, select the Same As Detail check box.

      If there is more than one label across the page, you must also set the following items under Grid Setting on the Columns tab:

    • In the Number Of Columns box, type the number of labels across.

    • In the Row Spacing box, type the amount of space between the bottom of one label and the top of the next.

    • In the Column Spacing box, type the amount of space between the right edge of one label and the left edge of the next.

Note When a dot-matrix printer is the default in Microsoft Windows Control Panel and you have Paper Size set to User-Defined Size, Microsoft Access uses that paper size. If you want to create or print a label or report on a page of a different size, change the user-defined page size in Microsoft Windows Control Panel before you create or print it.


Customize labels created with the Label Wizard

What do you want to do?

If you want to make major changes to the labels, it's better to create a new label report with the Label Wizard.

If you want to make minor adjustments to the labels, you can:

Change the font of the text in the controls

Change the font size of the text in the controls

Change the size of controls

Add controls

Modify the page setup options


Example of grouped records in a report

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


 Sort records in a report

Sort records in a report

You can sort on up to 10 fields or expressions in a report.

  1. Open the report in Design view.

  2. Click Sorting And Grouping [image] on the toolbar to display the Sorting And Grouping box.

  3. In the first row of the Field/Expression column, select a field name, or type an expression.

    The field or expression in the first row is the first sorting level (the largest set). The second row is the second sorting level, and so on.

    When you fill in the Field/Expression column, Microsoft Access sets the Sort Order to Ascending. Ascending order sorts from A to Z or 0 to 9.

  4. To change the sort order, select Descending from the Sort Order list. Descending order sorts from Z to A or 9 to 0.

Note The Customer Labels report in the Northwind sample database sorts records by the values in three fields. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Customer Labels report in Design view. For information on opening Northwind, click [image] .


 Group records in a report

Group records in a report

You can group on up to 10 fields or expressions in a report. To see an example of grouped records, click [image] .

  1. Open the report in Design view.

  2. Click Sorting And Grouping [image] on the toolbar to display the Sorting And Grouping box.

  3. Set the sort order for the data in the report.

    How?

  4. Click the field or expression whose group properties you want to set.

  5. Set the group properties in the following list. You must set either GroupHeader or GroupFooter to Yes in order to create a group level and set the other grouping properties.
    • GroupHeader. Adds or removes a group header for the field or expression.

    • GroupFooter. Adds or removes a group footer for the field or expression.

    • GroupOn. Specifies how you want the values grouped. The options you see depend on the data type of the field on which you're grouping. If you group on an expression, you see all the options for all data types.

    • GroupInterval. Specifies any interval that is valid for the values in the field or expression you're grouping on.

    • KeepTogether. Specifies whether Microsoft Access prints all or only part of a group on the same page.

More information

For information on grouping on Text fields, click [image] .

For information on grouping on Date/Time fields, click [image] .

For information on grouping on AutoNumber, Currency, or Number fields, click [image] .

Note The Employee Sales by Country report in the Northwind sample database has two group levels. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Employee Sales by Country report in Design view. For information on opening Northwind, click [image] .


 Change sorting and grouping order in a report

Change sorting and grouping order in a report

  1. Open the report in Design view.

  2. Click Sorting And Grouping [image] on the toolbar to display the Sorting And Grouping box.

  3. In the Sorting And Grouping box, click the row selector of the field or expression you want to move.

  4. Click the selector again, and drag the row to a new location in the list.

If the groups you're rearranging have headers or footers, Microsoft Access moves the headers, footers, and all the controls in them to their new positions. However, you must adjust the locations of the controls in the headers and footers yourself.


 Insert an additional sorting or grouping field or expression in a report

Insert an additional sorting or grouping field or expression in a report

  1. Open the report in Design view.

  2. Click Sorting And Grouping [image] on the toolbar to display the Sorting And Grouping box.

  3. In the Sorting And Grouping box, click the selector of the row where you want to insert the new field or expression, and then press INSERT.

  4. In the Field/Expression column of the blank row, select the field you want to sort on, or type an expression.

    When you fill in the Field/Expression column, Microsoft Access sets the Sort Order to Ascending.

  5. To change the sort order, select Descending from the Sort Order list.


 Delete a sorting or grouping field or expression in a report

Delete a sorting or grouping field or expression in a report

  1. Open the report in Design view.

  2. Click Sorting And Grouping [image] on the toolbar to display the Sorting And Grouping box.

  3. In the Sorting And Grouping box, click the row selector of the field or expression you want to delete, and then press DELETE.

  4. Click Yes to delete the sorting or grouping level, or click No to keep it.

Note If the field or expression you delete has a header or footer, Microsoft Access deletes the header or footer and its controls.


 Keep the data in a group together on a page or in a column in a report

Keep the data in a group together on a page or in a column in a report

  1. Open the report in Design view.

  2. Click Sorting And Grouping [image] on the toolbar to display the Sorting And Grouping box.

  3. Set the group levels for the report.

    How?

  4. Click the field or expression for the group level that you want to keep together.

  5. In the group properties section of the Sorting And Grouping box, set the KeepTogether property to one of the following settings:
    • Whole Group. The group header, all detail records, and the group footer are printed on the same page or in the same column.

    • With First Detail. The group header is printed on a page or in a column only if it can also print the first detail record.
  6. Display the property sheet for the report.

    How?

  7. Set the GrpKeepTogether property to one of the following settings:
    • Per Page. Keeps the group together on the page.

    • Per Column/Row. Keeps the group together in the column or row.

Notes

  • If you want to keep the data in one section together, for example, a record in the detail section, set the KeepTogether property for that section to Yes.

    How?

  • The Alphabetical List of Products report in the Northwind sample database keeps the products for each letter together as a group. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Alphabetical List of Products report in Design view. For information on opening Northwind, click [image] .


 Start each group in a report in a new row or column

Start each group in a report in a new row or column

  1. Create a multiple-column report that has at least one group level.

    For information on creating a multiple-column report, click [image] . For information on creating group levels, click [image] .

  2. In report Design view, click Page Setup on the File menu.

  3. Click the Columns tab. Under Grid Settings, make sure Number of Columns is set to a value greater than 1.

  4. Under Column Layout, do one of the following:
    • To start each group in a new column, click the Down, Then Across option.

    • To start each group in a new row, click the Across, Then Down option.
  5. Click OK.

  6. Double-click the section selector for the group header or footer to display its property sheet.

  7. Set the NewRowOrCol property to one of the following settings.
    Setting | Description
    None | (Default) The row or column breaks are determined by the setting in the Page Setup dialog box and by the available space on the page.
    Before Section | Microsoft Access starts printing the current section (the section for which you're setting the property, such as the group header) in a new row or column. It starts printing the next section, for example, the detail section, in the same row or column.
    After Section | Microsoft Access starts printing the current section, such as the group header, in the current row or column. It starts printing the next section, such as a detail section, in the next row or column.
    Before & After | Microsoft Access starts printing the current section, such as the group header, in a new row or column. It starts printing the next section, such as the detail section, in the next row or column.

Notes

  • To see an example of a report that starts each group in a new column and an example that starts each group in a new row, click [image] .

  • The Products by Category report in the Northwind sample database starts each group in a new column. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Products by Category report in Design view. For information on opening Northwind, click [image] .


 Reset page numbers for each group in a report

Reset page numbers for each group in a report

Create a macro that resets page numbers

  1. Create a macro that uses the SetValue action to change the Page property to 1.

    How?

    Decide if the page number will appear in the page header or footer, and then use the following values for the SetValue action arguments.

    Location of page number SetValue arguments
    Page header Item: [Page]

    Expression: 0
    Page footer Item: [Page]

    Expression: 1
  2. Save and close the macro.

Modify the report

  1. Open the report in Design view.

  2. Create a text box for the page number in the page header or footer if you haven't already done so.

    How?

  3. For the first-level group header and footer, set the following properties, depending on where the page number appears.

    If the page number appears in the page header, set the following properties.

    Section | Property | Setting | Purpose
    Group header | ForceNewPage | Before Section | Starts each group on a new page.
    Group footer | OnFormat | Name of macro you created in the first procedure | Resets the page number to 1 for the new group.

    If the page number appears in the page footer, set the following properties.

    Section | Property | Setting | Purpose
    Group header | OnFormat | Name of macro you created in the first procedure | Resets the page number to 1 for the new group.
    Group footer | ForceNewPage | After Section | Starts each group on a new page.

Note The Employee Sales by Country report in the Northwind sample database uses an event procedure in the OnFormat property to reset the page number for each country. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Employee Sales by Country report in Design view. For information on opening Northwind, click [image] .


 Repeat a group header on another page or column

Repeat a group header on another page or column

  1. Open the report in Design view.

  2. Display the property sheet for the group header you want to repeat by double-clicking its section selector.

  3. Set the RepeatSection property to Yes.


 Hide duplicate data in a report

Hide duplicate data in a report

You can hide duplicate data on a report with sorted records or on a report with grouped records.

Hide duplicate data on a report with only sorted records

  1. Create a report that sorts records on one or more fields that might contain duplicate values.

    How?

  2. In report Design view, place the text boxes for all the fields in the detail section.

  3. To display the property sheet for a text box that contains data that might repeat, make sure the text box is selected, and then click Properties [image] on the toolbar.

  4. Set the HideDuplicates property to Yes.

    Note In any text boxes for which HideDuplicates is set to Yes, Microsoft Access prints a value in the first record in which that value occurs and, if records with the duplicate value continue onto another page, at the top of a new page.

Hide duplicate data on a report with grouped records

  1. Create a report with one or more group levels.

    How?

  2. In report Design view, move the text box for the field you're grouping on from the group header to the detail section.

  3. To display the text box's property sheet, make sure the text box is selected, and then click Properties [image] on the toolbar.

  4. Set the HideDuplicates property to Yes.

  5. Remove lines and all other controls from the group header.

  6. Double-click the section selector of the group header to display its property sheet.

  7. Set the Height property of the group header to 0.

    Note The group name will appear only at the beginning of a new group or at the top of a new page if the group continues for more than one page.


 Calculate a total for one record in a report

Calculate a total for one record in a report

  1. Open the report in Design view.

  2. Add a calculated text box to the detail section.

    How?

  3. To display the property sheet, make sure the text box is selected, and then click Properties [image] on the toolbar.

  4. In the ControlSource property box, type an appropriate expression.

    Expression in a text box in the detail section of a report

    Tip In a Microsoft Access database (.mdb), you can click the Build button [image] to use the Expression Builder to create the expression.

Notes

  • If a report is based on a query, you can put the expression in the report's underlying query. It may improve the report's performance, and if you are going to calculate totals for groups of records, it's easier to use the name of a calculated field in an aggregate function. For more information, click [image] .

  • For examples of other expressions you can use to calculate values for one record, click [image] .

  • For more information about creating expressions in a Microsoft Access database (.mdb), click [image] .

  • For more information about creating expressions in a Microsoft Access project (.adp), click [image] .


 Calculate a total or average for a group of or all records in a report

Calculate a total or average for a group of or all records in a report

  1. Open the report in Design view.

  2. Add a calculated text box to one or more of the following sections:

    How?

    • To calculate a total or average for a group of records, add a text box to the group header or footer.

    • To calculate a grand total or average for all records in the report, add a text box to the report header or footer.
  3. To display the property sheet, make sure the text box is selected, and then click Properties [image] on the toolbar.

  4. In the ControlSource property box, type an expression that uses the Sum function to calculate a total or the Avg function to calculate an average.

    Controls that calculate totals in the group footer and report footer

    Tip In a Microsoft Access database (.mdb), you can click the Build button [image] to use the Expression Builder to create the expression.

Notes

  • For more information about creating expressions in a Microsoft Access database (.mdb), click [image] .

  • For more information about creating expression in a Microsoft Access project (.adp), click [image] .

  • For more information about calculating totals and averages using aggregate functions such as Sum and Avg, click [image] .

  • For examples of expressions that use aggregate functions, click [image] .

  • The Employee Sales by Country report in the Northwind sample database has an example of group totals and a grand total. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Employee Sales by Country report in Design view. For information about opening Northwind, click [image] .


 Calculate a running sum in a report

Calculate a running sum in a report

  1. Open the report in Design view.

  2. Add a text box to one or more of the following sections.

    How?

    • To calculate a running sum that increases for each record, add a bound text box or a calculated text box to the detail section.

    • To calculate a running sum that increases for each group of records, add a bound text box or a calculated text box to the group header or footer.
  3. To display the property sheet, make sure the text box is selected, and then click Properties [image] on the toolbar.

  4. Set the RunningSum property according to the type of running total you want:
    • Over Group. Resets to 0 at the beginning of each higher group level.

    • Over All. Accumulates until the end of the report.

Notes

  • To see an example of a report that calculates running sums, click [image] .

  • When you set the RunningSum property to Over All, you can repeat the grand total in the report footer. Create a text box in the report footer and set its ControlSource property to the name of the text box that calculates the running sum; for example, =[OrderAmount].


 Calculate percentages in a report

Calculate percentages in a report

  1. Open the report in Design view.

  2. Add the text boxes that calculate the record total, the group total, and the grand total.

    How?

  3. To the appropriate section, add the text box that calculates the percentage.

    To calculate what percentage of a group total or the grand total each item is, place the control in the detail section.

    To calculate what percentage of the grand total a group of items is, place the text box in the group header or footer.

    If your report includes multiple group levels, place the text box in the header or footer of the level for which you want Microsoft Access to calculate a percentage.

  4. To display the property sheet, make sure the text box is selected, and then click Properties [image] on the toolbar.

  5. In the ControlSource property box, type an expression that divides the smaller total by the larger total of which the smaller total is a part. For example, divide the value of the DailyTotal control by the value of the GrandTotal control.

    Tip In a Microsoft Access database (.mdb), you can click the Build button [image] to use the Expression Builder to create the expression.

  6. Set the Format property of the text box to Percent.

    Text boxes that calculate percentages shown in Design view

Notes

  • For more information about creating expressions in a Microsoft Access database (.mdb), click [image] .

  • For more information about creating expressions in a Microsoft Access project (.adp), click [image] .

  • The Employee Sales by Country report in the Northwind sample database has an example of percentages. To view this report, open the Northwind database in the Samples subfolder of the Office folder, and then open the Employee Sales by Country report in Design view. For information about opening Northwind, click [image] .


 About computing a total for a calculated control on a form or report

About computing a total for a calculated control on a form or report

When computing a total with an aggregate function such as Sum or a domain aggregate function such as DSum, you can't use the name of a calculated control in the Sum function. You must repeat the expression in the calculated control. For example:

=Sum([Quantity]*[UnitPrice])

However, if you have a calculated field in an underlying query, for example,

=ExtendedPrice: [Quantity]*[UnitPrice]

you can use the name of that field in the Sum function, as shown here:

=Sum([ExtendedPrice])

Notes

  • For information about creating a calculated field in a query in a Microsoft Access database (.mdb), click [image] .

  • For information about creating a calculated field in a query in a Microsoft Access project (.adp), click [image] .

  • For more information about the Sum function, click [image] .

  • For more information about the DSum function, click [image] .


Example of a report that calculates running sums

You can calculate running sums that accumulate within each group and are reset each time a new group of records begins. You can also calculate running sums that accumulate throughout the report.

In the following illustration, for the two fields on the right that are bound to the Subtotal field, the RunningSum property is set to Over Group and Over All, respectively.

Text boxes that calculate running sums shown in Design view

In the following printed report, you can see how Microsoft Access calculates the running sums.

Running sums shown in printed report


 Number each detail record in a report

Number each detail record in a report

  1. Open the report in Design view.

  2. Add a calculated text box to the detail section.

    How?

  3. To display the property sheet, make sure the text box is selected, and then click Properties [image] on the toolbar.

  4. Set the ControlSource property to =1.

  5. Set the RunningSum property to Over All.

    When you preview or print the report, each record number will be incremented by 1 (1, 2, 3...).

Note The Sales by Year report in the Northwind sample database has an example of numbered detail records. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Sales by Year report in Design view. For information about opening Northwind, click [image] .


 Count the number of records in a report as a whole

Count the number of records in a report as a whole

  1. Open the report in Design view.

  2. Add a calculated text box to the report header or footer.

    How?

  3. To display the property sheet, make sure the text box is selected, and then click Properties [image] on the toolbar.

  4. Set the ControlSource property of the text box to =Count(*). This expression uses the Count function to count all the records in the report even if some fields in some records are Null. For information about the Count function, click [image] .


 Count the number of records in each group in a report

Count the number of records in each group in a report

  1. Open the report in Design view.

  2. Add a calculated text box to the detail section.

    How?

  3. To display the property sheet, make sure the text box is selected, and then click Properties [image] on the toolbar.

  4. Set the following properties.
    Property | Setting
    Name | RecordCount
    ControlSource | =1
    RunningSum | Over Group
    Visible | No
  5. Add a calculated text box to the group footer.

  6. To display the property sheet, make sure the text box is selected, and then click Properties [image] on the toolbar.

  7. Set the ControlSource property to the name of the control in the detail section that's tracking the running total; for example, =[RecordCount].


 Combine text values from multiple fields on a form, report, or data access page

Combine text values from multiple fields on a form, report, or data access page

  1. Open the form in Design view, the report in Design view, or the data access page in Design view.

  2. Add a calculated text box for the fields that you want to combine.

    Tip On a data access page, you can use a bound HTML control instead.

  3. To display the property sheet, make sure the text box is selected, and then click Properties [image] on the toolbar.

  4. In the ControlSource property box, type an expression that concatenates the values from the appropriate fields.

    For example, to return an address like

    507 20th Ave. E., Seattle WA 98122

    type this expression:

    =[Address] & ", " & [City] & " " & [Region] & " " & [PostalCode]

    Tip In a form or report in a Microsoft Access database (.mdb), you can also click the Build button [image] to use the Expression Builder to create the expression.

Notes

  • For more information on creating expressions in a Microsoft Access database (.mdb), click [image] .

  • For more information on creating expression in a Microsoft Access project (.adp), click [image] .

  • For information on compensating for fields that might include Null values in some records, click [image] .

  • The Employee Sales by Country and Customer Labels reports in the Northwind sample database have examples of combining text values. To view one of these reports, open the Northwind database in the Samples subfolder of the Office folder, and then open that desired report in Design view. For information on opening Northwind, click [image] .


 About combining text values from fields when some fields contain no data

About combining text values from fields when some fields contain no data

When you combine text values from several fields, some records might contain empty fields, resulting in output that might not be what you want. For example, the output might include extra spaces.

To compensate for records that don't have values in certain fields, you can use the IIf function. You use the IIf function when you want the value (or absence of a value) in one field to determine which one of two possible results you want returned.

For example, if you know that not every record will have a value in the Region field, use the following expression:

=[Address] & ", " & [City] & IIf(IsNull([Region]),"", " " & [Region]) & " " & [PostalCode]

If the Region field is empty, Microsoft Access returns an empty string, as specified by the argument "". If the Region field contains a value, Microsoft Access returns a space and the region, as specified by the argument " " & [Region].

Notes

  • For more information of the Ilf function, click [image] .

  • The Invoice report in the Northwind sample database has an example of combining values from text fields by using the IIf function. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Invoice report in Design view. For information on opening Northwind, click [image] .


 Print the first few characters of a value as a group header in a report or data access page

Print the first few characters of a value as a group header in a report or data access page

  1. Open the report in Design view, or the data access page in Design view.

  2. Click Sorting And Grouping [image] on the toolbar, and make sure that the properties in the Sorting And Grouping box are set as follows:
    Property | Setting | Applies to
    Field/Expression | (Select a field or type an expression) | Reports
    GroupRecordSource | (Set when you click Promote or Group By Table on the toolbar) | Data access pages
    GroupHeader | Yes | Reports, pages
    GroupFooter | Yes or No | Reports, pages
    GroupOn | Prefix Characters | Reports, pages
    GroupInterval | (Type the number of characters) | Reports, pages
    KeepTogether | (Select an option) | Reports
    DefaultSort | (Type the name(s) of the field(s) you want to sort on.) | Data access pages
  3. Add a calculated text box to the group header.

    Note On a data access page, you can use a bound HTML control instead of a text box.

  4. To display the property sheet, make sure that the text box or bound HTML control is selected, and then click Properties [image] on the toolbar.

  5. In the ControlSource property box, type the expression (by using the Left or Right function) that will extract the appropriate characters.

    For example, if you're tracking office equipment and furniture, and the asset number includes an alphabetic code for distinguishing one type of asset from another (for example, FR100 for furniture), you could use an expression similar to the ones in the following table.

    This expression | Returns
    =Left([AssetCode], 2) | FR
    =Right([AssetCode], 3) | 100

    Tip In a form or report in a Microsoft Access database (.mdb), you can click the Build button [image] to use the Expression Builder to create the expression.

Notes

  • For more information on creating expressions in a Microsoft Access database (.mdb), click [image] .

  • For more information on creating expression in a Microsoft Access project (.adp), click [image] .

  • For more information on the Left function, click [image] .

  • For more information on the Right function, click [image] .

  • The Alphabetical List of Products report in the Northwind sample database has an example of printing the first letter of each group of products in the group header. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Alphabetical List of Products report in Design view. For information on opening Northwind, click [image] .


 Subreports: What they are and how they work

Subreports: What they are and how they work

A subreport is a report that's inserted in another report. When you combine reports, one of them must serve as the main report. A main report is either bound or unbound; that is, it is or isn't based on a table, query, or SQL statement.

Data from unrelated record sources in a main report with two subreports

An unbound main report can serve as a container for unrelated subreports that you want to combine.

Unbound main report with two subreports displaying unrelated data

Data from one record source in a main report and subreport

You bind the main report to an underlying table, query, or SQL statement when you want to insert subreports that contain information that's related to the data in the main report. For example, you can use the main report to show detail records, such as every sale in a year, and then use a subreport to show summary information, such as the total sales for each quarter.

Main report and subreport bound to the same record source

Data from related record sources in a main report and two subreports

A main report can also contain data common to two or more parallel subreports. In this case, the subreports contain the detail records related to the common data.

Main report with two subreports displaying related data

A main report can include subforms as well as subreports, and it can include as many subforms and subreports as you want. Additionally, a main report can contain up to two levels of subforms and subreports. For example, a report can contain a subreport, and that subreport can contain a subform or a subreport. The following table shows the possible combinations of subforms and subreports in a main report.

Level 1 | Level 2
Subreport 1 | Subreport 2
Subreport 1 | Subform 1
Subform 1 | Subform 2

Note The Sales by Category and Sales by Year reports in the Northwind sample database use subreports. To view these reports, open the Northwind database in the Samples subfolder of your Office folder, and then open the report in Design view. For information on opening Northwind, click [image] .


Create a subreport

How you create a subreport depends on whether you want to create a subreport in an existing report or add an existing report to another existing report to create a report and subreport.

What do you want to do?

Create a subreport in an existing report

Add an existing report to another existing report

Find out more about subreports


 How a main report and subreport are linked

How a main report and subreport are linked

When you insert a subreport that contains information related to data in the main report, the subreport control must be linked to the main report. The link ensures that the records printed in the subreport correspond correctly to the records printed in the main report.

When you create a subreport by using a wizard or by dragging a report or datasheet from the Database window to another report, Microsoft Access automatically synchronizes the main report and subreport if:

  • You have defined relationships for the tables you select, or you have defined relationships for the tables underlying the queries you select.

  • The main report is based on a table with a primary key and the subreport is based on a table that contains a field with the same name as that primary key and with the same or a compatible data type. For example, if the primary key of the table underlying the main form is an AutoNumber field and its FieldSize property is set to Long Integer, the corresponding field in the table underlying the subform should be a Number field with its FieldSize property set to Long Integer. If you select a query or queries, the underlying tables in the query or queries must meet the same conditions.

Note Microsoft Access uses the LinkMasterFields and LinkChildFields properties of the subreport control to link the main report and the subreport. If for some reason Access doesn't link the report and subreport, you can set these properties directly.

How?


 Link a main report and a subreport

Link a main report and a subreport

If you create a subreport with the Report Wizard or the Subreport Wizard, Microsoft Access automatically links the main report with the subreport under certain conditions. For more information, click [image] . If your main report and subreport don't meet these conditions, you can use this procedure to link them.

  1. Open the main report in Design view.

  2. To display the property sheet, make sure the subreport control is selected, and then click Properties [image] on the toolbar.

  3. Set the linking fields. To enter more than one linking field or control, separate the field or control names with a semicolon. If you enter more than one field or control, you must enter the names in the same order in the LinkChildFields and LinkMasterFields properties.
    • In the LinkChildFields property box, enter the name(s) of the linking field(s) in the subreport.

    • In the LinkMasterFields property box, enter the name(s) of the linking field(s) or control(s) in the main report.

    Note You can't use the name of a control in the LinkChildFields property box.

    If you're unsure what the linking field(s) should be, click the Build button [image] next to either property box to open the Subform/Subreport Field Linker.

Notes

  • The linking fields don't have to appear in the main report or the subreport, but they must be included in the underlying record source. If you use the Report Wizard to create the subreport, Microsoft Access automatically includes the linking fields in the underlying record source even if you don't select them in the wizard.

  • The linking fields must contain the same kind of data and have the same or a compatible data type or field size. For example, an AutoNumber field is compatible with a Number field whose FieldSize property is set to Long Integer.

  • For information on troubleshooting subreports, click [image] .


 Create a multiple-column report

Create a multiple-column report

  1. Create a report.

    How?

    Notes

    • When a multiple-column report is printed, the report header and footer and page header and footer span the full width of the report, so you can place controls anywhere in these sections in Design view.

    • When printed, the group header and footer and detail section of a multiple-column report span the width of one column. For example, if you want to print the data in two three-inch columns, place the controls within the width of one column; in other words, place the controls in the first three inches of these sections in Design view.
  2. On the File menu, click Page Setup.

  3. In the Page Setup dialog box, click the Columns tab.

  4. Under Grid Settings, in the Number Of Columns box, type the number of columns you want on each page.

  5. In the Row Spacing box, type the amount of vertical space you want between each record in the detail section.

    Note If you left space between the last control in the detail section and the bottom edge of the detail section, you can leave Row Spacing set to 0.

  6. In the Column Spacing box, type the amount of space you want between the columns.

  7. Under Column Size, type the width you want for a column in the Width box; for example, 3 inches. You can set the height of the detail section by typing a number in the Height box or by adjusting the height of the section in Design view.

  8. Under Column Layout, click the Down, Then Across option or the Across, Then Down option.

  9. Click the Page tab.

  10. Under Orientation, click Portrait or Landscape.

  11. Click OK.

Notes

  • For information on starting each group in a new row or column, click [image] .

  • The Products by Category report in the Northwind sample database displays data in multiple columns. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Products by Category report in Design view. For information on opening Northwind, click [image] .


 Create a crosstab report with fixed-column headings

Create a crosstab report with fixed-column headings

Create the underlying query

  1. Create a crosstab query.

    How?

  2. In query Design view, display the query's property sheet by double-clicking anywhere outside the design grid and outside the field lists.

  3. In the ColumnHeadings property box, type the column headings you want to appear in the report, separating each one with a semicolon. If a column heading contains spaces, enclose it in double (" ") quotation marks. For instance, in a query showing sales by quarter, you would type:

    "Qtr 1";"Qtr 2";"Qtr 3";"Qtr 4"

Create the report

  1. Create a blank report that is bound to the crosstab query.

    How?

  2. Add the controls for the fields you want to appear in the report.
    • Place labels for the row headings and column headings in the page header.

    • Place text boxes for the row headings and column values in the detail section.


 Cancel the printing of a report when it doesn't contain any records

Cancel the printing of a report when it doesn't contain any records

  1. Open the report in Design view.

  2. Double-click the report selector to display the report's property sheet.

  3. Set the OnNoData property to [Event Procedure] or to the name of a macro that cancels previewing or printing the report.
    • If you use a macro, use the MsgBox action to display a message that describes why there is no data for the report, and use the CancelEvent action to cancel printing or previewing the report. For information on creating a macro, click [image] .

    • If you use an event procedure, use the MsgBox statement to display a message, and set the Cancel argument of the Report_NoData Sub procedure to True. For information about customizing an event procedure, click [image] .

Note The Employee Sales by Country report in the Northwind sample database uses an event procedure in the OnNoData property. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Employee Sales by Country report in Design view. For information on opening Northwind, click [image] .


 Print the criteria for a report in the report header

Print the criteria for a report in the report header

  1. In a Microsoft Access database (.mdb), create the criteria parameters in the report's underlying query. In a Microsoft Access project (.adp), create the parameters in the report's underlying stored procedure.

  2. Open the report in Design view.

  3. Create an unbound text box for each parameter you want to display. Click the Text Box tool Text Box control in the toolbox, and then click in the report header.

  4. To display the property sheet, make sure the text box is selected, and then click Properties [image] on the toolbar.

  5. Do one of the following:
    • In an Access database, set the ControlSource property to the parameter(s) you specified in the Criteria cell in the query. For example, if the parameters in the query are:

      Between [Type a beginning date] And [Type an ending date]

      and you want to display them in two text boxes, set the ControlSource property of one text box to:

      [Type a beginning date]

      and the ControlSource property of the other text box to:

      [Type an ending date]

      If you want to display both parameters in one text box, you can use an expression in the ControlSource property box; for example:

      ="Between " & [Type a beginning date] & " and " & [Type an ending date]

    • In an Access project, set the report's InputParameters property to a string that specifies the parameters that are passed to the stored procedure that the report is bound to. As in the following example, the string must be an expression that includes the parameters you specified in the stored procedure and the text you want to appear in the prompt; enclose the prompt text in square brackets ([ ]):

      @Beginning_date datetime = [Beginning Date], @Ending_date datetime = [Ending Date]

      Then set the ControlSource property of the control to a string that specifies the parameters in the stored procedure, any text you want to include, and the prompt text enclosed in square brackets as shown in the following example:

      ="Sales from "& [Beginning Date] &" to "& [Ending Date]

  6. To see the criteria, print or preview the report. Microsoft Access displays the parameter values exactly as you typed them in the prompt.

Note The Employee Sales by Country report in the Northwind sample database prints the criteria in the report header. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Alphabetical List of Products report in Design view. For information on opening Northwind, click [image] .


Tips for optimizing report and subreport performance

There are several things you can do to make your reports print faster. In addition to the tips listed below, you can use the Performance Analyzer to analyze specific reports in your database. For information on using the Performance Analyzer, click [image] .

Performance tips

  • Avoid overlapping controls.

  • Use bitmaps and other graphic objects sparingly.

  • Convert unbound object frames that display graphics to image controls.

  • Use black-and-white rather than color bitmaps.

  • Avoid sorting and grouping on expressions.

  • Index fields you sort or group on.

  • Base subreports on queries rather than tables, and include only fields from the record source that are absolutely necessary. Extra fields can decrease subreport performance.

  • Index all the fields in the subreport that are linked to the main report.

  • Index any subreport fields used for criteria.

  • Avoid using domain aggregate functions. Include the field in the report's underlying query or use a subreport.

  • Make sure the report's underlying query is optimized.

  • Use the HasData property or NoData event to determine if a report is bound to an empty recordset.


 Data access pages: What they are and how they work

Data access pages: What they are and how they work

A data access page is a special type of Web page designed for viewing and working with data from an Internet or intranet — data that is stored in a Microsoft Access database or a Microsoft SQL Server database. The data access page may also include data from other sources, such as Microsoft Excel.

This topic provides reference information about:

Designing different types of data access pages

Using data access pages in Internet Explorer

Using data access pages in Microsoft Access

Designing different types of data access pages

You design data access pages in page Design view in Microsoft Access. The page is a separate file that is stored outside Microsoft Access; however, when you create the file, Microsoft Access automatically adds a shortcut to the file in the Database window. Designing a data access page is similar to designing forms and reports — you use a field list, the toolbox, controls, the Sorting and Grouping dialog box, and so on. However, there are some significant differences in the way that you design and interact with data access pages as opposed to forms and reports. How you design the page depends on what it will be used for:

  • Interactive reporting This type of data access page is often used to consolidate and group information that is stored in the database, and then publish summaries of the data. For example, a page might publish the sales performance for each region in which you do business. Using expand indicators, you can go from a general summary of the information, such as a list of all the regions and their combined sales total, to specific details on individual sales within each region. While the data access page may also provide toolbar buttons for sorting and filtering the data, you can't edit data on this type of page. See an example and learn more about data access pages that group records for interactive reporting.

  • Data entry This type of data access page is used to view, add, and edit records. Learn more about data access pages used for data entry.

  • Data analysis This type of data access page may include a PivotTable list, similar to a Microsoft Access PivotTable form or Microsoft Excel PivotTable report, that lets you reorganize the data to analyze it in different ways. The page might contain a chart that you can use to analyze trends, detect patterns, and compare data in your database. Or the page might contain a spreadsheet in which you can enter and edit data, and use formulas to calculate as you do in Microsoft Excel. See an example of a data access page used for data analysis.

Return to top

Using data access pages in Internet Explorer

A data access page is connected directly to a database. When users display the data access page in Microsoft Internet Explorer, they are viewing their own copy of the page. That means any filtering, sorting, and other changes they make to the way the data is displayed — including changes they make within a PivotTable list or spreadsheet — affect only their copy of the data access page. However, changes that they make to the data itself — such as modifying values, and adding or deleting data — are stored in the underlying database, and therefore are available to everyone viewing the data access page.

Users get Help on how to work with the page in Internet Explorer by clicking the Help [image] button on the record navigation toolbar. The Help file that displays is automatically included with any data access page that's published with a record navigation toolbar. If you delete the record navigation toolbar or if you disable the Help button on it, you should provide instructions for those who will use the page.

Note To view and work with the data access page on the Internet or an intranet, users need Microsoft Internet Explorer 5 and a Microsoft Office 2000 license.

Return to top

Using data access pages in Microsoft Access

You can also work with a data access page in Page view in Microsoft Access. Data access pages can supplement the forms and reports that you use in your database application. When deciding whether to design a data access page, form, or report, consider the tasks that you want to perform.

You get Help on how to work with the page in Page view by clicking the Help button on the Page View toolbar to display Access Help. Clicking the Help button on a record navigation toolbar on the page displays Help for working with the page in Internet Explorer. As mentioned previously, this Help file is automatically included with any data access page that's published with a record navigation toolbar. You can delete the Help button on pages that are used only within Access, or you can modify the button to provide custom Help.

Return to top

More information

Create a data access page


 Create a data access page

Create a data access page

To create a data access page, or to open a page in Design view, Page view, or in Microsoft Internet Explorer, you must install Internet Explorer 5 or later if it isn't already installed.

What do you want to do?

Create a data access page by using AutoPage With AutoPage, you select a record source and AutoPage creates a page that uses all the fields from that record source

Create a data access page by using a wizard The wizard asks you detailed questions about the record sources, fields, layout, and format you want and creates a page based on your answers

Make an existing Web page into a data access page

Create a data access page on my own


 Should I use a form, report, report snapshot, or data access page?

Should I use a form, report, report snapshot, or data access page?

Each Microsoft Access database object is designed for a particular purpose. In the following table, Yes identifies the objects that are best at performing a particular task, Possible identifies objects that can perform the task, though less optimally, and No identifies objects that don't perform the task at all.

Task/Purpose | Form | Report | Report snapshot | Data access page
Enter, edit, and interact with data within a Microsoft Access database or Microsoft Access project | Yes | No | No | Yes
Enter, edit, and interact with live data via the Internet or an intranet outside an Access database or Access project; users must have a Microsoft Office 2000 license but don't have to have Office installed | No | No | No | Yes
Print data for distribution | Possible | Yes | Yes | Possible
Distribute data by e-mail | No | No | Yes (static data) | Yes (live data)


 Strategies for creating data access pages

Strategies for creating data access pages

What do you want to accomplish with your data access page? There are many features that you can use to create effective data access pages. This topic helps you identify the right features and layout to use for each type of page. There are four types of data access pages, which you can use to:

Analyze data

Enter and edit data

Make projections

Review data

Analyze data

You can use a PivotTable list to analyze data because it allows you to reorganize the data in different ways. You can bind a PivotTable list to data in the database or use data from a Microsoft Excel worksheet. You can use the PivotTable list as the only control on a data access page or use it with other controls.

  • When using a PivotTable list on an ungrouped page, place the PivotTable list control and other controls either in the body or in the section.

  • When using a PivotTable list on a grouped data access page:
    • Place the PivotTable list and bound controls in the section.

    • Make sure the PivotTable list is in the lowest group level.

    • If the PivotTable list is the only control in a section, delete or hide the navigation section for the group level that the PivotTable list is in.

    • Make sure the DataPageSize property in the Sorting And Grouping box is set to 1.

How to create a PivotTable list on a data access page.

Return to top

Enter and edit data

You can create a data access page on which users can enter, edit, and delete data in the database. Key points to keep in mind when creating a page for data entry:

  • Use individual controls, such as text boxes, list boxes, drop-down list boxes, option groups, option buttons, and check boxes.

  • Place controls either in the body or in the section. You can delete the section if you don't use it.

  • Create only one group level. The Sorting And Grouping box will list only one group record source.

  • Make sure the DataPageSize property in the Sorting And Grouping box is set to 1.

  • Use the Spreadsheet Component to create a spreadsheet to perform one or more calculations on the fields in a record. You can display the calculated values in the spreadsheet or hide the spreadsheet and display the calculated values in bound HTML controls.

  • Determine how users can use the data access page by customizing the record navigation bar.

  • If you want to edit data from tables that have a one-to-many relationship, create one page that is bound to the table on the "one" side of the relationship and another data access page that is bound to the "many" side. Then, you can use the Insert Hyperlink dialog box to create a link between the two data access pages. To display the data from both pages on one page, you can use an HTML editor (for example, Microsoft FrontPage) to create frames.

Learn about creating a data access page for that's used for data entry.

Return to top

Make projections

You can use the Chart Component to create a chart to analyze trends, show patterns, and make comparisons on the data in your database, or use a spreadsheet control, in which you can enter and edit data and use formulas to perform some of the same calculations you can do in Excel.

  • When using a spreadsheet control on an ungrouped data access page, place the spreadsheet control and other controls either in the body or in the section.

  • When using a spreadsheet control on a grouped data access page, place the spreadsheet control and other controls bound to fields in the database in the section. You can use a spreadsheet control in any group level.

  • Make sure the DataPageSize property in the Sorting And Grouping box is set to 1 for the section that contains the spreadsheet control.

How to create a spreadsheet on a data access page.

How to create a chart on a data access page.

Return to top

Review data

Data access pages give you a way to interact with large amounts of data in a selective way. By expanding and collapsing groups of records, users can focus only on the data that they want to see. Keep the following points in mind when you create a grouped page:

  • Place bound controls in the section.

  • In the lowest group level, use individual controls or a PivotTable list to display detail records.

  • Remove unneeded buttons from the record navigation bar.

  • To make loading the data access page in Microsoft Internet Explorer faster:
    • Use bound HTML controls instead of text boxes.

    • Set the ExpandedByDefault property to No for all group levels.

    • Set the DataPageSize property in the Sorting And Grouping box, which determines the number of records displayed in a group on a page, to a low rather than a high number or to All. The lower the number, the faster the records are displayed.

How to create a data access page that groups records.

Return to top


 About data access pages that are used for data entry

About data access pages that are used for data entry

This topic provides reference information about:

Using a data access page for data entry

A data entry page in Design view

A data entry page in Page view or Internet Explorer

Using a data access page for data entry

Using a data access page for data entry is similar to using a data entry form: You can enter, edit, and delete data in a database. However, you can use a page outside a Microsoft Access database, so users who have a Microsoft Office 2000 license can update data over the Internet or an intranet.

The following illustration shows how the Product data access page, which is used for entering and updating product information, looks in Page view or in Microsoft Internet Explorer 5 or later.

Data entry page in Page view

Return to top

A data entry page in Design view

The body The body is the basic design surface of a data access page. On a data entry page, you can use it to display informational text, controls bound to data, and sections. By default, the position of text, sections, and other elements in the body are relative. That is, elements flow one after the other in the same order as they appear in the HTML source. The position of an element in the body is determined by the preceding content. When viewed in Page view or Internet Explorer, the content in the body adjusts itself to fit the size of the Web browser.

Sections You use sections to display text, data from a database, and toolbars. The position of controls and other elements within a section is absolute by default. That is, the position of each control or element is fixed relative to the top and left coordinates of the section. Controls that have an absolute position within a section keep the same position even when you resize the browser.

There are two types of sections that are typically used on data entry pages: group header and record navigation sections. On a data entry page, you can use just one group level; so the group footer section isn't available, but you can use a caption section.

  • Group header Used to display data and calculate values.

  • Record navigation Used to display the record navigation control for the group level. A record navigation section for a group appears after the group header section. You can't place bound controls in a record navigation section.

  • Caption Used to display captions for text boxes and other controls. It appears immediately before the group header. You can't place bound controls in a caption section.

Each group level in a data access page has a record source. The name of the record source is displayed on the section bar for each section used for a group level. The following illustration shows the Products data access page in Design view.

Parts of a data entry page in Design view

Return to top

A data entry page in Page view or Internet Explorer

The following illustration shows how the sections look on the Products data access page when it's open in Page view or in Internet Explorer. You can enter and edit data on pages where there is only one group level and where only one record is displayed on the data access page. To display one record, you set the group level's DataPageSize property in the Sorting And Grouping box to 1 in page Design view.

Sections on a data entry page in Page view

Return to top

More information

Create a data access page


 About grouping records on a data access page

About grouping records on a data access page

This topic provides reference information about:

Benefits of grouped data access pages

A grouped data access page in Design view

A grouped data access page in Page view or Internet Explorer

Benefits of grouped data access pages

Grouping records on a data access page is similar to grouping records on a report: You can create a hierarchy that groups records from general categories to specific details. However, data access pages have some advantages over printed reports.

  • Pages bound to database data display current data because they are connected to a database.

  • Pages are interactive. Users can filter, sort, and view just the records that they want.

  • Pages can be distributed electronically by using e-mail. Recipients will see current data each time they open the message.

The following illustration shows how the sample data access page, Orders by Date, which shows order totals grouped by date, looks in Page view or Microsoft Internet Explorer 5 or later.

Data access page with one group expanded

Return to top

A grouped data access page in Design view

The body The body is the basic design surface of a data access page. On a grouped page, you can use the body to display informational text and sections. By default, the position of text, sections, and other elements in the body are relative. That is, elements flow one after the other in the same order as they appear in the HTML source. The position of an element in the body is determined by the preceding content. When viewed in Page view or Internet Explorer, the content in the body adjusts itself to fit the size of the Web browser.

Sections You use sections to display text, data from a database, and toolbars. The position of controls and other elements within a section is absolute by default. That is, the position of each control or element is fixed relative to the top and left coordinates of the section. Controls that have an absolute position within a section keep the same position even when you resize the browser.

There are four types of sections available on a grouped data access page: group header, group footer, caption, and record navigation sections. You can use just the sections you need for a group level.

  • Group header Used primarily to display data and calculate totals. To group data, you must have at least two group levels. The group header at the lowest group level is like the detail section of a report: It repeats until all the records are printed for the current group.

  • Group footer Used primarily to calculate totals. It appears before the record navigation section for the group level. A group footer is not available for the lowest group level on a data access page.

  • Caption Used to display captions for columns of data. It appears immediately before the group header. This section is displayed only when the next-higher group level is expanded. You can't place bound controls in a caption section.

  • Record navigation Used to display the record navigation control for the group level. A record navigation section for a group appears after the group header section if there is no footer for the group level and appears after the footer if there is a footer for the group level. You can't place bound controls in a record navigation section.

Each group level has a record source. The name of the record source is displayed on the section bar for each section used for a group level. The following illustration shows the Orders by Date data access page in Design view.

Sections used on a data access page with two group levels

Return to top

A grouped data access page in Page view or Internet Explorer

The following illustration shows how the sections look on the same data access page when it's open in Page view or in Internet Explorer 5 or later. You can specify how many records you want displayed on the page for each group level by setting the DataPageSize property in the Sorting And Grouping box in page Design view. In the example page, DataPageSize is set to 2 for the OrderTotals-OrderDate group level and to All for the OrderTotals group level.

Grouped data access page with records in one group expanded

Return to top

More information

Create a data access page with grouped records.

Learn about grouping records on intervals of autonumbered, currency, or numeric values

Learn about grouping records on intervals of date or time values

Learn about grouping records on the first n characters in a text value


 Connect a data access page or other Web page to a database

Connect a data access page or other Web page to a database

If no database is open when you create a data access page or when you open in Microsoft Access a Web page created outside of Access, Access prompts you for connection information. If you don't specify the connection information when prompted, you'll need to specify it after you've opened the page; otherwise, you won't be able to bind database data to the page. In addition, if you change the location of a database after creating a data access page that stores the original location in its ConnectionString property, you'll need to change the connection information for the page.

  1. In Design view of a data access page, display the field list.

  2. Right-click the database icon at the top of the list.

  3. On the shortcut menu, click Connection.

  4. Specify the connection information for the database you want to use for the data access page.

    For information about the Connection dialog box, click the Help button at the bottom of the dialog box.

Notes

  • If you already have a Microsoft Access database or Microsoft Access project open when you create a data access page or open a Web page created outside of Microsoft Access, the page is automatically connected to the open database and stores that connection information in its ConnectionString property.

  • You can also change the ConnectionString property in the data access page property sheet directly.

  • A PivotTable list on the data access page may have a separate connection string if it displays data from an external data source. You can modify the connection information for the PivotTable list from within Access by using the Connection Editor in the Data Sources section of the PivotTable Property Toolbox.


 Where a data access page gets its data

Where a data access page gets its data

This topic provides reference information about:

Types of data sources for a data access page

Types of data sources for Microsoft Office Web Components on a data access page

Types of data sources for a data access page

A data access page gets its data from a Microsoft Access database, or a Microsoft SQL Server database version 6.5 or later. To design a page using data from one of these databases, the page must be connected to the database. If you have already opened a Microsoft Access database, or a Microsoft Access project that’s connected to a Microsoft SQL Server database, the data access page you create automatically connects to the current database and stores that path in the ConnectionString property of the data access page. When a user browses to the page in Internet Explorer 5 or displays the page in Page view, it displays current data from the underlying database by using the path defined in the ConnectionString property. If you design the data access page while the database is on a local drive, Microsoft Access will use the local path, which means the data won’t be accessible to others. For this reason, it’s important that you move or copy the database to a network location that’s accessible to those you want to use the page. Once it's on the network share, open the database using the UNC address. If you move or copy the database after you’ve already designed the page, you’ll have to update the path in the ConnectionString property to point to the new location.

When the data access page is connected to a database, the Database tab in the field list displays folders containing all of the tables or queries available in the database. You add data to the data access page from these record sources. If the database icon has a red X on it and you don’t see any folders underneath, you need to connect the data access page to a database to continue designing the page.

Return to top

Types of data sources for Microsoft Office Web Components on a data access page

Although the data access page gets its data from a Microsoft Access or Microsoft SQL Server database, Microsoft Office Web Component controls on the page can display data from either of these databases or from other sources. For example, the page may contain a PivotTable list, spreadsheet, or chart with data from a Microsoft Excel worksheet or a database other than Microsoft Access or Microsoft SQL Server. Depending on the data source, the data in these controls may be a snapshot of the original data or it may be live data displayed through a separate connection that the control has with its data source.

To create a Web component with data from a source other than the current database, you may have to use a program other than Microsoft Access to first publish the data to a Web page. For example, to create a PivotTable list that contains data from a Microsoft Excel worksheet, you have to publish the data from Microsoft Excel. Then, in Microsoft Access, you can open the Web page and turn it into a data access page by adding controls that are bound to a Microsoft Access or Microsoft SQL Server database. You can further customize the page by adding labels, pictures, or other features to enhance the page's appearance. From within Microsoft Access, you can create a PivotTable list control that uses data from an external source other than Microsoft Excel. You do this by specifying connection information in the Data Source section of the PivotTable Property Toolbox when you create the control.

Return to top

More information

About the Microsoft Office Web Component Pack

About OLE DB and Data Links


 Open a data access page

Open a data access page

To create a data access page, or to open a page in Design view, Page view, or in Microsoft Internet Explorer, you must install Internet Explorer 5 or later if it isn't already installed.

Open a page in Design view or Page view

  1. In the Database window, click Pages [image] under Objects.

  2. Click the data access page you want to open.

  3. On the Database window toolbar, do one of the following:
    • To open the page in Design view, click the Design button

    • To open the page in Page view, click the Open button.

Note You can also open a page in Page view by clicking Open on the File menu in Microsoft Access. Access opens the page without opening the database that the page is connected to, so wizards, builders, and add-ins are not available.

Open a page in Internet Explorer

Do one of the following:

  • In Access, open the data access page in Design view or Page view, and then click Web Page Preview on the File menu.

  • If Internet Explorer is your default Web browser, in Windows Explorer, double-click the HTML file to open the page in Internet Explorer without first opening Microsoft Access.


 Switch between views of a data access page

Switch between views of a data access page

To create a data access page, or to open a page in Design view, Page view, or in Microsoft Internet Explorer, you must install Internet Explorer 5 or later if it isn't already installed.

Switch between views from within Microsoft Access

  1. Open the data access page in Design view or Page view.

  2. Click the View button on the toolbar to change to the view indicated by the graphic.

Switch between Microsoft Access and Internet Explorer

Do one of the following:

  • In Microsoft Access, open the page in Design view or Page view, and then click Web Page Preview on the File menu.

  • In Internet Explorer, click Edit in Microsoft Access on the File menu to open the page in Design view in Microsoft Access.


 About adding data to a data access page by using the field list

About adding data to a data access page by using the field list

When you use the field list to add data to your data access page, Microsoft Access automatically creates controls that are bound to the fields you add, just like it does with the form and report field list. However, the form and report field list and the data access page field list are not the same. Before you can add bound controls to a form or report, you must first bind the form or report to a specific record source. Once you do that, only the fields from that record source are displayed in the field list. A data access page, on the other hand, isn't bound until you add controls to it, and then it can be bound to more than one record source at a time. Therefore, the field list for a data access page displays all the fields you can choose from in the database to add to the page.

This topic provides reference information about what you need to do to use the field list and what the field list contains, what Access does for you when you use the field list, and how you add fields to the data access page. Before you begin, familiarize yourself with the strategies for creating a data access page.

You connect to a database

Access identifies related fields

You can add individual controls for each field

You can add a PivotTable control with multiple fields

Access builds the SQL query for the data access page

Access builds the data access page's data definition

You connect to a database

Before you can add data to a data access page, you must be connected to a Microsoft Access database or Microsoft SQL Server database. When the page is connected to one of these databases, the Database tab in the field list displays folders containing all of the tables or queries available in the database. If the database icon in the field list has a red X on it and you don’t see any folders underneath it, you need to connect the data access page to a database to continue designing the page.

Return to top

Access identifies related fields

In the field list, when you click the expand indicator next to a specific table or query, you’ll see the list of fields for that record source. If the record source is a table, you'll see a Related Tables folder above the list of fields. The folder lists the tables and fields that are related to the table you expanded in the field list. If you hold the pointer over a table in the Related Tables folder, you'll see the field through which the tables are related. If you add fields directly from tables that are related, or if you add fields from queries that use related tables, Microsoft Access automatically uses the existing relationships as you design the data access page. If you add fields to the page from tables that aren't related or from tables that have multiple relationships to tables already used on the page, Microsoft Access will prompt you each time to define a new relationship. Relationships you define in this way are only used for the current data access page; they are not added to the database.

Note If you're working in a multiuser environment, you may want to refresh the field list occasionally in case others have added tables or queries since you began designing the data access page.

Return to top

You can add individual controls for each field

You can drag fields one at a time to the data access page to create a control bound to that field. Or you can drag an entire table or other record source from the field list to add all of its fields at one time. If the Control Wizards tool [image] in the toolbox is selected, when you drag an entire table to a section, Microsoft Access displays the Layout Wizard, which asks whether you want to add fields as individual controls or as a PivotTable list. If you want users to be able to edit the data in the fields, or if you want to arrange the controls in a free-form custom layout, use individual controls. With a few exceptions, Microsoft Access automatically creates the appropriate kind of individual control based on the type of data stored in the field. You can also choose the kind of individual control you want it to create before you drag the field to the data access page.

Return to top

You can add a PivotTable control with multiple fields

Add fields as part of a PivotTable control if you want to display data that you can rearrange, summarize, and otherwise analyze in different ways, but not add or change the actual values. Learn more about what a PivotTable list is and what it can do before you decide. Or you can use PivotTable lists just to display data in a grid, such as detail records in a grouped data access page. When you use a PivotTable control in this way, you can set properties that hide the pivoting functionality. If you create a PivotTable list by dragging a table or other record source from the field list and then choosing PivotTable list, some of these properties are already set to hide certain PivotTable list features, such as the title bar, toolbar, and column and row drop areas. Use the PivotTable Property Toolbox to change these and other properties of the control and its content.

Note A PivotTable list control has its own field list separate from the field list for the data access page. The PivotTable field list shows all of the fields you added from the data access page's field list to the PivotTable control. It does not list all of the fields and record sources available in the database. If you remove a field from the PivotTable list control, the field remains in the PivotTable's field list so you can add it at a later time. Unlike the data access page's field list, the PivotTable field list is also available in the browser so others using the page can add fields to the PivotTable list as they're analyzing data.

Return to top

Access builds the SQL query for the data access page

As you drag fields and record sources to the data access page and add grouping levels, sort orders, and so on, Microsoft Access constructs a query behind the scenes that translates what you've laid out on the screen and otherwise specified for the design into Structured Query Language (SQL) that the database understands. Using the existing relationships that are defined between record sources, Microsoft Access creates a query that retrieves the data you selected and presents it the way you've specified. If you add fields from record sources that have no relationship, Microsoft Access displays the New Relationship dialog box so you can define the relationship yourself.

Return to top

Access builds the data access page's data definition

When you add a field to the data access page, Access also adds the field to the page's data definition, which is the collection of data you've added to the page. The data definition, represented on the Page tab in the field list, shows which record sources are used for the page, how the data is related, and what the grouping levels are.

Return to top

More information

Where the data comes from for a data access page


 Refresh a data access page's field list to display new tables or queries

Refresh a data access page's field list to display new tables or queries

If you're working in a multiuser environment, you may want to occasionally refresh the data access page's field list to see any new tables or queries or changes to existing tables or queries that others may have added since you began designing the page.

  • On the Database tab in the field list, right-click the database icon at the top of the field list, and then click Refresh.


 Define a new relationship between record sources in a data access page

Define a new relationship between record sources in a data access page

If you add fields to the data access page and there isn't an existing relationship between the tables or queries they came from, Microsoft Access prompts you to define the relationship.

  • In the New Relationship dialog box, indicate which field you want to use to relate the record source you just tried adding to the data access page and the record source or sources that are currently part of the data access page's data definition. Also indicate the type of relationship between the two record sources.

Notes

  • Relationships you define in the New Relationship dialog box apply only to the current data access page. They are not added to the database; therefore, they won't appear in the Relationships window in a Microsoft Access database or the Database Diagram window in a Microsoft Access project.

  • In some cases, Access determines only one type of relationship is possible between the two record sources, so the other option will be disabled.


 Select a data access page, section, control, or other element

Select a data access page, section, control, or other element

  1. Open the data access page in Design view.

  2. Do one of the following:
    • To select the page, click Select Page on the Edit menu.

    • To select the body, click outside a section.

    • To select a section, click the section bar.

    • To select a control, click the control.

    • To select text, drag the cursor over the text you want to select.


 Set document properties such as title, subject, and author for a data access page

Set document properties such as title, subject, and author for a data access page

  1. Open the data access page in Design view or Page view

  2. On the File menu, click Page Properties.

  3. Set properties as needed on the following tabs:
    • General This is the same information that is displayed when you right-click the name of a file in Microsoft Windows Explorer and then click Properties on the shortcut menu. The only difference is that when you view these properties in Microsoft Access, the Attributes settings are read-only.

    • Summary The information that you enter on this tab is added to the SummaryInfo Document object in the Documents collection. This information is similar to the summary information that you can provide in other Microsoft Office applications. Summary information allows you to better identify a page both from within Microsoft Access and from other programs such as the Microsoft 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 that the active page was created, the last date and time it was modified, who modified it, the number of times it's been revised, and the total editing time.

    • Contents This information includes the title and the connection string.

    • Custom The custom properties that you enter become properties of the UserDefined Document object in the Documents collection.


 Set properties for a data access page, section, or control

Set properties for a data access page, section, or control

  1. Open the data access page in Design view.

  2. Do one of the following:
    • To select the page, click Select Page on the Edit menu.

    • To select a section, click the section bar.

    • To select a control, click it.
  3. Click Properties [image] on the toolbar. Microsoft Access displays the name of the object you selected in the title bar of the property sheet.


 Calculate a total or other value for one record on a data access page

Calculate a total or other value for one record on a data access page

What do you want to do?

Calculate a total or other value for one record on a page used for data entry This method uses a spreadsheet control, which automatically updates the calculated amount as you make changes to the values in the fields used in the expression.

Calculate a total or other value for one record on a grouped page This method uses a bound HTML control. When you use a bound HTML control instead of a spreadsheet control, you can display multiple records in each group level on a page.


 Calculate a total, average, or other aggregate for a group of records in a data access page

Calculate a total, average, or other aggregate for a group of records in a data access page

  1. Open the data access page in Design view. The page must have at least two group levels.

  2. Create a bound HTML control bound to the field you want to use to calculate a total, average, or other aggregate in the appropriate group header or group footer. For example, to calculate an order subtotal on a page with group levels bound to the Orders and Order Details tables, you would put the control that calculates the subtotal in the group header or footer of the higher group level, Orders.

  3. Make sure the bound HTML control is selected, and then click Properties [image] on the toolbar to display the property sheet.

  4. In the TotalType property box, select the type of aggregate you want from the list: Sum, Avg, Min, Max, Count, Any, or StDev.


 Calculate a grand total or other aggregate for all records on a data access page

Calculate a grand total or other aggregate for all records on a data access page

  1. Open the data access page in Design view. The page must have at least two group levels.

  2. Create a bound HTML control bound to the field you want to use to calculate a grand total in the group header of the highest group level.

  3. Make sure the bound HTML control is selected, and then click Promote [image] on the toolbar.

  4. With the bound HTML control still selected, click Properties [image] on the toolbar.

  5. In the TotalType property box, select the type of aggregate you want from the list: Sum, Avg, Min, Max, Count, Any, or StDev.

    The rest of the steps are optional.

  6. Create a label for the bound HTML control.

  7. Select the expand control in the header that contains the grand total and press DELETE.

  8. Select the record navigation section for the group level that contains the grand total and press DELETE. Access deletes the section and the navigation control that it contains.


 Examples of expressions used on data access pages

Examples of expressions used on data access pages

Expressions you can use in text boxes and bound HTML controls

See examples of expressions that manipulate text

See examples of expressions that perform arithmetic operations

See examples of expressions that refer to values of controls

See examples of expressions that manipulate and calculate dates

See examples of expressions that return one of two possible values

Learn more about creating expressions in a Microsoft Access database (.mdb).

Learn more about creating expressions in a Microsoft Access project (.adp).

Functions you can use in controls on data access pages, and in the queries underlying them

Expressions you can use in spreadsheet controls

See examples of commonly used formulas


About themes

A theme is a set of unified design elements and color schemes for bullets, fonts, horizontal lines, background images, and other data access page elements. A theme helps you easily create professional and well-designed data access pages.

When you apply a theme to a data access page, the following elements are customized in your data access page: body and heading styles, background color or graphic, table border color, horizontal lines, bullets, hyperlink colors, and controls.

You can apply a theme for the first time, apply a different theme, or remove a theme using the Theme command on the Format menu. You can preview a theme before applying it by selecting it from the list of available themes and viewing the display of sample data access page elements in the Sample of theme box. Before applying a theme in the Theme dialog box, you can also select options to apply brighter colors to text and graphics, animate certain theme graphics, and apply a background to your data access page. Theme graphics are animated only when you view the data access page in a Web browser, not while you view the data access page in Microsoft Access.

A variety of themes are available on your hard drive when you install Access. If you have Microsoft FrontPage 4.0 or 98 installed, you can use the FrontPage themes as well. There are also additional themes available from the World Wide Web. To download additional themes, click Microsoft on the Web on the Help menu.

More information

Use a theme for a new or existing data access page


Use a theme for a new or existing data access page

What do you want to do?

Learn more about themes

Apply a theme to an existing data access page

Apply a theme to a new data access page

Choose a default theme for new data access pages


 Choose a default theme for new data access pages

Choose a default theme for new data access pages

  1. Open any data access page in Design view.

  2. On the Format menu, click Theme.

  3. In the Choose a theme list, click the theme you want.

  4. Click Set Default.

  5. Click Yes.


Remove a theme from a data access page

What do you want to do?

Remove a theme from an existing data access page

Remove the default theme for new data access pages


 Add a background picture to a data access page

Add a background picture to a data access page

  1. Open the data access page in Design view.

  2. On the Format menu, point to Background, and then click Picture.

  3. In the Insert Picture dialog box, make sure that Picture Files is selected in the Files of type list, and then locate the file that you want to use for the background.

  4. Click OK.

Note You can set the following properties in the property sheet to adjust how the background picture is displayed: BackgroundPostionX, BackgroundPositionY, and BackgroundPositonRepeat.


 Add a background sound to a data access page

Add a background sound to a data access page

  1. Open the data access page in Design view.

  2. On the Format menu, point to Background, and then click Sound.

  3. In the Insert Sound dialog box, make sure that All Sounds (*.wav;*.au) is selected in the Files of type list, and then locate the file that you want to use for the background sound.

  4. Do one of the following:
    • Click Insert to store the sound file in the folder where supporting files for the data access page are stored.

    • Click Link to File to store a reference to the sound file.

    The sound will play when you open the page in Page view or in Internet Explorer.


 Change the record source for a section on a data access page

Change the record source for a section on a data access page

Use this procedure on a page that has only one group level.

  1. Open the data access page in Design view.

  2. Click the section bar of the section that you want to change, then click Properties [image] on the toolbar.

  3. In the RecordSource property, click a record source in the list.


 Change the size of a header, footer, or other section on a data access page

Change the size of a header, footer, or other section on a data access page

  1. Open the data access page in Design view.

  2. Click the section bar of the section you want to change. Microsoft Access displays selection boxes around the perimeter of the section

  3. Click a selection box. When the pointer changes to a crosshair, drag a selection box at the top or bottom of a section up or down; drag a selection box on the side left or right; or drag a selection box in the corner diagonally.

    You can drag any selection box to resize a section, but Access always adjusts a section from the bottom or the right edge. For example, if you drag the selection box at the top of a section down to reduce the section's height, Access moves the bottom edge of the section up.


 Add an unbound section to a data access page that doesn't have one

Add an unbound section to a data access page that doesn't have one

  1. Open the data access page in Design view.

  2. On the Insert menu, click Unbound Section.

Once you add an unbound section to a data access page, you can modify the page's design in other ways.


 Add or remove a group footer on a data access page

Add or remove a group footer on a data access page

  1. Open the data access page in Design view.

  2. Click Sorting And Grouping [image] on the toolbar to display the Sorting And Grouping box.

  3. Click the group record source for which you want to add or remove a group footer.

  4. In the GroupFooter property box, do one of the following:
    • To add a group footer, click Yes. Microsoft Access adds a group footer above the record navigation section for the selected group record source. You can add controls that calculate group totals to the group footer.

    • To delete the group footer, click No. Access deletes the group footer and any controls it contains.

Note You can't add a group footer to the lowest group level on a page.


 Add or remove a group's caption section on a data access page

Add or remove a group's caption section on a data access page

  1. Open the data access page in Design view.

  2. Click Sorting And Grouping [image] on the toolbar to display the Sorting And Grouping box.

  3. Click the group record source for which you want to add or remove the caption section.

  4. In the CaptionSection property box, do one of the following:
    • To add a caption section, click Yes. Microsoft Access adds a caption section above the group header. You can create new labels or paste existing labels in the caption section.

    • To delete a caption section, click No. Access deletes the caption section and any controls it contains.

Note You can't add bound controls to a caption section.


 Add or remove a group's record navigation section on a data access page

Add or remove a group's record navigation section on a data access page

  1. Open the data access page in Design view.

  2. Click Sorting And Grouping [image] on the toolbar to display the Sorting And Grouping box.

  3. Click the group record source for which you want to add or remove a record navigation section.

  4. In the RecordNavigationSection property box, do one of the following:
    • To add a section, click Yes. Microsoft Access adds the section and a record navigation control.

    • To remove the section, click No. Access removes the record navigation section and any controls it contains.

Tip You can also remove a record navigation section and any controls in it by clicking its section bar to select it, and then pressing DELETE.

Notes

  • When you delete a group level's record navigation control or record navigation section, Microsoft Access automatically changes the DataPageSize property for the group to All. If you delete the record navigation control or section for the highest group level, all the records in that group level will be displayed when you open the page in Page view or in Microsoft Internet Explorer. As a result, it might take longer to load a page.

  • You can't add bound controls to a record navigation section.


 Change the tab order in a data access page

Change the tab order in a data access page

  1. Open a data access page in Design view.

  2. Select the control you want to move in the tab order, and then click Properties [image] on the toolbar to display the control's property sheet.

  3. In the TabIndex property box, type the new tab order number.

  4. Switch to Page view to test the tab order.

Note In Design view, the tab order is always the order in which you created the controls.


 Remove a text box or other control from the tab order on a data access page

Remove a text box or other control from the tab order on a data access page

  1. Open a data access page in Design view.

  2. Select the control you want to remove from the tab order, and then click Properties [image] on the toolbar to display the control's property sheet.

  3. In the TabIndex property box, type -1.

Note As long as a control's Disabled property is set to False, you can click the control in Page view or in a Web browser to select it even if its TabIndex property is set to -1.


 Display a title and other informational text on a data access page

Display a title and other informational text on a data access page

  1. Open the data access page in Design view.

  2. Do one of the following:
    • To add a title, click the placeholder text labeled Click here and type title text.

    • To add other informational text, click the placeholder text labeled Click here and type body text.
  3. Use the buttons on the Data Access Page Formatting toolbar to change the font, font size, and other characteristics of the text.

Note To display HTML text on a page, create a bound HTML control in the body or a section.


 Format text as a bulleted or numbered list on a data access page

Format text as a bulleted or numbered list on a data access page

  1. Open the data access page in Design view.

  2. Select the text.

  3. Click Numbering [image] or Bullets [image] on the toolbar.


 Increase or decrease the amount text is indented on a data access page

Increase or decrease the amount text is indented on a data access page

  1. Open the data access page in Design view.

  2. Select the text.

  3. Click Increase Indent [image] or Decrease Indent [image] on the toolbar.


 Remove the placeholder text at the top of a data access page

Remove the placeholder text at the top of a data access page

  1. Open the data access page in Design view.

  2. Click Click here and type title text or Click here and type body text.

  3. Press DELETE.

Even if you don't delete it, the placeholder text won't show when you view the page in Page view or in Microsoft Internet Explorer.


 Group records on a data access page

Group records on a data access page

Grouping records on a data access page is similar to grouping records on a report: you can create a hierarchy that groups records from general categories to specific details. You can view the data on pages with grouped records, but you can't add, edit, or delete data.

Read an overview about grouping records on data access pages.

What do you want to do?

Group records by each value in a grouping field. For example, group sales by employee name.

Group records by using an expression

Group records by the first n characters in a text value. For example, group products by the first letter of the product name.

Group records on intervals of date or time values. For example, group sales by month.

Group records on intervals of autonumbered, currency, or numeric values. For example, group sales in intervals of 1,000.

Note You can use any of the above methods to create a grouped page and create a filter that allows you to select which group of records to display when the page is open in Page view or in Microsoft Internet Explorer.


 Merge two groups on a data access page

Merge two groups on a data access page

When you merge two groups, Microsoft Access moves the controls in the group header and footer of the selected group level into the header and footer of the next lower group level.

  1. Open the data access page in Design view.

  2. Click the section bar of the group header or footer for the group level you want to merge into the next lower group level.

  3. Click Demote [image] on the toolbar.


 Change grouping order on a data access page

Change grouping order on a data access page

  1. Open the data access page in Design view.

  2. Select the group header that you want to move to a lower group level.

  3. Click Demote [image] on the toolbar.

    Microsoft Access moves the controls in the selected group header and footer into the header and footer of the next lower group level.

  4. Click the control you want to move to a higher group level.

  5. Do one of the following:
    • To group on one field from a table or query, click Promote [image] on the toolbar.

    • To group on a table or query, click Group By Table [image] on the toolbar.

    Microsoft Access adds a group header that contains an expand control and a record navigation section that contains a record navigation control. If you grouped on one field, Access moves the control you grouped on to the group header. If you grouped on a table or query, Access moves all the controls, including controls bound to fields that are in that table or query and controls bound to Lookup fields, to the group header.


 Set or change the default sort order of records on a data access page

Set or change the default sort order of records on a data access page

  1. Open the data access page in Design view.

  2. Click Sorting And Grouping [image] on the toolbar to display the Sorting And Grouping box.

  3. Click the group record source for which you want to set the sort order.

  4. In the DefaultSort property box, type the name(s) of the field(s) you want to sort on. Separate the names with a comma. You can follow each name with a space and the keyword ASC or DESC. For example, type OrderDate DESC, OrderID ASC. If you don't specify the order, Microsoft Access sorts in ascending order.

    Note If the control you want to sort on is bound to an expression, you must type the alias of the control as displayed in its ControlSource property. For example, if the ControlSource property of the control you want to sort on is set to GroupOfExtendedPrice: ExtendedPrice, type GroupOfExtendedPrice in the DefaultSort property.


 Specify the number of records to display in a group on a data access page

Specify the number of records to display in a group on a data access page

  1. Open the data access page in Design view.

  2. Click Sorting And Grouping [image] on the toolbar to display the Sorting And Grouping box.

  3. Click the group record source for which you want to specify the number of records to display.

  4. In the DataPageSize property box, click a value in the list or type a value in the box.

If you set DataPageSize to All for a group level, and that group level is the only group level on the page or the highest group level on the page, all the records will be displayed when you open the page in Page view or in Microsoft Internet Explorer. If a page contains many records, it might take longer to load the page.

Note If a group level doesn't have a record navigation section or a record navigation control, you must set DataPageSize to All in order to see all the records for that group level.


 Specify whether a group is expanded or collapsed by default on a data access page

Specify whether a group is expanded or collapsed by default on a data access page

  1. Open the data access page in Design view.

  2. Click Sorting And Grouping [image] on the toolbar to display the Sorting And Grouping box.

  3. Click the group record source you want.

    Note When you set the ExpandedByDefault property, you're specifying whether to show or hide the records in the next lower group level when the page is displayed in Page view or in Microsoft Internet Explorer.

  4. In the ExpandedByDefault property box, do one of the following:
    • To open the page with the records in the next lower group level displayed, click Yes.

    • To open the page with the records in the next lower group level hidden, click No.

Note The page will load faster in Page view and in Microsoft Internet Explorer if the ExpandedByDefault property is set to No for the highest group level on the page.


 Tips for optimizing data access page performance

Tips for optimizing data access page performance

There are several things you can do to make your data access pages load faster in Page view or in Microsoft Internet Explorer 5.

  • Avoid overlapping controls.

  • Use bitmaps and other graphic objects sparingly. Use black-and-white rather than color bitmaps.

  • Make sure the ExpandedByDefault property in the Sorting And Grouping box is set to No for highest group level. Setting it to No for lower group levels will speed up other interactions after the page is opened.

  • Make sure the DataPageSize property in the Sorting And Grouping box, which determines the number of records displayed in a group on a page, is set to a low rather than a high number, or is set to All. The lower the number, the faster the records are displayed.

  • Use bound HTML controls instead of text boxes to display any data that isn't updateable — for example, to display autonumbered values, values derived from expressions, and hyperlinks.

  • On grouped pages, use bound HTML controls instead of text boxes to display data.

  • When using a data access page within Microsoft Access, close all database objects that aren't being used.

  • When using a data access page in Internet Explorer, close all windows that aren't being used.

  • On data access pages that are used for data entry, set the DataEntry property of the page to Yes so that the page opens to a blank record.

  • Index any fields that you sort, group, or filter on.

  • On grouped data access pages that contain records with a one-to-many relationship, group records by table rather than by a field or expression.

  • On grouped data access pages based on tables with a one-to-many relationship, bind each section to a table rather than to a query. Microsoft Access retrieves the records from a table only as it needs to display them on the page. With a query, Access retrieves all the records before it displays any records on the page. Use a query only when you want to limit the data used on the page, calculate aggregate values, or perform a task that's possible only in a query.


 About Microsoft Office Web Components

About Microsoft Office Web Components

Microsoft Office Web Components consists of two .cab files (msowcin.cab, msowc.cab) that contain a number of run-time files collectively called Microsoft Office Web components. The Office Web components include Microsoft Jet 4.0 OLE DB Provider, Microsoft OLE DB Provider for SQL Server, Microsoft Office Data Source Control (MSODSC), several other ActiveX controls and their help files, and other related files. With Office Web Components installed on your computer, you can use a data access page and interactively use a spreadsheet, a PivotTable list, and a chart in Internet Explorer 5 or later.

Office Web Components is installed with Microsoft Office 2000 Professional, Premium, Developer, and Standard editions. If Office Web Components is not installed on your computer but you have a Microsoft Office 2000 site license that permits intranet distribution, your system administrator can configure Microsoft Internet Explorer to automatically download Office Web Components from your corporate intranet the first time you view and work with a page. This lets users at your site use a page without having Microsoft Office 2000 software installed on their computers.

For information about how to configure Office Web Components, see the Microsoft Office 2000 Resource Kit.


 Controls: What they are and how they work

Controls: What they are and how they work

All the information on a form or report is contained in controls. On data access pages, information is contained in controls in the same way as it is on forms and reports. However, information can also be typed directly on the data access page. Controls are objects on a form, report, or data access page that display data, perform actions, or are used for decoration. For example, you can use a text box on a form, report, or data access page to display data, a command button on a form to open another form or report, or a line or rectangle to separate and group controls to make them more readable.

Microsoft Access includes the following types of controls, which are all accessible through the toolbox in form Design view, report Design view, or data access page Design view: text box, label, option group, option button, check box, list box, command button, image control, line, rectangle, and ActiveX custom controls. Forms and reports have these additional controls: toggle button, combo box, bound object frame, unbound object frame, subform/subreport, and page break. Data access pages also include the drop-down list box, hyperlinks, scrolling text, and the PivotTable list, spreadsheet, and chart components.

Controls can be bound, unbound, or calculated. A bound control is tied to a field in an underlying table or query. You use bound controls to display, enter, and update values from fields in your database. An unbound control doesn't have a data source. You can use unbound controls to display information, lines, rectangles, and pictures. The following illustration shows examples of bound, unbound, and calculated controls. A calculated control uses an expression as its source of data. An expression can use data from a field in an underlying table or query of a form or report, or from another control on the form or report.

Bound, unbound, and calculated controls

More information about Microsoft Access controls.


Microsoft Access controls

There are many controls that you can add to a form, report, or data access page to display and analyze data, work with graphics, and link to Web pages, and so on.

This topic provides reference information about:

Controls for entering, displaying, and filtering data

Controls for analyzing data

Controls that link to Web pages

Controls for graphics and animated text

Controls for customization

Controls for organizing data

Controls for entering, displaying, and filtering data

Check boxes

Combo boxes

Command buttons

Drop-down list boxes

Labels

List boxes

Option buttons

Option groups

Subforms

Subreports

Text boxes

Toggle buttons

Return to top

Controls for analyzing data

Office charts

Office PivotTable lists

Office spreadsheets

Return to top

Controls that link to Web pages

Hyperlinks and bound hyperlinks

Return to top

Controls for graphics and animated text

Hotspot images

Image controls, unbound object frames, or bound object frames

Scrolling text

Return to top

Controls for customization

ActiveX

Return to top

Controls for organizing data

Expand

Lines

Page breaks

Record navigations

Rectangles

Tabbed pages

Return to top


 Bind an unbound text box or other control to a field or column

Bind an unbound text box or other control to a field or column

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Make sure that the control is selected and then click Properties [image] on the toolbar to open its property sheet.

  3. In the ControlSource property box, enter the name of the field that you want to bind the control to.

Note If you bind a control to a field this way, or if you change the underlying field for a bound control, Microsoft Access doesn't set the control properties to the values that are set for the same properties in the underlying field. In forms and reports, ValidationRule, ValidationText, and DefaultValue property settings in the underlying field will be applied, however, because these properties are enforced for the field, not just the control. If you create a bound control by dragging fields from the field list to a form or report, the bound control inherits certain properties from the field. For more information about which properties are inherited and how this inheritance works in forms and reports, click [image] .


 Create an unbound text box or other control

Create an unbound text box or other control

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. If you want to use a wizard to help you create the control, make sure the Control Wizards tool [image] in the toolbox is pressed in.

    Notes

    • On forms and reports, you can use wizards to create command buttons, list boxes, subforms, combo boxes, and option groups. On data access pages, you can use wizards to create command buttons, list boxes, and drop-down list boxes.

    • Wizards are not available in a stand-alone data access page, or when you point a data access page to a database other than the one currently open. In this case, you will have to create the control without using a wizard.
  3. In the toolbox, click the tool for the control you want to create.

  4. In the form, report, or data access page, click the place where you want the upper-left corner of the control to be.

    Notes

    • If you click and release the mouse button, Microsoft Access creates a default-sized control. To create a control of a particular size, click the mouse button and then drag until the control is the size you want.

    • If you want to create several controls of the same type, you can double-click the appropriate tool in the toolbox to lock it down.


Create a specific type of text box or other control on a form

There are many controls you can add to a form to display, enter, analyze data, and so on.

This topic provides reference information about:

Controls for entering, displaying, and filtering data

Controls for analyzing data

Controls for organizing data

Controls for the Web and form customization

Controls for entering, displaying, and filtering data

Check boxes, toggle buttons, or option buttons that aren't included in an option group

Command buttons

Controls for pictures or other objects created with another application (Word document, for example)

Labels

List boxes or combo boxes

Option groups that include check boxes, toggle buttons, or option buttons

Subforms

Text boxes

Return to top

Controls for analyzing data

Charts

Controls to display Microsoft Access data in a Microsoft Excel PivotTable report

Return to top

Controls for organizing data

Controls that have multiple pages or tabs

Return to top

Controls for the Web and form customization

Display Web pages on a form

Add an ActiveX control

Return to top


Create a text box or other control on a data access page

This topic provides reference information about:

Controls for entering, displaying, and filtering data

Controls for analyzing data

Controls that are hyperlinks

Controls that display graphics and animated text

Advanced controls

Controls for organizing data

What do you want to create?

Controls for entering, displaying, and filtering data

Bound HTML controls

Check boxes or option buttons that aren't included in an option group

Command buttons

List boxes and drop-down list boxes

Labels

Option groups that contain check boxes or option buttons

Text boxes

Return to top

Controls for analyzing data

Charts

Controls that display Microsoft Access data in a PivotTable list

Spreadsheets

Return to top

Controls that are hyperlinks

Hyperlinks

Bound hyperlinks

Return to top

Controls that display graphics and animated text

Controls for pictures

Hotspot image controls

Scrolling text controls

Return to top

Advanced controls

ActiveX controls

Return to top

Controls for organizing data

Expand controls

Record navigation controls

Lines

Rectangles

Return to top


Create a text box or other type of control on a report

What do you want to do?

Create a label

Create a text box

Create a check box or option button that isn't included in an option group

Create an option group that includes check boxes or option buttons

Draw a line

Draw a rectangle

Create a subreport

Create a control for a picture or other object created with another application

Create a chart

Create an ActiveX control


 Select a text box or other control

Select a text box or other control

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click anywhere in the control.

In a form or report, if the control has an attached label, it looks like this:

Selected control with an attached label in form or report

In a data access page, if the control has an attached label, it looks like this:

Selected control with an attached label on a data access page

Note If you click a control that's already selected, an insertion point appears inside the control so that you can enter or edit text. To select the control, click outside the control, and then click the control again.


 Select adjacent text boxes or other controls in forms and reports

Select adjacent text boxes or other controls in forms and reports

  1. Open a form in Design view or a report in Design view.

  2. Starting at any point outside a control, drag a rectangle over the controls that you want to select.

Tips

You can specify whether the rectangle that you drag over controls needs to touch only the controls or must enclose them completely to select them. On the Tools menu, click Options, click the Forms/Reports tab, and then click one of the options under Selection Behavior.

To remove one or more controls from the selected group, hold down the SHIFT key, and then click the controls that you want to remove.


 Select nonadjacent or overlapping controls in a form or report

Select nonadjacent or overlapping controls in a form or report

  1. Open a form in Design view or a report in Design view.

  2. Hold down the SHIFT key and click each control that you want to select.


 Remove a text box or other control from a selected group in a form or report

Remove a text box or other control from a selected group in a form or report

If you have several controls selected in either form Design view or report Design view, you can remove either one control or several controls from the group. To remove a control from a selected group, hold down the SHIFT key and click the control or controls that you want to remove.


 Move a text box or other control and its label

Move a text box or other control and its label

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control or its label.

    When you click either part of a compound control in forms and reports, Microsoft Access displays the move handles for both controls, as well as the sizing handles for the control that you clicked. On data access pages, when the control is selected, the label is not automatically selected. If you move the control, the label goes with it. But if you move the label, the control does not move.

  3. Move the pointer over the border (not the move handle) of either the control or its label. In forms and reports, the pointer turns into an open hand. In data access pages, the pointer changes to a four-headed arrow. After the pointer changes, drag the controls to a new position.

Control in form or report showing cursor changed to an open hand

Control in data access page showing cursor changed to a four-headed arrow

Notes

  • When you move a control in a form or report, you can maintain its horizontal or vertical alignment with other controls by holding down the SHIFT key while selecting and moving the control. You can move the control horizontally or vertically only, depending on which direction you move it first.

  • If you need to make small adjustments to the placement of a control, you might find it easier to press CTRL plus the appropriate arrow keys. When you move a control this way in forms, reports, and data access pages, Access does not align the control with the grid, even if Snap To Grid is on.


 Move a control or its label separately

Move a control or its label separately

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control or its label.

  3. In forms and reports, place the pointer over the move handle in the upper-left corner of the control or label and the pointer changes to an upward-pointing hand. In data access pages, place the pointer on any edge of the control's border until the pointer changes to a four-headed arrow.

  4. Drag the control or label to its new position. The first example demonstrates how to drag a control on a form or report, and the second example demonstrates how to drag a control on a data access page.

Only the label selected on a form or report

Only the text box selected on a data access page

Notes

  • The parts of a compound control remain related, even if you move the individual parts separately.

  • To move an attached label to another section without moving the control, you must use the Cut and Paste commands. If you move a label to another section, the label will no longer be related to the control.

  • If you need to make small adjustments to the placement of a control on a form, report, or data access page, you may find it easier to press CTRL plus the appropriate arrow keys. When you move a control this way, Microsoft Access does not align the control with the grid, even if Snap To Grid is on.


 Move two or more controls at the same time in a form or report

Move two or more controls at the same time in a form or report

  1. Open a form in Design view or a report in Design view.

  2. Select the controls by holding down the SHIFT key as you click each control.

  3. Pass the pointer over the border (not the move handle) of any selected control until it turns into an open hand, and then drag the controls to a new position.

Example of several controls selected at once


 Move a text box or other control in front of or behind other controls

Move a text box or other control in front of or behind other controls

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control that you want to move, and then on the Format menu, click Send To Back or Bring To Front.

Note A list box or subform is always at the top of the stack; you can't move a list box or subform to the bottom of a stack.


 Cut or copy and paste a text box or other control

Cut or copy and paste a text box or other control

If you want to create a group of evenly spaced controls, it's better to use the Duplicate command instead of the Copy command. For more information, click [image] .

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control that you want to cut or copy. If the control has an attached label, click the control, not the label.

  3. On the Edit menu, click Cut to delete the control, or click Copy to copy the control.

  4. Select the section that you want to paste the control to.

  5. On the Edit menu, click Paste.

    To a limited extent, you can determine where Microsoft Access pastes the control. If you select a section, Access pastes the control in the upper-left corner of the section. If you select a control near the area where you want to paste the control, Access pastes the control just below the selected control. Note, however, that if you paste a label on a form or report, and the control that you select doesn't have an attached label, Access attaches the label to the selected control.

Note Access doesn't copy event procedures associated with a control.


 Duplicate a text box or other control

Duplicate a text box or other control

  1. Open a form in Design view, a report in Design view or a data access page in Design view.

  2. Click the control that you want to duplicate. If the control has an attached label, click the control, not the label.

  3. On the Edit menu, click Duplicate.

    Microsoft Access pastes the control just below the control you selected.

  4. If you want to create another evenly spaced control, click Duplicate again.

    Microsoft Access places the control beneath the most recently pasted control, even if you moved that control.

Notes

  • When you duplicate a control, Microsoft Access doesn't copy event procedures that are associated with it.

  • If you just want to copy formatting properties from one control to another on a form or report, you can click Format Painter [image] on the toolbar. For more information, click [image] .


 Copy formatting characteristics from one text box or other control to another in a form or report

Copy formatting characteristics from one text box or other control to another in a form or report

  1. Open a form in Design view or a report in Design view.

  2. Click the control that has the formatting characteristics that you want to copy.

    Note You can copy characteristics only from a single control.

  3. Click Format Painter [image] on the toolbar. If you know that you'll want to use the same formatting characteristics on several controls, double-click the button to lock it down.

  4. Click the control that you want to paste the formatting characteristics to. You can click the same type of control, or you can select another type of control. For example, you can copy formatting characteristics from a text box to a list box.

    Microsoft Access copies any of the following properties:

BorderStyle | LineSlant | SpecialEffect
BorderColor | Visible | FontWeight
BorderWidth | DisplayWhen | ForeColor
BackColor | FontName | FontItalic
BackStyle | FontSize | FontUnderline
LabelX | TextAlign | LabelAlign
LabelY |  |

Note You can't copy properties to or from ActiveX controls.


 Delete a text box or other control

Delete a text box or other control

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control.

  3. Press DEL.

    If the control has an attached label, Microsoft Access deletes the control and its label. If you want to delete just the attached label, click the label and press DEL.


 Size a text box or other control

Size a text box or other control

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control or controls that you want to resize.

  3. Drag the sizing handles until the control is the size you want.

Example of move handles and sizing handles

In a form or report, if you select more than one control, all the controls change size as you drag the sizing handle of one control.

Notes

  • In data access pages, you can’t size a list box or drop-down list box vertically. The vertical size of the list box and drop-down list box is based on the font setting of the data in the control.

  • If you want to make small adjustments to the size of a control in a form or report, you may find it easier to press SHIFT plus the appropriate arrow keys.


 Size a text box or other control to fit its contents in a form or report

Size a text box or other control to fit its contents in a form or report

  1. Open a form in Design view or a report in Design view.

  2. Select the control or controls that you want to resize.

  3. On the Format menu, point to Size, and then click To Fit.


 Size a text box or other control uniformly using the grid in a form or report

Size a text box or other control uniformly using the grid in a form or report

  1. Open a form in Design view or a report in Design view.

  2. If the grid isn't already displayed, on the View menu, click Grid.

  3. Select the controls that you want to resize.

  4. On the Format menu, point to Size, and then click To Grid.

Notes

  • You can have Microsoft Access automatically snap items to the grid as you size them. For more information, click [image] .

  • You may find that you need to adjust the distance between the dots on the grid so that you can size controls more accurately. For more information, click [image] .


 Size text boxes or other controls uniformly relative to each other in a form or report

Size text boxes or other controls uniformly relative to each other in a form or report

  1. Open a form in Design view or a report in Design view.

  2. Select the controls that you want to size.

  3. On the Format menu, point to Size, and then click one of the following commands:
    • To Tallest. Makes the controls as tall as the tallest selected control.

    • To Shortest. Makes the controls as short as the shortest selected control.

    • To Widest. Makes the controls as wide as the widest selected control.

    • To Narrowest. Makes the controls as narrow as the narrowest selected control.


 Align text boxes or other controls using the grid in a form or report

Align text boxes or other controls using the grid in a form or report

  1. Open a form in Design view or a report in Design view.

  2. If the grid isn't already displayed, click Grid on the View menu.

  3. Select the control or controls that you want to align.

  4. On the Format menu, point to Align, and then click To Grid.

Notes

You can have Microsoft Access automatically snap items to the grid as you create or move them. For more information, click [image] .

You may find that you need to adjust the distance between the dots on the grid so that you can align controls more accurately. For more information, click [image] .


 Align text boxes and other controls on a data access page

Align text boxes and other controls on a data access page

  1. Open the data access page in Design view.

  2. On the Format menu, click Alignment And Sizing to display the Alignment And Sizing toolbar.

Alignment And Sizing toolbar

  3. Make sure that the text box or other control that is aligned or sized the way you want is selected.

  4. Click the button that you want on the Alignment And Sizing toolbar, and then click the control that you want to size or align to the selected control.

    Tip To align or size just one control, click the button on the toolbar once. To lock down the button so that you can align or size several controls, double-click it. To release the lock, click the same or a different button or press ESC.


 Turn Snap To Grid behavior on or off

Turn Snap To Grid behavior on or off

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. On the Format menu, click Snap To Grid.

    If Snap To Grid is turned on, when you create a control by clicking the form, report, or data access page, Microsoft Access aligns the upper-left corner of the control to the grid. If you create a control by dragging, Access aligns all corners of the control to the grid. If you move or resize an existing control, Access lets you move the control or its boundary from grid point to grid point only.

When Snap To Grid is turned off, Access ignores the grid and lets you place, move, or resize controls anywhere on the form, report, or data access page.

Tip If you want to turn Snap To Grid off temporarily, hold down the CTRL key before or while you're placing, moving, or sizing a control. Releasing the CTRL key turns Snap To Grid back on.


 Align text boxes or other controls to each other in a form or report

Align text boxes or other controls to each other in a form or report

  1. Open a form in Design view or a report in Design view.

  2. Select the controls that you want to align. Select only controls that are in the same row or in the same column.

  3. On the Format menu, point to Align, and then click one of the following commands:
    • Left. Aligns the left edges of the controls with the left edge of the leftmost control.

    • Right. Aligns the right edges of the controls with the right edge of the rightmost control.

    • Top. Aligns the top edges of the controls with the top edge of the highest control.

    • Bottom. Aligns the bottom edges of the controls with the bottom edge of the lowest control.

Note If any of the selected controls would overlap after being aligned, Microsoft Access places them with their edges next to each other instead.


 Space text boxes or other controls evenly in a form or report

Space text boxes or other controls evenly in a form or report

  1. Open a form in Design view or a report in Design view.

  2. Select the controls (at least three) that you want to adjust. For controls with attached labels, select the controls, not their labels.

  3. On the Format menu, point to Horizontal Spacing or Vertical Spacing, and then click Make Equal.

    Microsoft Access spaces the controls evenly. Only the middle controls actually adjust, however; the top and bottom controls don't change location.


 Increase or decrease space between text boxes or other controls in a form or report

Increase or decrease space between text boxes or other controls in a form or report

  1. Open a form in Design view or a report in Design view.

  2. Select the controls that you want to adjust.

  3. On the Format menu, point to Horizontal Spacing or Vertical Spacing, and then click Increase or Decrease.

    When the space between controls is increased or decreased, the leftmost (horizontal spacing) and highest (vertical spacing) controls don't change positions.


 Position text, a text box, or another element on a data access page relatively or absolutely

Position text, a text box, or another element on a data access page relatively or absolutely

  1. Open the data access page in Design view.

  2. Make sure that the text box or other control, section, or text is selected, and then click Properties [image] on the toolbar.

  3. In the Position property box, click a value in the list.
    • Relative Places the element in the natural HTML flow of the document but offsets the position of the element based on the preceding content. For example, by default, the position of a control inserted into a paragraph of text in the body of a page is relative to the text that precedes it. When viewed in Page view or in Microsoft Internet Explorer, the content adjusts itself to fit the size of the window.

    • Absolute Places the element relative to either the next positioned element in the hierarchy (its parent),or, if there isn't one, the body. Values for the element's Left and Top properties are relative to the upper-left corner of the element's parent. For example, by default, the position of a control in a section is fixed relative to the Left and Top properties of the section. When viewed in Page view or in Internet Explorer, the content keeps the same position even when you resize the window.


 Change a text box or other control to another type of control in a form or report

Change a text box or other control to another type of control in a form or report

  1. Open a form in Design view or a report in Design view.

  2. Click the control that you want to change.

  3. On the Format menu, point to Change To.

    Microsoft Access displays a list of controls that the selected control can be changed to. If a type of control appears dimmed on the menu, you can't change the selected control to that type of control.

  4. Click the type of control that you want to change to.

    When you change a control to another type of control, Access copies the appropriate property settings from the original control to the new control. If a property exists for the original control but not for the new control, Access doesn't copy that setting. If a property exists for the new control but not for the original control, Access sets the property to the default control style for that type of control.


 Assign a default value to a control

Assign a default value to a control

  1. Open a form in Design view or a data access page in Design view.

  2. Make sure the control is selected, and then click Properties [image] on the toolbar to open the control's property sheet.

  3. In the DefaultValue property box, type the default value (such as New York) or an expression (such as =Date()). If the string expression that you type includes commas or other punctuation, be sure to enclose the value in quotation marks. For example, to use "New York, NY" as the default value, type "New York, NY". In a form in a Microsoft Access database (.mdb), if you need help creating an expression, click the Build button [image] to use the Expression Builder

Note If you set the DefaultValue property for a field in the table's design and also set the DefaultValue property for a control bound to that field, the default value set for the control overrides the default value set for the field.


Change default properties for a text box or other control in a form or report

What do you want to do?

For the current form or report only, change a control's default control style

For the current form or report only, change a control's default control style to match an existing control

Change a control's default control style for all forms or all reports

Not sure which choice you want?


 About changing default properties for a text box or other control in a form or report

About changing default properties for a text box or other control in a form or report

Each type of control has a default set of properties that determines the general appearance and behavior of that type of control. For example, the default properties for a text box determine the size and font of the text box and whether the text box has an attached label. This set of properties for a control is called the "default control style." You may want to change the default control style for a type of control if you find that you often make the same changes to that type of control after you add it to a form or report.

For example, suppose you don't want to create labels for text boxes that you add to a new form. Rather than deleting the label each time you create a text box, you can change the AutoLabel property setting to No in the text box's default control style.

Once you reset a control's default control style, all subsequent controls of that type that you add to the current form or report will have those property settings. The default control style remains in effect for that form or report until you change it again.

Return to Change default properties for a text box or other control in a form or report.


 Change the properties of several text boxes or other controls at once in a form or report

Change the properties of several text boxes or other controls at once in a form or report

  1. Open a form in Design view or a report in Design view.

  2. Make sure a control is selected, and then click Properties [image] on the toolbar to open its property sheet.

  3. Select the other controls by holding down the SHIFT key as you click each control.

  4. In the property sheet, change the appropriate properties.

Notes

  • You can change property settings for a group of controls of the same type or for a group of controls of different types. If you select controls of different types, Microsoft Access displays only the properties that are shared by the group in the property sheet. If all the controls that you've selected share the same property setting, that setting appears in the property sheet; otherwise, the property box is blank. If you change the property setting, the change is applied to all selected controls.

  • The Name property never appears when more than one control is selected because control names must be unique.


 How control properties on a form or report relate to properties in their underlying fields in an Access database

How control properties on a form or report relate to properties in their underlying fields in an Access database

When you create a bound control in forms and reports by dragging a field from the field list, Microsoft Access copies certain properties from the field in the underlying table or query to the control. For example, if the Unit Price field in a Products table has the Format property set to Currency and the DecimalPlaces property set to Auto, then when you create a bound text box in a form by dragging the Unit Price field from the field list, Access automatically sets the Format and DecimalPlaces properties for the text box control to the same values. (This assumes that the DisplayControl property for the field is set to Text Box or has no setting.)

You can change the settings of any inherited (copied) properties in the control's property sheet. If you change a control's property setting, the change doesn't affect the setting of that property for the field in the underlying table or query. Similarly, if you change the property setting for a field in a table or query after you've created a form by using that field, the property setting for the control isn't updated; you must update this manually. (Note, however, that if you change the field property settings for the DefaultValue, ValidationRule, and ValidationText properties, these changes will be enforced in any controls based on these fields, even if the controls were created before you changed the field properties.)

Tip It's best to set the Format, DecimalPlaces, InputMask, ValidationRule, ValidationText, and DefaultValue properties in the underlying field rather than in a control. This way, you can be sure that you have consistent settings whenever you add fields to a form or report.

The following table lists properties that are inherited for each type of bound control when you drag a field from the field list in forms and reports.

Bound control | Properties inherited
Text box | Format, DecimalPlaces, InputMask, and StatusBarText (from Description property)
List box | All of the properties that are specified in the Lookup tab in table Design view, and the StatusBarText property (from Description property)
Combo box | All of the properties that are specified in the Lookup tab in table Design view, the InputMask property and the StatusBarText property (from Description property)
Check box, option button, option group, toggle button, bound object frame | StatusBarText (from Description property)

Notes

  • The DefaultValue, ValidationRule, and ValidationText properties are not inherited. That is, Access doesn't set the control properties to the values that are set for the same properties in the underlying field. These property settings are enforced, however, when you create a control that is based on a field with these settings. If you set the ValidationRule property in a field, and also in a control based on that field, Access enforces both rules. If you set the DefaultValue property for a field, and also in a control that is based on that field, the control property will override the field property.

  • If you create a text box that is based on a field with the Memo data type, Access automatically sets the EnterKeyBehavior property to New Line In Field, and the ScrollBars property to Vertical Only. These properties aren't inherited from the field properties — they are just properties of the control.


 Change the font of text in a text box or other control

Change the font of text in a text box or other control

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control that contains the text you want to change.

  3. In the Font Name box FontNames object on the Form/Report Formatting toolbar or the Data Access Page Formatting toolbar, click the font you want to apply.

    When you change the font, the change applies to the entire contents of the control. You can't change individual characters in a control.

Tip In forms and reports, if you want to resize the control to fit the new font, point to Size on the Format menu, and then click To Fit.


 Change the font size of text in a text box or other control

Change the font size of text in a text box or other control

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control that contains the text you want to change.

  3. In the Font Size box [image] on the Form/Report Formatting toolbar or the Data Access Page Formatting toolbar, enter the font size that you want to use.

    On data access page scrolling text controls, you can select text and apply formatting to individual characters within the control. In all other controls, when you change the font size, the change applies to the entire contents of the control. You can't change individual characters in a control.

Tip In forms and reports, if you want to resize the control to fit the new font size, point to Size on the Format menu, and then click To Fit.


 Change the alignment of text in a text box or other control in a form or report

Change the alignment of text in a text box or other control in a form or report

  1. Open a form in Design view or a report in Design view.

  2. Click the control that contains the text you want to change.

  3. On the Form/Report Formatting toolbar, click Center [image] to center the text, Align Right [image] to align the text to the right, or Align Left [image] to align the text to the left.

Note If you don't select any of the alignment buttons, the control has general alignment ? text is aligned to the left, and numbers are aligned to the right.


 Change the default alignment of text in new text boxes or other controls for forms and reports

Change the default alignment of text in new text boxes or other controls for forms and reports

Changes made by using this procedure only affect new controls on the current form or report. If you want to change the default control style for all forms and reports, click [image] .

  1. Open a form in Design view or a report in Design view.

  2. Click the appropriate tool in the toolbox. For example, if you want to change the default alignment of text in a text box, click the Text Box tool Text Box control in the toolbox.

  3. Click Properties [image] on the toolbar to display the property sheet.

    Microsoft Access changes the title bar of the property sheet to indicate that you're setting default properties for that type of control.

  4. In the TextAlign property box, click General, Left, Center, Right, or Distribute. If you click General, Access aligns text to the left and numbers and dates to the right.


 Set the margins within a label or text box on a form or report

Set the margins within a label or text box on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Select the control, and then click Properties [image] on the toolbar to display the control's property sheet.

  3. Do one of the following:
    • To adjust the left margin of a control, in the LeftMargin property box type the new margin.

    • To adjust the top margin of a control, in the TopMargin property box type the new margin.

    • To adjust the right margin of a control, in the RightMargin property box type the new margin.

    • To adjust the bottom margin of a control, in the BottomMargin property box type the new margin.

Note You can enter margins in either inches (in), centimeters (cm), pixels (px), or points (pt). For example, 5px creates a margin that is 5 pixels from the edge of the control.


 Display text vertically in a text box or label on a form or report

Display text vertically in a text box or label on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Select the control, and then click Properties [image] on the toolbar to display the control's property sheet.

  3. In the Vertical property box, click Yes.


 Make text in a text box or other control bold, italic, or underlined

Make text in a text box or other control bold, italic, or underlined

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control that contains the text you want to change.

  3. On the Form/Report Formatting toolbar or the Data Access Page Formatting toolbar, click Bold [image] to make the text bold, Italic [image] to make the text italic, or Underline [image] to make the text underlined.

    On data access page scrolling text controls, you can select text and apply bold, italic, and underlined formatting to individual characters within the control. In all other controls in forms, reports, and data access pages, when you apply bold, italic, or underlined formatting, the change applies to the entire contents of the control. You can’t change individual characters in a control.

Tip In forms and reports, if you want to resize the control to fit the text, point to Size on the Format menu, and then click To Fit.


 Change the default alignment of text in new attached labels in forms and reports

Change the default alignment of text in new attached labels in forms and reports

Changes made by using this procedure only affect new controls on the current form or report. If you want to change the default control style for all forms and reports, click [image] .

  1. Open a form in Design view or a report in Design view.

  2. Click the tool in the toolbox for the type of control that has the attached label. For example, if you want to change the default alignment of text in labels that attached to text boxes, click the Text Box tool Text Box control in the toolbox.

  3. Click Properties [image] on the toolbar to display the property sheet.

    Microsoft Access changes the title bar of the property sheet to indicate that you're setting default properties for that type of control.

  4. In the LabelAlign property box, click Left, Center, Right, or Distribute.

    For information about how the LabelAlign property interacts with the LabelX and LabelY properties, click [image] .


 Change the color of text in a text box or other control

Change the color of text in a text box or other control

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control that contains the text you want to change.

  3. On the Form/Report Formatting toolbar or the Data Access Page Formatting toolbar, click the arrow next to Font/Fore Color [image] .

  4. Click a color in the palette.

Tip If you want to use the same color for another control, you can just click Font/Fore Color [image] (you don't have to click the arrow next to the button and pick the color again from the palette). If you want to set different colors for several controls at once, click the arrow next to Font/Fore Color [image] , and then click the border of the color palette and drag it to another location. By using this method, you won't need to click Font/Fore Color [image] each time you want to apply a color.


 Set color properties to Microsoft Windows system colors in forms and reports

Set color properties to Microsoft Windows system colors in forms and reports

Using the BackColor, BorderColor, and ForeColor properties, you can create a color scheme in Microsoft Access that matches the color scheme used in other Microsoft Windows applications. Creating a common color scheme is particularly useful if you're developing an application that you want to distribute to multiple users. Setting color properties to Windows system colors enables you to specify a single setting that can display different colors on different users' computers, depending on the colors they've chosen in Windows Control Panel.

  1. Open a form in Design view or a report in Design view.

  2. Open the property sheet for the section or control.

  3. In the property sheet, click the BackColor, BorderColor, or ForeColor property.

  4. In the property box, type one of the numbers that are listed in the following table. For example, if you want the background of your form to display the same color that you or another user uses for the Windows background color, set the BackColor property to -2147483643, the value for Window.
    Screen element | Value
    Scroll bar | -2147483648
    Desktop | -2147483647
    Active window title bar | -2147483646
    Inactive window title bar | -2147483645
    Menu bar | -2147483644
    Window | -2147483643
    Window frame | -2147483642
    Menu text | -2147483641
    Window text | -2147483640
    Title bar text | -2147483639
    Active window border | -2147483638
    Inactive window border | -2147483637
    Application background | -2147483636
    Highlight | -2147483635
    Highlight text | -2147483634
    3-D face | -2147483633
    3-D shadow | -2147483632
    Dimmed (disabled) text | -2147483631
    Button text | -2147483630
    Inactive window title bar text | -2147483629
    3-D highlight | -2147483628
    3-D dark shadow | -2147483627
    3-D light | -2147483626
    ToolTip text | -2147483625
    ToolTip background | -2147483624

Notes

  • The Windows system color value refers only to the color of the screen element listed, not to the type of object it can be assigned to. For example, you could set the BackColor property for a text box to the Windows system color for scroll bars, the desktop, or any other screen element.

  • The values for the Windows screen elements are always the same, regardless of the user's color settings.

  • You can also set the BackColor, BorderColor, and ForeColor properties to a Windows system color using Visual Basic for Applications.


 Make a text box or other control transparent

Make a text box or other control transparent

When a control is transparent, the color displayed in the control is the color of the control, section, or form behind it.

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control that you want to change.

  3. On the Form/Report Formatting toolbar or the Data Access Page Formatting toolbar, click the arrow next to Fill/Back Color [image] .

  4. Click the Transparent button on the palette.

Note You can make any control transparent except labels, list boxes, and toggle buttons in forms and reports. In data access pages, you can make drop-down list boxes, list boxes, rectangles, and PivotTable lists transparent. Option groups in forms, reports, and data access pages are transparent by default.


 Hide a section or control

Hide a section or control

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Do one of the following:
    • To open the property sheet for the section that you want to hide in a form or report, double-click the section selector.

    • To open the property sheet for the section that you want to hide in a data access page, double-click the section bar.

    • To open the property sheet for the control that you want to hide, make sure the control is selected, and then click Properties [image] on the toolbar.
  3. On forms and reports, in the Visible property box, click No. On data access pages, in the Visibility property box, click Hidden.

Notes

  • On forms and reports, to hide or unhide a control in response to an event, you can use a macro or event procedure to set the Visible property. Attach the macro or event procedure to the OnCurrent property of a form or the OnFormat property of a report. 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.

  • For form sections, the Visible property has no effect on a column in Datasheet view. To specify whether a column is visible in Datasheet view, use the ColumnHidden property.

  • To hide an object on a form only when you are printing, use the DisplayWhen property.


 Change the width of the border of a text box or other control

Change the width of the border of a text box or other control

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control that you want to change.

  3. On the Form/Report Formatting toolbar or the Data Access Page Formatting toolbar, click the arrow next to the Line/Border Width [image] button.

  4. Click the border width you want.

Notes

  • If you want to use the same border width for another control, you can just click the Line/Border Width [image] button (you don't have to click the arrow next to the button and pick the width again from the list).

  • In forms and reports, if the SpecialEffect property for the control is set to Raised, Sunken, Etched, or Chiseled, Microsoft Access changes the setting to Flat when you change the border width.


 Change the color of the border of a text box or other control

Change the color of the border of a text box or other control

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control you want to change.

  3. On the Form/Report Formatting toolbar or the Data Access Page Formatting toolbar, click the arrow next to Line/Border Color [image] .

  4. Click a color in the palette.

Notes

  • If you want to use the same color for another control, you can just click Line/Border Color [image] (you don't have to click the arrow next to the button and pick the color again from the palette). If you want to set different colors for several controls at once, click the arrow next to Line/Border Color [image] , click the border of the color palette, and drag it to another location. This way you don't need to click Line/Border Color [image] each time you want to apply a color.

  • If the SpecialEffect property for a control in a form or report is set to Raised, Sunken, Etched, or Chiseled, Microsoft Access changes the setting to Flat when you change the border color.


 Make the border of a text box or other control transparent

Make the border of a text box or other control transparent

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control you want to change.

  3. On the Form/Report Formatting toolbar or the Data Access Page Formatting toolbar, click the arrow next to Line/Border Color [image] .

  4. Click the Transparent button on the palette.

Note If the SpecialEffect property for the control is set to Raised, Sunken, Etched, or Chiseled, Microsoft Access changes the setting to Flat when you make the border transparent.


 Make the border of a text box or other control dotted, dashed, or solid in forms and reports

Make the border of a text box or other control dotted, dashed, or solid in forms and reports

  1. Open a form in Design view or a report in Design view.

  2. Make sure the control is selected, and then click Properties [image] on the toolbar to display the control's property sheet.

  3. In the BorderStyle property box, click the border style you want to apply.

Note If the SpecialEffect property for the control is set to Raised, Sunken, Etched, or Chiseled, Microsoft Access changes the setting to Flat when you change the border style.


 Make a text box or other control appear raised, sunken, shadowed, chiseled, or etched

Make a text box or other control appear raised, sunken, shadowed, chiseled, or etched

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the control that you want to change.

  3. On the Form/Report Formatting toolbar or the Data Access Page Formatting toolbar, click the arrow next to the Special Effect [image] button.

  4. Click the effect you want to apply.

Notes

  • If you want to use the same special effect for another control, you can just click the Special Effect [image] button (you don't have to click the arrow next to the button and pick the effect again from the list).

  • You can adjust the thickness of the shadow by clicking the Line/Border Width [image] button on the Formatting toolbar.

  • In forms and reports, if you click Raised, Sunken, Etched, or Chiseled, Microsoft Access overrides any settings for the BorderColor, BorderWidth, and BorderStyle properties. If you click Etched, Access also sets the BackStyle property for text boxes and combo boxes to Transparent, and the BackColor property for list boxes to the same setting as the section's BackColor property.

  • If you choose a raised or sunken appearance but the three-dimensional look doesn't appear in your form, double-click Display in Windows Control Panel, click the Appearance tab, and then click Windows Standard in the Scheme box.


 Draw a rectangle on a form, report, or data access page

Draw a rectangle on a form, report, or data access page

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the Rectangle tool Rectangle control in the toolbox.

  3. Click anywhere on the form, report, or data access page to create a default-sized rectangle, or drag to create a rectangle that's the size you want.

Note To change the thickness of a rectangle's border, click the rectangle, click the arrow next to the Line/Border Width button on the Forms/Reports Formatting toolbar or the Data Access Page Formatting toolbar and then click the thickness that you want. To change the line style (dashes, double, and so on) of a rectangle in forms and reports, click the rectangle, click Properties [image] on the toolbar to open the property sheet, and then click a border style in the BorderStyle property box. In data access pages, the rectangle tool can only have a solid line style.


 Draw a line on a form, report, or data access page

Draw a line on a form, report, or data access page

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the Line tool Line control in the toolbox.

  3. Click anywhere on the form, report, or data access page to create a default-sized line. You can click and drag to create a line that's the size you want.

Notes

  • To draw horizontal or vertical lines on a form or report, click the Line tool and then drag it to create the line.

  • To make small adjustments to the length or angle of a line in forms and reports, select the line, hold down the SHIFT key, and press one of the arrow keys.

  • To make small adjustments in the placement of a line, hold down the CTRL key and press one of the arrow keys.

  • To change the thickness of a line, click the line, click the arrow next to the Line/Border Width [image] button on the Form/Report Formatting toolbar or the Data Access Page Formatting toolbar, and then click the line thickness you want.

  • To change the line style (dots, dashes, double, and so on) of a line in a form or report, click the line, click Properties [image] on the toolbar to open the property sheet, and then click a border style in the BorderStyle property box. In data access pages, the line tool can only have a solid line style.


 Use custom colors from another application in a form or report

Use custom colors from another application in a form or report

When you want to display graphics in the colors available in the application used to create them, you can specify a custom palette for a form or report. The custom palette replaces the Microsoft Access default palette only for that form or report.

  1. Open a form in Design view or a report in Design view.

  2. Double-click the form selector or the report selector to open the property sheet.

  3. In the PaletteSource property box, type the path and file name of one of the following types of files:
    • .dib (device-independent bitmap file)

    • .pal (Microsoft Windows palette file)

    • .ico (Windows icon file)

    • .bmp (Windows bitmap file)

    • .wmf (Windows metafile)

    • .emf (enhanced metafile)

    • Any other file types supported by graphic filters that you have installed

Note To display pictures and charts in their original colors, the display driver currently loaded in your system must support the palette you specify in the PaletteSource property box. For example, if you specify C:\Windows\256Color.bmp, the currently loaded display driver must support 256 colors.


 Create a tip that pops up when you move the mouse pointer over a text box or other control

Create a tip that pops up when you move the mouse pointer over a text box or other control

  1. Open a form in Design view or a data access page in Design view.

  2. Make sure the control that you want to create a tip for is selected, and then click Properties [image] on the toolbar to open the control's property sheet.

  3. In the ControlTipText (forms and reports) or the Title (data access pages) property box in the property sheet, type the message you want to display for the control. You can type up to 255 characters.

    You can also create a custom Help file or custom What's This tips for your form. For more information, click [image] .


 Display instructions for a text box or other control in the status bar of a form or report

Display instructions for a text box or other control in the status bar of a form or report

  1. Open a form in Design view or a report in Design view.

  2. Make sure that the control is selected, and then click Properties [image] on the toolbar to open its property sheet.

  3. In the StatusBarText property box, type the message that you want to display for the control.

    You can enter up to 255 characters, but Microsoft Access can only display as much text as will fit in the status bar. The amount of text that can be displayed varies according to the font you use and whether you resize the Access window.

Tip You can create a tip that pops up when you move the pointer over a control. For more information, click [image] . You can also create custom Help files and What's This tips. For more information, click [image] .


What is a bound hyperlink?

You can bind a bound hyperlink control on a data access page to a Text field containing an Internet address. Use a bound hyperlink when you want a different hyperlink address for each record in a table. As you move from record to record, you can click on the hyperlink and go to a different Web page for each record.


 What is the hotspot image control?

What is the hotspot image control?

Use the hotspot image control to add an image to a data access page that, when clicked, displays another Web page from your hard drive, the Web, or another location. When you create a hotspot image control, you select the image to display on the page and the address of the file to jump to. In Page view, as the pointer passes over the image, the pointer changes to a hand, indicating that the image is a link that you can click to go to another page. You can also define ScreenTips and alternate text for the image.

The hotspot image control is useful for providing links to information that relates to data on your data access page.

More information

Create a link to a Web page by using an image


 About hyperlink addresses

About hyperlink addresses

You can type a hyperlink address directly in a hyperlink field in a datasheet or in a text box or control that accepts hyperlinks on a form or data access page.

A hyperlink address can have up to four parts that are separated by the number sign (#):

displaytext#address#subaddress#screentip

The following table explains each part.

Part | Description | Optional?
displaytext | The text that you see in the field or control. For example, you might want to display a descriptive name for the World Wide Web site or object specified by the address and the subaddress. | Yes
Address | An absolute or relative path to a target document. An absolute path is a fully qualified URL or UNC path to a document. For data access pages, a relative path is a path that is related to the saved location of the page. For other database objects, a relative path is a path that is related to the base path that is specified in the Hyperlink Base setting in the DatabaseName dialog box (available by clicking Database Properties on the File menu) or to the current database path. | No, unless subaddress points to an object in the current .mdb file or .adp
subaddress | The location in the file or page. For example, you might want to point to a particular form or report in a Microsoft Access database, or a particular bookmark in a Microsoft Word document. For information on the correct syntax to use for each type of document, click [image] . | Yes
screentip | The text that appears when you rest the pointer over a hyperlink. | Yes

Note In a field or text box that formats the hyperlink address as a hyperlink, Microsoft Access doesn't display all four parts in the field or control. If you want to see the whole hyperlink address, use the keyboard to place the insertion point in the field or control (so you don't follow the link), and press F2.

  • If you enter displaytext, Microsoft Access doesn't show any of the rest of the address following the display text.

  • If you don't enter displaytext, Microsoft Access displays just the address.

  • Subaddress is displayed only if there is no display text or address.

  • The ScreenTip that is displayed for a hyperlink on a data access page is defined for the hyperlink control, so a ScreenTip that you enter as part of the address won’t be displayed on the data access page.

See a list of examples of hyperlink addresses.


Create a hyperlink on a data access page

What do you want to do?

Create a link to an existing file or Web page

Create a new data access page and create a link to the page at the same time

Create a link from one data access page to another

Create a link that opens your e-mail program and creates a message addressed to the specified e-mail address


 Create a hyperlink on a form or report

Create a hyperlink on a form or report

When you create a hyperlink by using any of the following methods, Microsoft Access creates a label control on the form or report. Although hyperlinks in a report won't work when viewed in Microsoft Access, the hyperlinks will work when you output the report to Microsoft Word, to Microsoft Excel, or to HTML.

What do you want to do?

Link to a document, file, or Web page

Use the Insert Hyperlink button to create a link to an existing file or Web page

Use the Insert Hyperlink button to create a new data access page and create a link to the page at the same time

Paste a hyperlink from a Microsoft Office document

Paste text from a Microsoft Office document

Drag an Internet shortcut

Link to an object in the current database

Use the Insert Hyperlink button to create a link to a table, query, form, report, or data access page

Link to an e-mail address

Use the Insert Hyperlink button to create a link that opens your e-mail program and creates a message addressed to the specified e-mail address


 Create a field to store hyperlinks

Create a field to store hyperlinks

  1. Open an existing table in Design view, or create a new table.

  2. In the upper portion of the window, type a name for the field that you'll use to store the hyperlinks.

  3. In the Data Type column for that field, select Hyperlink.

  4. Click Save [image] on the toolbar to save the table.

    For information on entering hyperlink addresses in a form or datasheet, click [image] .

Notes

  • In Datasheet view, you can create a field to store hyperlinks by clicking the Hyperlink Column command on the Insert menu and then typing the hyperlink address in the new field.

  • If you create a table by importing data, Microsoft Access automatically makes any column that contains URLs or UNC paths a Hyperlink field. Access will convert the column only if all the values start with a recognized protocol, such as "http:" or "\\". If even one value starts with an unrecognized protocol, Access won't convert the column into a Hyperlink field.


 Modify the hyperlink of a label, picture, or command button

Modify the hyperlink of a label, picture, or command button

  1. Open the form in Design view or the report in Design view.

  2. Right-click the label, image control, or command button to display the shortcut menu.

  3. On the shortcut menu, point to Hyperlink, and then click Edit Hyperlink.

  4. In the Edit Hyperlink dialog box, click an option under Link to, and then fill in the information required for that option.

  5. In the Text to display box, type the text you want displayed in the control.

  6. Click ScreenTip, and type the text you want to appear when the user rests the pointer on the hyperlink. If you leave the ScreenTip text box blank, Microsoft Access displays the hyperlink address, the name of the database object, or the e-mail address as the ScreenTip.

Note You can also modify the hyperlink by typing directly in the property sheet. For information on the syntax to use to type a hyperlink, place the insertion point in the HyperlinkAddress property or the HyperlinkSubAddress property and press F1.


 Create a hyperlink from one data access page to another in the current database

Create a hyperlink from one data access page to another in the current database

  1. Open a data access page in Design view.

  2. On the Insert menu, click Hyperlink.

  3. In the Insert Hyperlink dialog box, click Page in this database under Link to.

  4. In the Text to display box, type the text that you want displayed in the field or text box. If you leave the box blank, then Microsoft Access will use the hyperlink address as the display text.

  5. Click ScreenTip and type the text you want to appear when the mouse pointer hovers over the hyperlink. If you leave the ScreenTip text box blank, Microsoft Access will display the hyperlink address as the ScreenTip.

  6. From the list, select the data access page you want to link to.

  7. To create a filter for the data access page, type an expression in the form of a WHERE clause in the Filter criteria for the data access page box. For example, if you have a data access page that displays order information, including the ID of the salesperson, and you want to link to a second data access page with the employee record about that salesperson, type EmployeeID=[EmployeeID].

  8. Click OK.

    Microsoft Access adds the hyperlink to the data access page. To test the link, switch to Page view and click the hyperlink. Microsoft Access opens the target page in your Web browser.


 Create a picture that's a hyperlink between two data access pages

Create a picture that's a hyperlink between two data access pages

  1. Open a data access page in Design view.

  2. Click the Hotspot Image tool Hotspot Image control in the toolbox, and then click where you want to create the picture.

  3. In the Insert Picture dialog box, locate the picture that you want to use, and then click OK.

  4. In the Insert Hyperlink dialog box, click Page in this database under Link to.

  5. Click ScreenTip, and type the text you want to appear when the mouse pointer hovers over the hyperlink. If you leave the ScreenTip text box blank, then Microsoft Access will display the hyperlink address as the ScreenTip.

  6. From the list, select the page that you want to link to.

  7. To create a filter for the page, type an expression in the form of a WHERE clause in the Filter criteria for the data access page box. For example, to open the second page, which displays the records for the employee ID that is shown on the first page, type EmployeeID=[EmployeeID].

  8. Click OK.

    Microsoft Access adds the hyperlink to the data access page. To test the link, switch to Page view and click the hyperlink. Microsoft Access opens the target page in your Web browser.


Change the default formatting of hyperlinks

  1. On the Tools menu, click Options.

  2. Click the General tab.

  3. Click Web options.

  4. Select the options you want.


 Create a chart on a data access page

Create a chart on a data access page

  1. Open a data access page in Design view.

  2. Click the Office Chart tool Office Chart control in the toolbox.

  3. In the data access page, click where you want the upper-left corner of the chart control to be; Microsoft Access creates a default-sized control. To create a chart of a particular size, click in the data access page and then drag until the control is the size you want.

  4. Follow the instructions in the Microsoft Office Chart Wizard.

Note Wizards are not available in a stand-alone data access page, or when you point a data access page to a database other than the one currently open.


 Create a PivotTable list on a data access page

Create a PivotTable list on a data access page

Although you can rearrange the layout in a PivotTable list in a data access page and set properties to affect its look and behavior, you can't ever add, delete, or change the stored values in the PivotTable list.

  1. In Design view of a data access page, display the toolbox.

  2. Click the Office PivotTable tool Office Pivot List control in the toolbox.

  3. Click on the data access page where you want the upper-left corner of the control to be.

  4. To choose a data source for the PivotTable list, do one of the following:
    • To use the current Microsoft Access or Microsoft SQL Server database as the data source, display the data access page's field list, and then drag to the PivotTable list control the table or query you want to use for the PivotTable list. You can also drag individual fields from these record sources one at a time. When you create a PivotTable list by dragging fields from the field list, Microsoft Access automatically sets the Data source control option in the PivotTable Property Toolbox to MSODSC, which means Microsoft Access uses the same data source control for the PivotTable list as for the page itself. It also sets the Data member option to the name of the table or query on which you based the PivotTable list. Go to step 6.

    • To use an external data source, display the PivotTable Property Toolbox, click the Data Source bar, click the Connection option, then click Connection Editor. Click the Provider tab, and then select the OLE DB provider you want to use to retrieve the data. Click the Connection tab, and then provide the connection information to the data that you want to use for the PivotTable list. For information about the Data Link Properties dialog box, click the Help button at the bottom of the dialog box.
  5. In the Data Source section in the PivotTable Property Toolbox, under Use data from, do one of the following:
    • To use the data from a specific record source within the database, click Data member, and then select the element you want from the list.

    • To use a query or command — such as an SQL statement — to select the data, click Command text, and then type the query or command in the box. For information about the query syntax, see the documentation for the external data source.
  6. Finish the PivotTable list by arranging the layout and using the toolbar in the PivotTable list and the PivotTable Property Toolbox to add totals, set properties, and so on until the control looks and behaves the way you want. Learn more about what a PivotTable list is and how you use it.

Notes

  • To create a PivotTable list that uses data from a Microsoft Excel worksheet, you have to publish the data to a Web page from Microsoft Excel. If you want to turn the Web page into a data access page, open it in Microsoft Access, and then add controls that are bound to Microsoft Access or Microsoft SQL Server database data.

  • When you have a Web Component control bound to an external data source on the same data access page with controls bound to a Microsoft Access or Microsoft SQL Server database, the component control uses a different data source control than the rest of the page.

  • You can create a chart that's linked to the PivotTable list so that when you change the PivotTable list, the chart updates automatically to reflect the changes.

  • When you add a PivotTable list to a grouped data access page, a PivotTable list appears for each unique group and contains only those records for that group. For example, on a page grouped by year with a PivotTable list containing employee sales data, there is a PivotTable list for each year, containing only the sales data for that year. You can't display the PivotTable list for more than one group at a time.

  • If you open the data access page property sheet, you'll see the specific properties associated with all the settings in the PivotTable Property Toolbox, along with other properties not available in the property toolbox.


 Change the connection to the external data source for a PivotTable list or the query it uses

Change the connection to the external data source for a PivotTable list or the query it uses

  1. In data access page Design view, activate the PivotTable list.

  2. Click the title bar of the PivotTable list, and then display the PivotTable Property Toolbox.

  3. Click the Data Source bar to display its settings.

  4. Do one of the following:
    • To change the connection information, click the Connection option, then click Connection Editor. In the Connection Editor, click the Provider tab, and then select the OLE DB provider you want to use to retrieve the data. Click the Connection tab, and then provide the connection information for the data you want to use in the PivotTable list. For information about the Data Link Properties dialog box, click the Help button at the bottom of the dialog box.

    • To use the data from a different record source within the external database, click Data member, and then select the record source you want from the list.

    • To change the command text, in the Data Sources section in the PivotTable Property Toolbox, click Command text under Use data from, and then enter the query to select the data. For information about the query syntax, see the documentation for the external data source.


 Add a spreadsheet to a data access page

Add a spreadsheet to a data access page

You can add a spreadsheet control to a data access page to provide some of the same capabilities you have in a Microsoft Excel worksheet. You can enter values, add formulas, apply filters, and so on. Use the procedure below to create a spreadsheet in which you enter raw data, or import data from a Web page or text file. If within the spreadsheet you want to use data from other controls on the data access page, you need to refer to those controls in the appropriate spreadsheet cells

  1. In Design view of a data access page, display the toolbox.

  2. Click the Office Spreadsheet tool Office Spreadsheet control in the toolbox.

  3. Click on the data access page where you want the upper-left corner of the control to be.

  4. Enter data and formulas or import data to use in the spreadsheet.

  5. Use the toolbar in the spreadsheet and the Spreadsheet Property Toolbox to complete the spreadsheet and make it look and behave the way you want.


 Modify a spreadsheet control so it looks like a text box control

Modify a spreadsheet control so it looks like a text box control

By hiding the control's spreadsheet features, adjusting the color of cell borders to match other controls on the data access page, and sizing the control to a cell or range of cells, you can make the spreadsheet control look like the text box controls on the page.

  1. Open the data access page in Design view.

  2. Activate the spreadsheet control, and then display the Spreadsheet Property Toolbox.

  3. Click the Show/Hide bar, then hide the toolbar, gridlines, title bar, column headers, and row headers by clicking their respective buttons so they aren't pressed in.

  4. Click the Advanced bar, and then do the following:
    • Set AutoFit spreadsheet to True.

    • Set Viewable range to the cell or cells you want to display. For example, to display the value in cell A1, set the Viewable range to A1.
  5. Select the cells whose borders you want to change.

  6. In the Spreadsheet Property Toolbox, if the Format section is not expanded, click the Format bar.

  7. In the Cell format group, click the Borders button.

  8. Do one of the following:
    • To specify a border color, click the Border Color button, and then select the same border color as the other controls you're trying to match on the data access page.

    • To specify border width, click a size in the list.
  9. In the border diagram, click a border line to turn the border on or off. Click an intersection point to turn on or off all borders connected to that intersection.

  10. If necessary, move the control to its final location on the data access page.

Notes

  • If you're changing the settings for borders that were specified previously, in the border diagram you need to click the existing border line to turn it off, and then click the same border line again to turn it back on with the new border color and width settings you specified.

  • When you view the data access page in Page view or Internet Explorer, you won't see the new border when the control has the focus. Move focus away from the spreadsheet to see the effect.


 Activate a PivotTable list, spreadsheet, or chart on a data access page

Activate a PivotTable list, spreadsheet, or chart on a data access page

Activating one of these Microsoft Office Web Component controls is not the same as selecting the control it. When you select the control, you’re selecting the outer control. Once the outer control is selected and has the focus, you can move the focus inside the control to activate its contents. Once its content is activated, you can set properties and work with the features of the control. For example, in a PivotTable list, you can move columns and rows, or otherwise work with its layout and data.

  • Click the control once to select the outer control. Click the control again to activate the content in the control. When the content is activated, the border of the control has diagonal slashes around it.

Selected and activated PivotTable list controls

Once the content is activated, you can select different parts of the Web component to set properties for the selected part.


 Add an ActiveX control (OLE custom control) to a form, report, or data access page

Add an ActiveX control (OLE custom control) to a form, report, or data access page

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the More Controls tool ActiveX control in the toolbox, and then click the control you want in the list.

    Note If you've installed ActiveX controls with other applications, such as Microsoft Excel, those controls will show up if you click the More Controls tool in the toolbox or if you click the ActiveX Control command on the Insert menu. Some ActiveX controls may not work well with Microsoft Access, however. To see a list of controls that have been tested and verified with Microsoft Access, see the Readme file or contact the vendor for the control.

  3. On the form, report, or data access page, click where you want to place the control.

  4. Right-click the control, and then click Properties to open the ActiveX control property sheet.

  5. Set properties as necessary.

    To get Help on any property, click the property in the property sheet, and then press F1.

Notes

  • For more information on using ActiveX controls, see "Using ActiveX Controls," in Building Applications with Forms and Reports.

  • Additional ActiveX controls are available through Microsoft Office 2000 Developer. For information on what's included in Office 2000 Developer, click [image] .


 Register an ActiveX control

Register an ActiveX control

Use this procedure to register an ActiveX control that isn't included with Microsoft Access.

  1. Add the files for the control to your hard disk. See the documentation that came with the control for information.

  2. On the Access Tools menu, click ActiveX Controls.

  3. In the ActiveX Controls dialog box, click Register, specify a path to the control in the Add ActiveX Control dialog box, and then click Open.

  4. Click Close.


 What is a label?

What is a label?

You use labels on a form, report, or data access page to display descriptive text such as titles, captions, or brief instructions. Labels don't display values from fields or expressions; they're always unbound and they don't change as you move from record to record.

Labels are either stand-alone or attached to a control

A label can be attached to another control. When you create a text box, for example, it has an attached label that displays a caption for that text box. This label appears as a column heading in the Datasheet view of a form.

When you create a label by using the Label tool Label control , the label stands on its own — it isn't attached to any other control. You use stand-alone labels for information such as the title of a form, report, or data access page, or for other descriptive text. Stand-alone labels don't appear in Datasheet view.


 Create a label

Create a label

Use this procedure to create a stand-alone label (a label that isn't attached to another control). To create a label that's attached to a control, just create the control. Microsoft Access automatically attaches a label to the control when you create it.

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the Label tool Label control in the toolbox.

  3. On the form, report, or data access page, click where you want to place the label, and then type the text for the label.

Notes

  • If you want to display the text in a label on more than one line on a form or report, you can resize the label after you enter all the text, or you can press CTRL+ENTER at the end of the first line of text to enter a carriage return. If you insert a carriage return, Microsoft Access automatically wraps subsequent lines as you type. To manually insert a line break on a subsequent line, press CTRL+ENTER again. The maximum width of the label is determined by the length of the first line of text.

  • If you want to use an ampersand (&) in a label on a form or report, you must type two ampersands. This is because Microsoft Access uses the ampersand in a label or button to define an access key.


 Change label text or command button text

Change label text or command button text

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the label or button, and then select the label text or button text.

    Button with label text selected

  3. Type the new text.


 Attach a label to a text box or other control in a form or report

Attach a label to a text box or other control in a form or report

  1. Open a form in Design view or a report in Design view.

  2. Click the label that you want to attach to a control.

  3. Click Cut [image] on the toolbar.

  4. Click the control that you want to attach the label to.

  5. Click Paste [image] on the toolbar.


 Specify whether labels are automatically attached to new text boxes or other controls in a form or report

Specify whether labels are automatically attached to new text boxes or other controls in a form or report

You can use this procedure to change the default control style for the current form or report. If you want to change the default control style for all forms and reports, click [image] .

  1. Open a form in Design view or a report in Design view.

  2. Click the tool in the toolbox that you want to set defaults for. For example, if you want to specify whether labels are automatically attached to text boxes, click the Text Box tool Text Box control .

  3. Click Properties [image] on the toolbar to display the property sheet for the tool.

  4. In the AutoLabel property box, click Yes or No.


 Change the default placement of new attached labels for forms and reports

Change the default placement of new attached labels for forms and reports

Changes made by using this procedure only affect new controls on the current form or report. If you want to change the default control style for all forms and reports, click [image] .

  1. Open a form in Design view or a report in Design view.

  2. Click the button in the toolbox for the type of control that has the attached label. For example, if you want to change the default placement of labels attached to text boxes, click the Text Box tool Text Box control in the toolbox.

  3. Click Properties [image] on the toolbar to display the property sheet.

    Microsoft Access changes the title bar of the property sheet to indicate that you're setting default properties for that type of control.

  4. In the LabelX property box (horizontal axis), type a positive or negative number that specifies the starting point of the label text relative to the upper-left corner of the control that the label is attached to. A negative number places the label to the left of the control. A positive number places the label to the right of the control.

  5. In the LabelY property box (vertical axis), type a number. A negative number places the label above the control. A positive number places the label below the control.

Tip To use a unit of measure that is different from the setting specified by double-clicking Regional Settings in Microsoft Windows Control Panel, specify that type of measurement after the number (for example, 1.5 in or 2 cm).

For information about how the LabelX and LabelY properties interact with the LabelAlign property, click [image] .


 Specify whether new attached labels have a colon in a form or report

Specify whether new attached labels have a colon in a form or report

You can use this procedure to change the default control style for the current form or report. If you want to change the default control style for all forms and reports, click [image] .

  1. Open a form in Design view or a report in Design view.

  2. Click the tool in the toolbox that you want to set defaults for. For example, if you want to remove colons from labels attached to text boxes, click the Text Box tool Text Box control .

  3. Click Properties [image] on the toolbar to display the property sheet for the tool.

  4. In the AddColon property box, click Yes or No.


 What is a text box?

What is a text box?

You use text boxes on a form, report, or data access page to display data from a record source. This type of text box is called a bound text box because it's bound to data in a field. Text boxes can also be unbound. For example, you can create an unbound text box to display the results of a calculation or to accept input from a user. Data in an unbound text box isn't stored anywhere.

Examples of bound and unbound text boxes


 Create a text box

Create a text box

How you create a text box depends on whether you want it to be bound, unbound, or calculated.

What do you want to do?

Learn more about bound, unbound, and calculated controls

Create a bound text box

Create an unbound text box

Create a calculated text box


 Make a text box grow or shrink to fit data when printing a form or report

Make a text box grow or shrink to fit data when printing a form or report

  1. Open the form in Design view or the report in Design view.

  2. To display the property sheet, make sure the text box is selected, and then click Properties [image] on the toolbar.

  3. Set the CanGrow or CanShrink property to Yes.
    • CanGrow expands the text box vertically to fit the data in the field when the form or report is printed.

    • CanShrink reduces the text box vertically if there is no data in the field when the form or report is printed.

    To see examples of text boxes that grow or shrink, click [image] .

Notes

  • When you set the CanGrow property to Yes for a text box, Microsoft Access automatically sets CanGrow to Yes for the section.

  • The Catalog and Invoice reports in the Northwind sample database have examples of text boxes that grow. To view these reports, open the Northwind database in your Office folder's Samples folder, and then open the report you want to see in Design view. For information on opening Northwind, click [image] .


 What is a check box?

What is a check box?

You can use a check box on a form, report, or data access page as a stand-alone control to display a Yes/No value from an underlying table, query, or SQL statement. For example, the check box in the following illustration is bound to the Discontinued field in the Products table. The data type of the Discontinued field is Yes/No. If the box contains a check mark, the value is Yes; if it doesn't, the value is No.

Check box bound to a field with a Yes/No data type

When you select or clear a check box that's bound to a Yes/No field in a Microsoft Access database or a Bit column in a Microsoft Access project, Access displays the value in the underlying table according to the field's Format property (Yes/No, True/False, or On/Off). In an Access project, the option button is bound to a column defined as a Bit data type. When the value in this column is 1, it is equivalent to Yes, On, or True conditions. When the value is 0, the column indicates No, Off, or False conditions.

You can also use check boxes in an option group to display values to choose from. For more information on option groups, click [image] .

You can also use an unbound check box in a custom dialog box to accept user input.


 What is an option button?

What is an option button?

You can use an option button on a form, report, or data access page as a stand-alone control to display a Yes/No value from an underlying record source. For example, the option button in the following illustration is bound to the Discontinued field in the Products table of a database. The data type of the Discontinued field is Yes/No. If the option button is selected, the value is Yes; if not, the value is No.

Stand-alone option button displaying Yes value bound to field

When you select or clear an option button that's bound to a Yes/No field in a Microsoft Access database, the value in the underlying table displays according to the field's Format property (Yes/No, True/False, or On/Off). In a Microsoft Access project, the option button is bound to a column defined as a Bit data type. When the value in this column is 1, it is equivalent to Yes, On, or True conditions. When the value is 0, the column indicates No, Off, or False conditions. You can also use option buttons in an option group to display values to choose from. For more information on option groups, click [image] .

You can also use an unbound option button in a custom dialog box to accept user input.


 What is an option group?

What is an option group?

You can use an option group on a form, report, or data access page to display a limited set of alternatives. An option group makes selecting a value easy because you can just click the value that you want. Only one option in an option group can be selected at a time.

In a form or report, an option group consists of a group frame and a set of check boxes, option buttons, and toggle buttons. In a data access page, an option group consists of a group frame and a set of option buttons.

If an option group is bound to a field, only the group frame itself is bound to the field, not the check boxes, toggle buttons, or option buttons inside the frame. Instead of setting the ControlSource property for each control in the option group, you set the OptionValue (form or report) or the Value (data access page) property of each check box, toggle button, or option button. In a form or report, set the control property to a number that's meaningful for the field the group frame is bound to. In a data access page, set the control property to either a number or any text that's meaningful for the field the group frame is bound to. When you select an option in an option group, Microsoft Access sets the value of the field to which the option group is bound to the value of the selected option's OptionValue or Value property.

Selected option in an option group

Notes

  • The OptionValue or Value property is set to a number because the value of an option group can only be a number, not text. Access stores this number in the underlying table. In this example, if you want to display the name of the shipper instead of a number in the Orders table in an Access database, you can create a separate table called Shippers that stores shipper names, and then make the ShipVia field in the Orders table a Lookup field that looks up data in the Shippers table. For more information on creating a Lookup field, click [image] .

  • In a form or report, an option group can also be set to an expression. In a form, report, or data access page, an option group can be unbound. You can use an unbound option group in a custom dialog box to accept user input and then carry out an action based on that input.


 Create a check box, toggle button, or option button

Create a check box, toggle button, or option button

How you create a check box, option button, or toggle button depends on whether you want it to be a stand-alone control that's bound to a Yes/No field in a Microsoft Access database or a Bit column in a Microsoft Access project, a control that's part of an option group, or an unbound control.

What do you want to do?

Read about check boxes and how they work

Read about toggle buttons and how they work

Read about option buttons and how they work

Read about option groups and how they work

Create a check box, toggle button, or option button that's bound to a Yes/No field or Bit column

Create an option group and add check boxes, toggle buttons, or option buttons to the option group

Create an unbound check box, option button, or toggle button


 Create an option group with check boxes, toggle buttons, or option buttons

Create an option group with check boxes, toggle buttons, or option buttons

You can create an option group on your own or you can have Microsoft Access create your option group for you by using a wizard. A wizard speeds up the process of creating an option group because it does all the basic work for you. When you use a wizard, Access prompts you for information, and then creates an option group based on your answers.

Note Toggle buttons are not available in data access pages.

Tip If you want to present more than a few options, use a list box, a combo box, or a drop-down list box instead of an option group.

What do you want to do?

Read about option groups and how they work

Create an option group with a wizard

Create an option group on my own


 List boxes: What they are and how they work

List boxes: What they are and how they work

In many cases, it's quicker and easier to select a value from a list than to remember a value to type. A list of choices also helps to ensure that the value that's entered in a field is correct.

The list in a list box consists of rows of data. In a form, a list box can have one or more columns, which can appear with or without headings. If a multiple-column list box is bound, Microsoft Access stores the values from one of the columns. In a data access page, a list box has one column without a heading.

List box value stored in underlying field

You can use an unbound list box to store a value that you can use with another control. For example, you could use an unbound list box to limit the values in another list box or in a custom dialog box. You could also use an unbound list box to find a record based on the value you select in the list box.

On a form, you can use a combo box instead of a list box; it takes up less room, and you can type new values in it, as well as select values from a list. Learn about combo boxes on forms.

On a data access page, you can use a drop-down list box instead of a list box; it takes up less room; however, you can't type new values in it. Learn about drop down list boxes on data access pages.


 Combo boxes: What they are and how they work

Combo boxes: What they are and how they work

In many cases, it's quicker and easier to select a value from a list than to remember a value to type. With a combo box, you can do either without using too much space on a form. A combo box is like a text box and a list box combined.

Combo box combines text box and list box functionality

When you enter text or select a value in a combo box, if the combo box is bound, the entered or selected value is inserted into the field that the combo box is bound to.

Combo box value stored in underlying field

The list in a combo box consists of rows of data. Rows can have one or more columns, which can appear with or without headings. If a multiple-column combo box is bound, Microsoft Access stores the values from one of the columns.

You can use an unbound combo box to store a value that you can use with another control. For example, you could use an unbound combo box to limit the values in another combo box or in a custom dialog box. You could also use an unbound combo box to find a record based on the value you select in the combo box.

Combo boxes have a LimitToList property that you can use to control whether any value can be entered in the list, or only text that matches one of the values in the list can be entered.

If you have room on your form and you want a list to appear at all times, or if you always want to limit data entries to values in the list, you might want to use a list box instead of a combo box. For more information on list boxes, click [image] .


 Drop-down list boxes: What they are and how they work

Drop-down list boxes: What they are and how they work

In many cases, it's quicker and easier to select a value from a list than to remember a value to type. With a drop-down list box, you can select a value from a list without using too much space on a data access page. A drop-down list box on a data access page looks like a combo box on a form. As in a combo box, a drop-down list box shows only one record until you click to expand the contents; however, you can't type new values in a drop-down list box.

Select a value from a drop-down list box

When you select a value in a drop-down list box, if the drop-down list box is bound, the selected value is inserted into the field that the drop-down list box is bound to.

Drop-down list box value stored in underlying field

The list in a drop-down list box consists of rows of data. Rows can have only one column that appears without headings.

You can use an unbound drop-down list box to store a value that you can use with another control. For example, you could use an unbound drop-down list box to limit the values in another drop-down list box. You could also use an unbound drop-down list box to find a record based on the value you select in the drop-down list box.

If you have room on your data access page and you want a list to appear at all times, you might want to use a list box instead of a drop-down list box. For more information on list boxes, click [image] .


 Should I create a list box, a combo box, or a drop-down list box?

Should I create a list box, a combo box, or a drop-down list box?

To decide whether to create a list box, combo box, or drop-down list box, think about where you're going to use the control, how you want the control to appear on your form or data access page, and how you expect people to use it. Each control offers advantages:

Advantages of a list box You can use list boxes on forms and data access pages. The list appears at all times and the value of the control is limited to the set of alternatives in the list. To move quickly to the first value that starts with a particular letter, you can type that letter. When you're using the form or data access page to enter or edit data, you can't add a value that's not in the list. For more information on list boxes and how they work, click [image] .

Advantages of a combo box You can use combo boxes on forms. Since the list isn't displayed until you open it, the control uses less room on the form. You can type the first few characters of a value in the combo box to quickly find that value. You can also control whether any value can be entered in the list, or only text that matches one of the values in the list can be entered. For more information on combo boxes and how they work, click [image] .

Advantages of a drop-down list box You can use drop-down list boxes on data access pages. Because the list isn't displayed until you open it, the control uses less room on the data access page. The value of the control is limited to the set of alternatives in the list. To move quickly to the first value that starts with a particular letter, you can type that letter. For more information on drop-down list boxes and how they work, click [image] .


 Create a bound or unbound combo box, drop-down list box, or list box

Create a bound or unbound combo box, drop-down list box, or list box

How you create a combo box, drop-down list box, or list box depends on two issues:

  • Whether you want the values in the box to come from a fixed list or from a table or query.

  • Whether you want Microsoft Access to save the values that the user selects, or to use the values to determine the contents of another control.

What do you want to do?

In a form, create a bound list box or combo box that displays data in an Access database

Create a bound list box, combo box, or drop-down list box in a Microsoft Access project or data access page that retrieves data from a record source

Create an unbound list box, drop-down list box, or combo box that displays fixed values

Create an unbound list box, drop-down list box, or combo box that displays values from a table or query in a database

Not sure which choice you want?


 Sort records in a list box, drop-down list box, or combo box

Sort records in a list box, drop-down list box, or combo box

If you use a wizard to create the list box, drop-down list box, or combo box, Microsoft Access automatically sorts the rows that make up the list by the first visible column. If you want to specify a different sort order, or if you're using a saved query as the row source for the list box, drop-down list box, or combo box, you can use this procedure.

Note Wizards are not available in a stand-alone data access page, or when you point a data access page to a database other than the one currently open. In this case, you will have to create a list box or drop-down list box on your own.

  1. Open the form in Design view or the data access page in Design view.

  2. Make sure that the list box, drop-down list box, or combo box is selected, and then click Properties [image] on the toolbar to open the property sheet for the control.

  3. Do one of the following:
    • To change the sort order of a control on a form, in the RowSource property box, click the Build button [image] to open the Query Builder or SQL Statement Builder.

    • To change the sort order of a control on a data access page, create a query with the sort order you want, and then in the data access page ListRowSource property box, select the query from the list.
  4. Specify the sort order.

    How?


 Bind a column from a list box, drop-down list box, or combo box

Bind a column from a list box, drop-down list box, or combo box

  1. Open a form in Design view, or a data access page in Design view.

  2. Make sure the list box, drop-down list box, or combo box is selected, and then click Properties [image] on the toolbar to open the property sheet for the control.

  3. Do one of the following:

    On the form, in the BoundColumn property box of the list box or combo box, specify a number that corresponds to the placement of the column in the list box or combo box. For example, type 1 to bind the first column in the list box or combo box to the underlying field specified in the ControlSource property. Include hidden columns when you count columns.

    On the data access page, in the ListBoundField property box of the list box or drop-down list box, enter the name of the field that corresponds to the placement of the column in the list box or drop-down list box.

Notes

  • In forms, you can specify the number of a hidden column in the BoundColumn property. For more information on hiding a column in a multiple-column list box or combo box, click [image] .

  • In forms, if you set the BoundColumn property to 0, Microsoft Access saves the list index instead of a value from one of the columns. This is useful if you want to store a sequence of numbers instead of the list value.

  • For more information on the BoundColumn property, click [image] .


 Optimize list box, drop-down list box, or combo box performance

Optimize list box, drop-down list box, or combo box performance

There are several things you can do to make your list boxes, drop-down list boxes, and combo boxes run faster:

  • Base the list box, combo box, or drop-down list box on a saved query instead of an SQL statement. On a form, if you use a wizard to create a list box or combo box, Microsoft Access automatically sets the RowSource property of the control to an SQL statement. To change the RowSource property to a saved query, click the Build button [image] next to the RowSource property box. With the Query Builder window open, click Save on the File menu, and type a name for the query. When you close the Query Builder window, click Yes when Microsoft Access asks if you want to update the property.

  • Base the drop-down list box on a saved query instead of a table. On a data access page, if you use a wizard to create a drop-down list box, Access automatically sets the ListRowSource property of the control to the table you specified in the wizard. To retrieve rows from a query instead of a table, select the query name from the ListRowSource property box.

  • In the query specified in the RowSource or ListRowSource property box, include only fields that are absolutely necessary. Extra fields can decrease performance.

  • Index both the first field displayed in the combo box, list box, or drop-down list box and the bound field (if the fields are different).

  • In combo boxes on a form, set the AutoExpand property to No if you don't need the fill-in-as-you-type feature.

  • On a form, if the AutoExpand property for a combo box is set to Yes, the first displayed field should have a Text data type instead of a Number data type. In order to find a match in the list, Microsoft Access converts a numeric value to text. If the data type is Text, Microsoft Access doesn't have to do this conversion.

  • On a form, if the bound field in a lookup combo box is not the displayed field:
    • Don't use expressions for the bound field or the displayed field.

    • Don't use restrictions in the row source.

    • Use single-table (or query) row sources rather than multiple-table row sources, if possible.
  • Don't create list boxes, drop-down list boxes, or combo boxes based on data in a linked table if the data won't change. It's better to import the data into your database, in this case.

Note Builders are not available in a data access page. Wizards are not available in a stand-alone data access page, or when you point a data access page to a database other than the one currently open. In both cases, you will have to create a list box or drop-down list box on your own.


 Add column headings to a list box or combo box in a form

Add column headings to a list box or combo box in a form

  1. Open the form in Design view.

  2. Make sure the list box or combo box is selected, and then click Properties [image] on the toolbar to open the property sheet for the control.

  3. In the ColumnHeads property, click Yes to display column headings.

If the combo box or list box is based on a record source, Microsoft Access uses the field names from the record source as the column headings. If the combo box or list box is based on a fixed value list, Microsoft Access uses the first x items of data from the value list (RowSource property) as the column headings, where x = the number set in the ColumnCount property.

Notes

  • Headings in combo boxes appear only when the list is open.

  • For more information on creating fixed value lists by using the RowSource property, click [image] .


 Hide a column in a list box or combo box in a form

Hide a column in a list box or combo box in a form

  1. Open the form in Design view.

  2. Make sure the list box or combo box is selected, and then click Properties [image] on the toolbar to open the property sheet for the control.

  3. In the ColumnWidths property box, enter 0 for the column or columns that you want to hide.

For example, suppose you have a bound two-column combo box that has a SupplierID column and a SupplierName column. The SupplierID column is the first column in the list. To hide the SupplierID column, set the ColumnWidths property as shown in the following illustration.

Hide columns by using the ColumnWidths property

Note In a combo box, the first visible column is displayed in the text box portion of the combo box when the list isn't displayed. For example, the SupplierName column in the previous example would be displayed because the SupplierID column is hidden. If the SupplierID column weren't hidden, then it would be the only column that was displayed.


 Limit combo box entries to items in the list on a form

Limit combo box entries to items in the list on a form

  1. Open the form in Design view.

  2. Make sure the combo box is selected, and then click Properties [image] on the toolbar to open the property sheet for the combo box.

  3. In the LimitToList property box, click Yes.

Notes

  • If the first column displayed in a combo box is not the bound column, Microsoft Access limits the entries to the list even if the LimitToList property is set to No.

  • If the LimitToList property is set to No, when you enter an entry that isn't in the list, if the combo box is bound, the entry is stored in the underlying field, but it isn't added to the list. To add new entries to the list, use the OnNotInList property and the NotInList event. For more information, click [image] .


 Use an SQL statement as the row source for a list box or combo box on a form

Use an SQL statement as the row source for a list box or combo box on a form

You might want to use an SQL statement instead of a saved query for the row source of a list box or combo box on a form so that the query doesn't show up in the Database window. However, list boxes and combo boxes based on SQL statements are slower than list boxes and combo boxes based on saved queries.

  1. Open a form in Design view.

  2. Make sure the list box or combo box is selected, and then click Properties [image] on the toolbar to open the property sheet for the control.

  3. Click the Build button [image] next to the RowSource property to open the Query Builder.

  4. In the Query Builder, click SQL on the View menu.

  5. In the SQL window, select the entire SQL statement, and then press CTRL+C to copy it. Close the Query Builder.

  6. Click in the RowSource property box, and press CTRL+V to paste the SQL statement into the property box.

  7. Delete the original query in the Database window.

Notes

  • For information on properties that you can use to customize a list box or combo box, click [image] .

  • If you create a list box or combo box on a form with a wizard, Microsoft Access uses an SQL statement as the row source for the list box or combo box.


 Set the maximum number of rows to display for a combo box on a form

Set the maximum number of rows to display for a combo box on a form

  1. Open the form in Design view.

  2. Make sure the combo box is selected, and then click Properties [image] on the toolbar to open the property sheet for the combo box.

  3. In the ListRows property box, enter a number.

    If the actual number of rows exceeds the number specified in the ListRows property, a vertical scroll bar is displayed in the combo box.


 Set the width of the list box portion of a combo box on a form

Set the width of the list box portion of a combo box on a form

  1. Open the form in Design view.

  2. Make sure the combo box is selected, and then click Properties [image] on the toolbar to open the property sheet for the combo box.

  3. In the ListWidth property box, enter the desired width using the current unit of measurement (set in Windows Control Panel). To use a unit of measurement other than the default, include a measurement indicator. For example, enter 2".

Notes

  • The list box portion of the combo box can be wider than the text box portion, but it can't be narrower. The default setting (Auto) makes the list box the same width as the text box portion of the combo box.

  • When designing a combo box, leave enough space for a scroll bar.


 Turn off the fill-in-as-you-type feature of a combo box on a form

Turn off the fill-in-as-you-type feature of a combo box on a form

  1. Open the form in Design view.

  2. Make sure the combo box is selected, and then click Properties [image] on the toolbar to open the property sheet for the combo box.

  3. In the AutoExpand property box, click No.

    Note When the AutoExpand property is set to No, you must select a value from the list or type the entire value.


 Properties you can use to create or modify list boxes and combo boxes on a form

Properties you can use to create or modify list boxes and combo boxes on a form

When you use a wizard to create a list box or combo box, Microsoft Access sets certain properties for the control. You can work with these properties directly if you don't want to use a wizard to create the control, or you can use a wizard to create the control and then modify these properties to make the control work just the way you want. To find out more about any of the following properties, click the property in the property sheet and press F1.

Note If you're planning to use the bound list box or combo box on more than one form in an Access database (.mdb), you can set most of these properties in table Design view instead of using the control's property sheet. This way, you can specify the properties once. When you add the field to a form, Microsoft Access automatically creates the control based on the properties you specified.

Property | Description
RowSourceType | Works together with the RowSource property. You specify the type of row source (table/query, value list, field list, or Visual Basic function) by using this property, and then specify the actual row source in the RowSource property.
RowSource | Specifies the name of the table, query, or SQL statement if RowSourceType is set to Table/Query. Specifies the entries in the list, separated by semicolons, if RowSourceType is set to Value List. Specifies the name of the table or query if RowSourceType is set to Field List. Is blank if RowSourceType is set to a function name.
BoundColumn | In a bound multiple-column list box or combo box, specifies which column is bound to the underlying field specified in the ControlSource property. Data in that column will be stored in the field when you select that item in the list. This data may be different from the data that appears in the list if you hide the column.
ColumnCount | Specifies the number of columns in a list box or combo box. You can include a column but not display it in a list by setting the ColumnWidths property. You might want to do this if you have a list that looks up values from a table or query. You could include an ID field but hide it in the list. In a combo box, the first visible column in the list appears in the text box portion of the combo box.
ColumnWidths | Specifies the width of each column, separated by semicolons. Enter 0 to hide a column. Enter a semicolon without a measurement to use the default (about 1 in. or 2.5 cm, depending on the unit of measurement set in Windows Control Panel). In a combo box, the first visible column appears in the text box portion of the control. The data type of any value you type in the combo box must be the same as or compatible with the data type of the first visible column.
ColumnHeads | Determines whether the field names from the underlying row source for a combo box or list box are used as column headings in the combo box or list box. Headings appear in combo boxes only when the list is open.
ListWidth | Specifies the width of the list box portion of a combo box.
ListRows | Specifies the maximum number of rows to display in the list box portion of a combo box.
LimitToList | Determines whether a combo box accepts any entered text or only text that matches one of the values in the list. If you want to allow a new value that a user enters to be added to the list, set the property to No and attach an event procedure to the OnNotInList property.
OnNotInList | Runs the attached event procedure when the NotInList event occurs. You can use this property to automatically add a new value to a list. This property isn't available on the Lookup tab in table Design view.
AutoExpand | Specifies whether Microsoft Access automatically fills in a value that matches the characters that you type in a combo box. This property isn't available on the Lookup tab in table Design view.
DisplayControl | Specifies the type of control (combo box or list box) that Microsoft Access creates by default when you add a Lookup field to a form. This property is available only on the Lookup tab in table Design view.


 Properties you can use to create a multiple-column list box or combo box in a form

Properties you can use to create a multiple-column list box or combo box in a form

You can use a wizard to create a multiple-column list box or combo box. When you use a wizard, you can drag the columns in the list box or combo box to make them look just the way you want. If you want to customize a list box or combo box that was created with a wizard, however, or if you want to create a multiple-column list box or combo box on your own, you can set the following properties. For more information on any of these properties, click the property in the property sheet and press F1.

Note If you're planning to use the bound list box or combo box on more than one form, you can set these properties in table Design view instead of using the control's property sheet. This way, you can specify the properties once. When you add the field to a form, Microsoft Access automatically creates the control based on the properties you specified.

Property | Description
BoundColumn | Specifies which column is bound to the underlying field specified in the ControlSource property. Data in that column will be stored in the field when you select that item in the list. This data may be different from the data displayed in the list if you hide the column.
ColumnCount | Specifies the number of columns. You can include a column but not display it in a list by setting the ColumnWidths property. You might want to do this if you have a list that looks up values from a table or query. You could include an ID field but hide it in the list. In a combo box, the first visible column in the list is displayed in the text box portion of the combo box.
ColumnWidths | Specifies the width of each column, separated by semicolons. Enter 0 to hide a column. Enter a semicolon without a measurement to use the default (about 1 in. or 2.5 cm, depending on the unit of measurement set in Windows Control Panel).
ColumnHeads | Determines whether the list box or combo box has column headings. If the combo box or list box is based on a record source, Microsoft Access uses the field or column names from the record source as the column headings. If the combo box or list box is based on a fixed value list, Microsoft Access uses the first x items of data from the value list (RowSource property) as the column headings, where x = the number set in the ColumnCount property. Headings appear in combo boxes only when the list is dropped down.

Note If you want to display all the columns in a multiple-column list box (instead of scrolling horizontally to view them), size the control to fit the column widths.


 Properties you can use to create or modify a list box or a drop-down list box in a data access page

Properties you can use to create or modify a list box or a drop-down list box in a data access page

When you use a wizard to create a list box or a drop-down list box in a data access page, Microsoft Access sets certain properties for the control. You can work with these properties directly if you don't want to use a wizard to create the control, or you can use a wizard to create the control and then modify these properties to make the control work just the way you want. To find out more about any of the following properties, click the property in the property sheet and press F1.

Property | Description
ListRowSource | The name of a record set in the data source that supplies the values and text for the list box or drop-down list box.
ListBoundField | In a bound list box or drop-down list box, specifies which field is bound to the underlying data source specified in the ListRowSource property. Data in that column will be stored in the field when you select that item in the list.
ListDisplayField | In a bound list box or drop-down list box, specifies the name of a field in the ListRowSource that provides the display values that correspond to the ListBoundField values.


 What is a command button?

What is a command button?

You use a command button on a form or data access page to start an action or a set of actions. For example, you can create a command button that opens another form. To make a command button do something on a form, you write a macro or event procedure and attach it to the button's OnClick property. On a data access page, you can attach code written in either JScript or Microsoft Visual Basic Scripting Edition (VBScript) to a command button by using the Microsoft Script Editor. How to create an event procedure for a command button on a data access page.

Note You can create over 30 different types of command buttons with the Command Button Wizard. When you use the Command Button Wizard, Microsoft Access creates the button and the event procedure for you. Wizards aren't available in a stand-alone data access page, or when you point a data access page to a database other than the one that is currently open. The Command Button Wizard is also not available if the page isn't bound to a table or query.

Command button for running an event procedure

You can display text on a command button in a form by setting the Caption property, and display a picture on a command button by setting the Picture property. In a data access page, you can display text on a command button by using the Value property.


 Create a command button

Create a command button

You can create a command button on your own, or you can have Microsoft Access create your command button for you using a wizard. A wizard speeds up the process of creating a command button because it does all the basic work for you. When you use a wizard, Access prompts you for information, and then creates the command button based on your answers.

You can create over 30 different types of command buttons by using the Command Button Wizard. For example, you can create a command button that finds a record, prints a record, or applies a form filter.

It's also a good idea to use the Command Button Wizard if you want to learn how to write event procedures. When Access creates a command button in a form or report with a wizard, it creates an event procedure and attaches it to the button. You can open the event procedure to see how it works and modify it to fit your needs. When you create a command button on a data access page with a wizard, Access doesn't create event procedures for you. Learn about creating event procedures for a command button on a data access page.

Note Wizards are not available in a stand-alone data access page, or when you point a data access page to a database other than the one currently open. The Command Button Wizard is also not available if a data access page isn't bound to a table or query. You will have to create a command button on your own if wizards aren't available.

What do you want to do?

Create a command button with a wizard

Create a command button on my own


 Make a command button on a form a Cancel button

Make a command button on a form a Cancel button

  1. Open a form in Design view.

  2. Click the command button, and then click Properties [image] on the toolbar to open the command button's property sheet.

  3. In the Cancel property box, click Yes.

When a command button's Cancel property is set to Yes and the form is the active form, you can choose the command button by clicking it, pressing the ESC key, or pressing ENTER when the command button has the focus. When the Cancel property is set to Yes for one command button, it's automatically set to No for all other command buttons on the form. Only one button can be the default on a form.

To have a Cancel button cancel all the actions that have taken place in a form or dialog box, you need to write a macro or event procedure and attach it to the OnClick property of the button.

Tip For a form that allows 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.


 Make a command button the default button in a form or custom dialog box

Make a command button the default button in a form or custom dialog box

  1. Open a form in Design view.

  2. Click the command button, and then click Properties [image] on the toolbar to open the command button's property sheet.

  3. In the Default property box, click Yes.

When a command button's Default property is set to Yes and the form is the active form, you can choose the command button by clicking it or by pressing ENTER when no other command button has the focus. When the Default property is set to Yes for one command button, it's automatically set to No for all other command buttons on the form. Only one button can be the default on a form.

Tip For a form that allows 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.


 Hide a command button on a form

Hide a command button on a form

  1. Open a form in Design view.

  2. Click the command button, and then click Properties [image] on the toolbar to open its property sheet.

  3. In the Transparent property box, click Yes.

    Microsoft Access hides the command button, but it's still active.

Tip To hide and disable a button, set the Visible property to No. To disable a button without hiding it, set the Enabled property to No. To hide a button only when a form is printed, set the DisplayWhen property to Screen Only.


 Hide a command button on a data access page

Hide a command button on a data access page

  1. Open a data access page in Design view.

  2. Click the command button, and then click Properties [image] on the toolbar to open its property sheet.

  3. Set the Visibility property to Hidden.

Tip To disable a button without hiding it, set the Disabled property to True.


 Add a picture to a command button or a toggle button in a form

Add a picture to a command button or a toggle button in a form

  1. Open a form in Design view.

  2. Click the command button or toggle button, and then click Properties [image] on the toolbar to open its property sheet.

  3. In the Picture property box, type the path and file name for a .bmp, .ico, or .dib file. If you're not sure of the path or file name, click the Build button [image] to open the Picture Builder.

Tip If you want to add a picture and a caption to a command button, you can create the picture and caption in Microsoft Windows Paint. To create a picture the size of your button using Paint, draw the picture on a background of any size, and then select only the portion that will fit on your button. On the Edit menu, click Copy To and specify a file name in the Save As dialog box. This creates a file with a picture of the exact size that you selected.


 See an event procedure created by the Command Button Wizard

See an event procedure created by the Command Button Wizard

The following procedure describes how to display an event procedure created by the Command Button Wizard on a form. In a data access page, you have to create the event procedure yourself.

  1. In form Design view, right-click the command button created by the Command Button Wizard.

  2. On the shortcut menu, click Build Event.


 Create an event procedure for a command button on a data access page

Create an event procedure for a command button on a data access page

  1. In data access page Design view, right-click the command button.

  2. On the shortcut menu, click Microsoft Script Editor.

  3. In the Script Outline window, double-click the command button.

  4. Double-click the OnClick event.


 Create a command button that finds a record

Create a command button that finds a record

  1. Open a form in Design view or a data access page in Design view.

  2. Click the Control Wizards tool [image] in the toolbox if it's not already pressed in.

  3. In the toolbox, click the Command Button tool Command Button control .

  4. On the form or data access page, click where you want to place the command button.

  5. In the first wizard dialog box, click Record Navigation in the Categories box, and then, in the Actions box, click the type of button that you want to create.

  6. Follow the directions in the wizard dialog boxes. In the last dialog box, click Finish to display the command button in Design view.

Notes

  • If you want to see the event procedure that makes the button work on a form, click the Build button [image] in the OnClick property for the command button. On a data access page, you can attach code written in either JScript or Microsoft Visual Basic Scripting Edition (VBScript) to a command button by using the Microsoft Script Editor. How to create an event procedure for a command button on a data access page.

  • Wizards aren't available in a stand-alone data access page, or when you point a data access page to a database other than the one that is currently open. The Command Button Wizard is also not available if the page isn't bound to a table or query.


 Create a command button that edits or applies a filter on a form

Create a command button that edits or applies a filter on a form

  1. Open a form in Design view.

  2. Click the Control Wizards tool [image] in the toolbox if it's not already pressed in.

  3. In the toolbox, click the Command Button tool Command Button control .

  4. On the form, click where you want to place the command button.

  5. In the first wizard dialog box, click Form Operations in the Categories box, and then, in the Actions box, click the type of button that you want to create.

  6. Follow the directions in the wizard dialog boxes. In the last dialog box, click Finish to display the command button in Design view.

If you want to see the event procedure that makes the button work, click the Build button [image] in the OnClick property for the command button.


 Create a command button to open and synchronize, close, or print a form

Create a command button to open and synchronize, close, or print a form

  1. Open a form in Design view.

  2. Click the Control Wizards tool [image] in the toolbox if it's not already pressed in.

  3. In the toolbox, click the Command Button tool Command Button control .

  4. On the form, click where you want to place the command button.

  5. In the first wizard dialog box, click Form Operations in the Categories box, and then, in the Actions box, click the type of button that you want to create.

  6. Follow the directions in the wizard dialog boxes. In the last dialog box, click Finish to display the command button in Design view.

If you want to see the event procedure that makes the button work, click the Build button [image] in the OnClick property for the command button.


 Create a command button that updates form data

Create a command button that updates form data

If you're using a database that's shared on a network, you can view the latest version of existing records by creating a command button that updates form data. If you want to display all the updated records, including new ones, you can requery the records. For more information about requerying records, click [image] .

  1. Open a form in Design view.

  2. Click the Control Wizards tool [image] in the toolbox if it's not already pressed in.

  3. In the toolbox, click the Command Button tool Command Button control .

  4. On the form, click where you want to place the command button.

  5. In the first wizard dialog box, click Form Operations in the Categories box, and then, in the Actions box, click the type of button that you want to create.

  6. Follow the directions in the wizard dialog boxes. In the last dialog box, click Finish to display the command button in Design view.

If you want to see the event procedure that makes the button work, click the Build button [image] in the OnClick property for the command button.


 Create a command button that prints or mails a report

Create a command button that prints or mails a report

  1. Open a form in Design view.

  2. Click the Control Wizards tool [image] in the toolbox if it's not already pressed in.

  3. In the toolbox, click the Command Button tool Command Button control .

  4. On the form, click where you want to place the command button.

  5. In the first wizard dialog box, click Report Operations in the Categories box, and then, in the Actions box, click the type of button that you want to create.

  6. Follow the directions in the wizard dialog boxes. In the last dialog box, click Finish to display the command button in Design view.

If you want to see the event procedure that makes the button work, click the Build button [image] in the OnClick property for the command button.


 Create a command button on a form that prints a table

Create a command button on a form that prints a table

  1. Open a form in Design view.

  2. Click the Control Wizards tool [image] in the toolbox if it's not already pressed in.

  3. In the toolbox, click the Command Button tool Command Button control .

  4. On the form, click where you want to place the command button.

  5. In the first wizard dialog box, click Miscellaneous in the Categories box, and then click Print Table in the Actions box.

  6. Follow the directions in the wizard dialog boxes. In the last dialog box, click Finish to display the command button in Design view.

If you want to see the event procedure that makes the button work, click the Build button [image] in the OnClick property for the command button.


 Create a command button on a form that runs or quits an application

Create a command button on a form that runs or quits an application

  1. Open a form in Design view.

  2. Click the Control Wizards tool [image] in the toolbox if it's not already pressed in.

  3. In the toolbox, click the Command Button tool Command Button control .

  4. On the form, click where you want to place the command button.

  5. In the first wizard dialog box, click Application in the Categories box, and then, in the Actions box, click the type of button you that want to create.

  6. Follow the directions in the wizard dialog boxes. In the last dialog box, click Finish to display the command button in Design view.

If you want to see the event procedure that makes the button work, click the Build button [image] in the OnClick property for the command button.


 Create a command button on a form that runs a query or a macro

Create a command button on a form that runs a query or a macro

  1. Open a form in Design view.

  2. Click the Control Wizards tool [image] in the toolbox if it's not already pressed in.

  3. In the toolbox, click the Command Button tool Command Button control .

  4. On the form, click where you want to place the command button.

  5. In the first wizard dialog box, click Miscellaneous in the Categories box, and then, in the Actions box, click the type of button that you want to create.

  6. Follow the directions in the wizard dialog boxes. In the last dialog box, click Finish to display the command button in Design view.

If you want to see the event procedure that makes the button work, click the Build button [image] in the OnClick property for the command button.


 Create a command button on a form that dials a phone number

Create a command button on a form that dials a phone number

  1. Open a form in Design view.

  2. Click the Control Wizards tool [image] in the toolbox if it's not already pressed in.

  3. In the toolbox, click the Command Button tool Command Button control .

  4. On the form, click where you want to place the command button.

  5. In the first wizard dialog box, click Miscellaneous in the Categories box, and then click AutoDialer in the Actions box.

  6. Follow the directions in the wizard dialog boxes. In the last dialog box, click Finish to display the command button in Design view.

If you want to see the event procedure that makes the button work, click the Build button [image] in the OnClick property for the command button.


What is a tab control?

You can use a tab control to present several pages of information as a single set. This is especially useful when you're working with many controls that can be sorted into two or more categories. For example, you might use a tab control on an Employees form to separate general and personal information.

Tab control with two tabs

For information on creating a tab control, click [image] .


Create a form with multiple pages or tabs

What do you want to do?

Use a tab control to create a multiple-page form

Use a page break control to create a multiple-page form

Not sure which choice you want?


 Add a tab control to a form to create a multiple-page form

Add a tab control to a form to create a multiple-page form

  1. Open a form in Design view.

  2. In the toolbox, click the Tab Control tool [image] and then click the form where you want to place the control.

    Microsoft Access adds a tab control with two pages. The first page is on top.

  3. To add controls to the tab control, click the tab of the page you want to add controls to. Then add controls using any of the following methods:
    • Click Field List [image] on the toolbar to display the field list and drag one or more fields to the tab page.

    • Click a tool in the toolbox and click on the tab page. You can add any type of control except another tab control.

    • Copy controls from another part of the form or from another page. (However, you can't drag controls from another part of a form or from another page.)
  4. Use the following list for other tasks you might want to perform:
    • To change the caption displayed on a tab, double-click the tab to open its property sheet, and then specify a new caption in the Caption property. If you don't specify a caption in the Caption property, Microsoft Access uses the setting in the Name property.

    • To add, delete, or change the order of tabs, click the border of the tab control with the right mouse button and click Insert Page, Delete Page, or Page Order.

    • To change the tab order of controls on a page, click the page with the right mouse button and click Tab Order.

    • To change the font name, font size, font style, and so on, of the captions on tabs, double-click the border of the tab control to open its property sheet and then set the appropriate properties. You can't specify different settings for different tabs.
  5. Size the tab control as appropriate. Click each tab to make sure all the controls fit well within each tab.

    Note Microsoft Access won't crop controls when you size the tab control. You may need to move controls to make the tab control smaller.

  6. Switch to Form view to test the control.

Notes

  • For information on other properties you might want to set for a tab control, click [image] .

  • To see an example of a tab control, see the Employees form in the Northwind sample database. For information on opening the Northwind database, click [image] .


 Properties you can use to customize a tab control

Properties you can use to customize a tab control

You can use the following properties to customize a tab control to make it look just the way you want.

Property | Description | Where set
Caption | Specifies the display text that appears on a tab. If you don't specify a caption in the Caption property, Microsoft Access uses the name in the Name property. | Property sheet for the page in a tab control
MultiRow | Specifies whether a tab control can have more than one row of tabs. If the MultiRow property is set to No, Microsoft Access truncates the tabs if they exceed the width of the tab control and adds a scroll bar. | Property sheet for the tab control
Style | Specifies what to display at the top of the tab control. You can display tabs, command buttons, or nothing. You may want to display nothing if you want to use a command button on the form outside the tab control to determine which page has the focus. For more information on the Style property, click [image] . | Property sheet for the tab control
TabFixedHeight | The height of tabs in the unit of measurement specified in Windows Control Panel. If the value is 0, each tab will be high enough to fit its contents. | Property sheet for the tab control
TabFixedWidth | The width of tabs in the unit of measurement specified in Windows Control Panel. If the value is 0, each tab will be wide enough to fit its contents and, if there is more than one row of tabs, the width of each tab will be increased so that each row of tabs spans the width of the tab control. If the value is greater than zero, all tabs have an identical width as specified by this property. | Property sheet for the tab control
Picture | Use to add a graphic to a tab. (Tab controls can contain bitmaps but not Windows metafiles.) The graphic is displayed to the left of the text specified in the Caption property. If you just want to display a picture and no text, enter a SPACEBAR space in the Caption property. | Property sheet for the page in a tab control

Notes

  • To display the property sheet for a tab control, double-click the edge of the tab control. To display the property sheet for a page in a tab control, double-click the tab for the page.

  • If you're going to use a tab control in a custom dialog box, you may want to set additional properties. For information on properties you can set for a custom dialog box, click [image] .


 What is a toggle button in forms and reports?

What is a toggle button in forms and reports?

You can use a toggle button on a form as a stand-alone control to display a Yes/No value from an underlying record source. For example, the toggle button in the following illustration is bound to the Discontinued field in the Products table of a database. The data type of the Discontinued field is Yes/No. When the button is pressed in, the value in the Products table is Yes. When the button isn't pressed in, the value in the Products table is No.

Toggle button indicates Yes/No, True/False, or On/Off conditions

When you click a toggle button that's bound to a Yes/No field in a Microsoft Access database, the value in the underlying table displays according to the field's Format property (Yes/No, True/False, or On/Off). In a Microsoft Access project, the option button is bound to a column defined as a Bit data type. When the value in this column is 1, it is equivalent to Yes, On or True conditions. When the value is 0, the column indicates No, Off, or False conditions.

Toggle buttons are most useful when used in an option group with other buttons. In an option group, you can easily tell whether a button is pressed in. For more information on option groups, click [image] .

You can use pictures on toggle buttons instead of text. For example, instead of displaying the word "Discontinued" on the toggle button in the first example, you could display a picture of a trash can.

Examples of toggle buttons pressed in and not pressed in

You can also use a toggle button in a custom dialog box to accept user input.


 What is a PivotTable form?

What is a PivotTable form?

A PivotTable form is an interactive table that performs the calculations you choose, such as sums (the default for numeric fields) and counts (the default for text fields), based on how the data is arranged in the PivotTable form. For example, a PivotTable form can display a field's values horizontally or vertically, and then calculate the total of the row or column. It can also use a field's values as row or column headings, calculating individual amounts at the intersection of each row and column heading, and then calculating subtotals and grand totals. For example, to analyze sales by product category for each employee, you can list employee names as column headings across the top of the PivotTable form, product categories as row headings down the side of the PivotTable form, and the sales amount calculated by product category for each employee at the intersection of each row and column.

You can limit the records that the PivotTable form uses by designating a field as a page field — which becomes a drop-down list that works as a filter above the PivotTable form. The value you select from the list determines which records are displayed in the PivotTable form. For example, you could use the City field from the Employees table as a page field to view the sales performance by product category of just the sales representatives in London. The Sales Analysis form in the Northwind sample database has an example of a PivotTable form. To view this PivotTable form, open the Northwind database in your Office folder’s Samples subfolder, and then open the Sales Analysis form in Design view.

PivotTable forms are so named because you can dynamically change their layouts to analyze the data in different ways. You can rearrange row headings, column headings, and page fields until you achieve the desired layout. Each time you change the layout, the PivotTable form immediately recalculates the data based on the new arrangement. In addition, as source data changes, you can update the PivotTable form.

You create a PivotTable form in Microsoft Access by using the PivotTable Wizard. The wizard uses Microsoft Excel to create the PivotTable object and Microsoft Access to create a form in which it embeds the PivotTable object. For information on using the wizard, click [image] .

Each time you open a PivotTable form, the PivotTable form shows you the data that was current the last time you activated the PivotTable form. To display the most current data in the PivotTable form, you need to update the data. For more information, click [image] .


 Edit a PivotTable form

Edit a PivotTable form

Because a PivotTable form is an embedded Microsoft Excel object, you modify it by going to the Microsoft Access form where the PivotTable object is embedded, and then starting and using Microsoft Excel to edit the data.

  1. Open the PivotTable form in Form view.

  2. Click the Edit PivotTable Object button.

    Note If you prefer to use in-place editing instead of editing the PivotTable form in a separate Microsoft Excel window, point to Worksheet Object on the Edit menu in Microsoft Access, and then click Edit.

  3. On the Data menu in Microsoft Excel, click Refresh Data.

  4. Make the changes you want to the PivotTable form.

    Note For help on specific ways you can modify or otherwise work with the PivotTable form, use Microsoft Excel Help.

  5. When you're done editing the PivotTable form, click Exit on the File menu in Microsoft Excel.

Notes

  • If you don't find the answer you need in the Microsoft Excel Help topics, you can use Microsoft Access Help when the PivotTable form is open in Form view in Microsoft Access. If you're using in-place editing, you must first click any place on the Access form outside the PivotTable object to get Microsoft Access Help.

  • The source data that the PivotTable form uses isn't automatically saved with the PivotTable form. Instead, you must update the PivotTable form with the most current data each time you want to use it, which means you'll need access to the location where the data is stored. If you know that you'll need to edit the PivotTable form later on when you won't have access to the data, save the data with the PivotTable form. For more information, click [image] .


 Update the data in a PivotTable form

Update the data in a PivotTable form

  1. Open the PivotTable form in Form view.

  2. Click the Edit PivotTable Object button.

  3. On the Data menu in Microsoft Excel, click Refresh Data.


 Show or hide a text box or other control on a data access page

Show or hide a text box or other control on a data access page

  1. Open a data access page in Design view.

  2. Select the control you want to show or hide, and then click Properties [image] on the toolbar to open its property sheet.

  3. Do one of the following:
    • To have the control inherit the visibility setting from the section in which it is placed, in the Visibility property box, click Inherit.

    • To make the control invisible, in the Visibility property box, click Hidden.

    • To display the control on the data access page, in the Visibility property box, click Visible.

Note If the control has an associated label, the visibility of the label must be set separately from the control.


 Delete an option button or other control from an option group in a data access page

Delete an option button or other control from an option group in a data access page

You can delete one or more option buttons from an option group control in data access page Design view.

  • Click the control that you want to delete, and then press the DEL key.


 Disable a control or make data in a text box or other control read-only in a data access page

Disable a control or make data in a text box or other control read-only in a data access page

  1. Open a data access page in Design view.

  2. Select the control you want to disable, and then click Properties [image] on the toolbar to open its property sheet.

  3. To prevent users from changing the data, set the ReadOnly property to True.

Note If you don't want a control in the tab order, but you want to be able to select that control, set its TabIndex property to -1.


 Add an expand control to a data access page

Add an expand control to a data access page

  1. Open the data access page in Design view.

  2. Click Expand [image] in the toolbox.

  3. Click in the group header where you want the expand control.

  4. Specify whether you want the records in the next lower group level expanded or collapsed by default.


 Delete an expand control from a data access page

Delete an expand control from a data access page

  1. Open the data access page in Design view.

  2. Make sure the expand control that you want to delete is selected.

  3. Press DELETE.

Note When you delete the expand control for a group header, Microsoft Access automatically sets that group's ExpandedByDefault property in the Sorting And Grouping box to Yes. When ExpandedByDefault is set to Yes for a group level, and that level is the highest group level on the page, then all the records in the next lower group level will be displayed when you open the page in Page view or in Microsoft Internet Explorer. As a result, it may take longer for the page to be loaded. If you set the ExpandedByDefault property to No, you won't be able to see the records in the next lower group level.


 Add a record navigation control to a data access page

Add a record navigation control to a data access page

When you add a record navigation section to a group level, Microsoft Access automatically adds a record navigation control. Use this procedure for a group level that has a record navigation section but doesn't have the record navigation control.

  1. Open the data access page in Design view.

  2. Click Record Navigation Record Navigation control in the toolbox.

  3. Click the record navigation section where you want the record navigation control.

  4. Specify the number of records you want to display for this group level when you open the page in Page view or in Microsoft Internet Explorer

Note You can set properties to customize a record navigation control. For example, on a grouped page, you can hide the buttons that add and delete records.


 Customize a record navigation control on a data access page

Customize a record navigation control on a data access page

  1. Open the data access page in Design view.

  2. Make sure that the record navigation control is selected. and then click Properties [image] on the toolbar.

  3. Type values for the following properties to change them:
    • In the RecordsetLabel property, modify the strings as needed. For example, the RecordsetLabel property for a Products group level could be set to Products |0 of |2;Products |0-|1 of |2. The first string (before the semicolon (;)) represents the label that is displayed when one record is displayed on the page in Page view or in Microsoft Internet Explorer. The second string (after the semicolon) represents the label that is displayed when two or more records are displayed on the page. |0 indicates the number of the current record on a page used for data entry or the number of the first visible record in the group on a grouped page; |1 indicates the number of last visible record in the group on a grouped page; and |2 indicates the number of records in the recordset.

    • In the RecordSource property, type the name of the table or query for the group level.
  4. Set any of the following properties to True to show a button or label, or to False to remove a button or label. In Page view or in Internet Explorer, these buttons have the following functions:
    • ShowDelButton [image] Deletes a record

    • ShowFilterBySelectionButton [image] Filters for records that match the selected field

    • ShowFirstButton [image] Moves to the first record

    • ShowHelpButton [image] Displays Help

    • ShowLabel Displays the information that is specified in the RecordsetLabel property

    • ShowLastButton [image] Moves to the last record

    • ShowNewButton [image] Moves to a new record

    • ShowNextButton [image] Moves to the next record

    • ShowPrevButton [image] Moves to the previous record

    • ShowSaveButton [image] Saves the current record

    • ShowSortAscendingButton [image] Sorts records in ascending order

    • ShowSortDescendingButton [image] Sorts records in descending order

    • ShowToggleFilterButton Filter object Applies or removes a filter

    • ShowUndoButton [image] Undoes the last record


 Delete a record navigation control from a data access page

Delete a record navigation control from a data access page

  1. Open the data access page in Design view.

  2. Select the record navigation control you want to delete by clicking it.

  3. Press DELETE.

Notes

  • After you delete a record navigation control, you should also delete the record navigation section.

  • When you delete a group level's record navigation control or record navigation section, Microsoft Access automatically changes the DataPageSize property for the group to All. If you delete the record navigation control or section for the highest group level, all the records in that group level will be displayed when you open the page in Page view or in Microsoft Internet Explorer. As a result, it might take longer to load a page.


 What is a scrolling text control on a data access page?

What is a scrolling text control on a data access page?

You use a scrolling text control, often called a marquee, on a data access page to display moving text or text that scrolls. Scrolling text draws attention to a line of text, such as a headline or an important announcement. You display text that is contained in a field of your database by binding the scrolling text control to the field. You can customize scrolling text by setting options such as direction of travel, speed, and type of motion.

To see how the text moves in the scrolling text control, view it in Page view.

More information

Work with scrolling text


Work with scrolling text on a data access page

What do you want to do?

Create a bound scrolling text control that displays data

Create an unbound scrolling text control

Change the motion of the scrolling text

Change the number of times the text scrolls

Change the speed of the scrolling text

Change the direction of scrolling text

Not sure which choice you want?


 Should I use a bitmap, metafile, or other graphic file to display a picture?

Should I use a bitmap, metafile, or other graphic file to display a picture?

You can use bitmap files (.bmp or .dib extensions), metafiles (.wmf or .emf extensions), or other graphic files such as GIF and JPEG to display background pictures or pictures in bound object frames, unbound object frames, or image controls.

When to use metafiles

  • If you need to adjust the size of your picture, it's better to use a metafile. Metafiles scale better than bitmaps because they're made up of collections of lines rather than patterns of individual dots.

  • Metafiles are usually much smaller than bitmaps, so if you need to conserve disk space, use a metafile.

Many graphics programs allow you to save files as metafiles. See the documentation that came with your graphics program for details. Note that if you paste a bitmap into a graphics program and save it as a metafile, it will still be a bitmap — it's just embedded in the metafile. You must create the graphic in the graphics program and save it as a metafile.

When to use bitmaps

  • If scaling and disk space aren't concerns, or if you don't have access to a tool that creates metafiles, use a bitmap.

  • If you want to create a tiled background picture, a bitmap will work well because it won't be scaled.

  • If you want to be able to make small changes to the picture, use a bitmap. With bitmaps you have pixel-level control, so that you can make very small adjustments to the picture.

Notes

  • In forms and reports, if you need to adjust the size of a picture, set the PictureSizeMode property (background pictures) or the SizeMode property (bound object frames, unbound object frames, and image controls) to Zoom. When you set the PictureSizeMode or SizeMode property to Zoom, Microsoft Access retains the proportions of the picture when you size the form or control.

  • In a data access page, use the Height and Width properties to adjust the size of a picture. In the Height and Width property boxes, enter values in pixels (px), points (pt), centimeters (cm) or inches (in). For instance, if you type 25px in the Height property box, the image will be 25 pixels high.

  • Learn about other graphics file formats you can use with Microsoft Access.


 Add an unbound picture to a form, report, or data access page by using an image control

Add an unbound picture to a form, report, or data access page by using an image control

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the Image tool Image frame control in the toolbox.

  3. On the form, report, or data access page, click where you want to place the picture.

  4. In the Insert Picture dialog box, click the file name for the picture that you want to add. You may need to use the Look In box to specify the drive and/or folder where the picture is located.

  5. Click OK.

    Microsoft Access creates an image control and displays the picture in the control.

Notes

  • You can adjust the size and proportions of the picture.

    How?

  • When you add a picture to an image control, Microsoft Access inserts the picture in a form or report by default. In a form or report, when a picture is inserted, it becomes part of the database file. If you plan to use the same picture on several forms and reports, you may want to link to the picture instead of inserting it. When you link to a picture, you only store the picture once. To link to a picture in a form or report, set the PictureType property for the image control to Linked.

  • When you add a picture in a data access page, the picture is added to the supporting files that accompany the data access page. If you plan to use the same picture on several different data access pages, you may want to link to the picture instead of inserting it.


 Adjust the size and proportions of a picture on a form or report

Adjust the size and proportions of a picture on a form or report

How you adjust the size and proportions of a picture depends on whether it's a background picture (watermark) or a picture that uses an image control, unbound object frame, or bound object frame.

What do you want to do?

Adjust the size of a background picture

Adjust the size of a picture displayed in an image control, unbound object frame, or bound object frame


 Add a background picture to a form

Add a background picture to a form

  1. Open a form in Design view.

  2. Double-click the form selector to open the property sheet.

  3. In the Picture property box, type the path and file name for a .bmp, .ico, .dib, .wmf, or .emf file. If you've installed graphics filters for other applications, you can use any file supported by those filters. If you're not sure of the path or file name, click the Build button [image] .

  4. In the PictureType property box, specify whether you want the picture to be embedded or linked. When you embed a picture, it's stored in the database file. If you embed the same picture in another form, it's added to the database file again. When you link a picture, you don't store it in the database file, but you must keep a copy of it on your hard disk. If you want to use your hard disk space efficiently, specify the Linked setting.

  5. After you add the picture to the form, you can size or clip it by clicking one of the following settings in the PictureSizeMode property box.
    Setting | Description
    Clip | Displays the picture at actual size. If the picture is larger than the Form window, the image is cut off.
    Stretch | Sizes the picture to fit the Form window. This setting may distort the image.
    Zoom | Sizes the picture to fill either the height or width of the Form window. This setting won't clip the picture or distort its proportions.
  6. If you want to change the alignment of the picture, click one of the settings in the PictureAlignment property box.

    Note If you want to center the background picture, and you want the background picture to resize when you size the window, click the Center setting. If you don't want the background picture to resize when you size the window, click the Form Center setting.

  7. If you want to repeat the picture across the background of the form, set the PictureTiling property to Yes. Tiling starts at the position that is specified in the PictureAlignment setting.

    Note Set the PictureSizeMode property to Clip if you want to tile the background picture. The background picture will not be tiled if the PictureSizeMode property is set to Zoom or Stretch.

Notes

  • If the colors in your picture don't look the same as the original colors, you can specify that Microsoft Access use the colors from the application you used to create the picture.

    How?

  • If you're creating your own background pictures and you have access to a graphics program that creates metafiles, you may want to use a metafile rather than a bitmap as a background picture. For more information, click [image] .


 Reconnect a link to a picture on a form or report

Reconnect a link to a picture on a form or report

You may lose a link to a picture if you rename or move the picture. How you reconnect the link depends on whether it's a picture in a bound object frame or unbound object frame, a picture in an image control, or a background picture (watermark).

Note This type of link is different from a hyperlink used on a form or report to jump to another document, object, or page. For more information on hyperlinks, click [image] .

What do you want to do?

Reconnect a link to a picture in a bound or unbound object frame

Reconnect a link to a picture in an image control

Reconnect a link to a background picture


 Reconnect a link to an object on a form or report

Reconnect a link to an object on a form or report

You may lose a link to an object if you rename or move the linked object.

Note This type of link is different from a hyperlink that is used on a form or report to jump to another document, object, or page. For more information on hyperlinks, click [image] .

  1. Do one of the following:
    • If the object is unbound, click the object in form or report Design view.

    • If the object is bound, open the form in Form view (or open a datasheet), find the record you want to change, and click the object.
  2. On the Edit menu, click OLE/DDE Links.

  3. In the Links box, click the link you want to reconnect or change.

  4. Click Change Source.

  5. In the Change Source dialog box, select the new file name. You may need to switch to a different drive and/or folder to find the appropriate file.

  6. Click Open to complete the link and close the Change Source dialog box, and then click Close in the Links dialog box.

Note When you make any changes to a link for a bound object frame, you are changing the link only for the current record. To make a change in a different record, move to that record and repeat the process.


 Add an image control to a data access page

Add an image control to a data access page

  1. Open a data access page in Design view.

  2. In the toolbox, click the Image tool Image frame control .

  3. Click Field List [image] on the toolbar to display the field list.

  4. From the field list, drag the field that contains a path to an image to the data access page. Place the upper-left corner of the icon where you want the upper-left corner of the image to be, and release the mouse button.

  5. Size the image control. How to adjust the size of a picture displayed in an image control.


 About working with graphics on a data access page

About working with graphics on a data access page

This topic provides reference information about:

Inserting graphics from a file

Aligning graphics

More information

Inserting graphics from a file

When you insert a graphic from a file you can either insert the entire graphic by copying and pasting it from another location, or you can insert a link to the graphic at a fixed location, such as another Web server or to a relative file location. Linking a graphic to your data access page reduces the size of the page, makes it easier to update the graphic, and makes it easier to share the graphic between different data access pages. In Windows, if you move or copy a data access page to another location, make sure that you also move or copy any supporting files — such as graphics, background textures, and bullets — so that you maintain the graphic links to your page.

Return to top

Aligning graphics

The Alignment and Sizing toolbar in data access page Design view provides alignment commands that help you arrange your graphics.

Return to top

More information

Add a picture or other object to a data access page

Add an ActiveX control (OLE custom control) to a data access page

Return to top


 Display alternate text for a picture on a data access page

Display alternate text for a picture on a data access page

You may want to add alternate text to a picture; if the user has graphics turned off in the Web browser, or the user has a screen reader, the alternate text will be displayed in place of the picture.

  1. Open a data access page in Design view.

  2. Select the image control, and then click Properties [image] on the toolbar to display the control’s property sheet.

  3. In the Alt property box, type the text that you want to be displayed.


 Delete an unbound picture on a data access page

Delete an unbound picture on a data access page

  1. Open a data access page in Design view.

  2. Click the image control.

  3. Press the DELETE key.


 What is an expression?

What is an expression?

Expressions are a fundamental part of many Microsoft Access operations. An expression is a combination of symbols — identifiers, operators, and values — that produces a result.

For example, you can use the following expression in a control on a form or report to display the sum of the values in the Subtotal and Freight controls:

= [Subtotal] + [Freight]

Here are a few common examples of operations where you use expressions:

  • Setting a property that defines a calculated control, establishes a validation rule, or sets a default field value.

  • Entering a criteria expression, creating a calculated field, or updating records in a query or filter.

  • Setting a condition for carrying out an action or series of actions in a macro, or specifying arguments for many actions.

  • Specifying arguments for many functions, statements, and methods in Visual Basic for Applications procedures.

  • Editing an SQL query in SQL view of the Query window, or using an SQL statement in a property setting or argument.

For information on creating an expression, click [image] .

To see examples of expressions, click [image] .


Create an expression using the Expression Builder

  1. Start the Expression Builder.

    How?

  2. In the lower-left box of the Expression Builder, double-click or click the folder containing the element you want.

  3. In the lower-middle folder, double-click an element to paste it into the expression box, or click a category of elements.

  4. If you select a category in the lower-middle box, values display in the lower-right box. Double-click a value to paste it in the expression box.

    Tip You can also type any part of the expression directly in the expression box.

  5. Paste any operators you want in the expression by placing the insertion point in the expression box where you want the operator, and clicking one of the operator buttons that are in the middle of the builder.

  6. When your expression is complete, click OK.

Microsoft Access copies your expression to the location where you started the Expression Builder. If that location already contains a value, your new expression replaces the value or text.

For more information about the Expression Builder, click [image] .


Use the Expression Builder

What do you want to do?

Read about the Expression Builder

Start the Expression Builder

Create an expression using the Expression Builder

See examples of expressions

Read more about expressions


 About the Expression Builder

About the Expression Builder

The Expression Builder has three sections:

Create an expression by selecting database objects, elements, and values from the lists

  • In the upper section of the builder is an expression box where you build the expression. Use the lower section of the builder to create elements of the expression, and then paste these elements into the expression box to form an expression. You can also type parts of the expression directly into the expression box.

  • In the middle section of the builder are buttons for commonly used operators. If you click one of the operator buttons, the Expression Builder inserts the operator at the insertion point in the expression box. For a complete list of operators you can use in expressions, click the Operators folder in the lower-left box and the appropriate operator category in the middle box. The right box lists all operators in the selected category.

  • In the lower section of the builder are three boxes:
    • The left box contains folders that list the table, query, form, and report database objects, built-in and user-defined functions, constants, operators, and common expressions.

    • The middle box lists specific elements or categories of elements for the folder selected in the left box. For example, if you click Built-In Functions in the left box, the middle box lists categories of Microsoft Access functions.

    • The right box lists the values, if any, for the elements you select in the left and middle boxes. For example, if you click Built-In Functions in the left box and a category of functions in the middle box, the right box lists all built-in functions in the selected category.

Notes

  • In order to view new field names in the Expression Builder, you must first save the table or query containing the new fields.

  • If an object or function isn't listed in the lower section of the Expression Builder, it's not valid in the context where you started the builder. For example, you can't refer to other fields and controls in the validation rule for a field in table Design view, so the Tables, Queries, Forms, and Reports folders aren't available if you start the Expression Builder from the ValidationRule property of a field in table Design view.

  • When you paste an identifier in your expression, the Expression Builder pastes only the parts of the identifier that are required in the current context. For example, if you start the Expression Builder from the property sheet of the Customers form, and then paste an identifier for the Visible property of the form in your expression, the Expression Builder pastes only the property name: Visible. If you use this expression outside the context of the form, you must include the full identifier: Forms![Customers].Visible.


 Start the Expression Builder

Start the Expression Builder

You can start the Expression Builder from most places where you write expressions, such as in a property sheet, a Criteria cell in the query design grid, or the Macro window.

What do you want to do?

Start the Expression Builder in a property sheet or the lower pane of the Macro window

Start the Expression Builder in the query design grid or a macro condition


 Enter expressions in a property sheet, a design grid, or an action argument

Enter expressions in a property sheet, a design grid, or an action argument

If you are entering an expression that is longer than the standard input area in a property sheet, a design grid, or an action argument, you can type the expression in the Zoom box. To open the Zoom box, press SHIFT+F2 when the focus is where you want to enter the expression.

When you enter an expression in a property sheet, a design grid, or an action argument, Microsoft Access:

  • Recognizes region-specific function names, property names, and list separators for international versions.

  • Inserts certain characters for you when the focus changes. Depending on where you enter the expression, Microsoft Access automatically inserts:
    • Brackets ([ ]) around form, report, field, or control names.

    • Number signs (#) around dates.

    • Double (") quotation marks around text.

Note Calculated control expressions are always preceded by an equal sign (=).

Using functions and properties in international versions of Microsoft Access

When you enter a function or property in an expression in most international versions of Microsoft Access:

  • You can type its localized name (in your language) in a property sheet, a design grid, or an action argument.

  • You can use the list separator for your country when you specify more than one argument for a function. You specify the list separator on the Number tab of the Regional Settings Properties dialog box in Windows Control Panel. For most international versions, the default list separator is a semicolon (;).

However, in Visual Basic for Applications code, you must type the English function or property name and use a comma (,) as a list separator.

Entering object names

Brackets ([ ]) around a field, control, or property in an identifier indicate that the element is the name of a table, query, form, report, field, or control.

When you type an object name in an identifier, you surround the name with brackets if it contains a space or a special character, such as an underscore. If the name doesn't contain a space or a special character, you can type the name without brackets. Microsoft Access inserts brackets automatically (with two exceptions noted below).

For example, you can type the following expression as a setting for the ControlSource property to calculate the sum of the values in the Freight and OrderAmount fields:

= Freight + OrderAmount

Microsoft Access displays the expression as follows:

= [Freight] + [OrderAmount]

Note In a ValidationRule property setting or in a Criteria cell in the query design grid, Microsoft Access doesn't always automatically insert brackets around a name. If you are entering an object name, be sure to type brackets around it. Otherwise, Microsoft Access may assume you are entering text and may insert double quotation marks.

Entering date/time values

Number signs (#) around an element of an expression indicate that the element is a date/time value. Microsoft Access automatically evaluates a value surrounded by number signs as a date/time value and lets you type the value in any common date or time format.

You don't have to type number signs around a date/time value in a validation expression or a criteria expression for a field whose data type is Date/Time. You can type the value in any common date or time format and Microsoft Access automatically inserts number signs around the value.

Microsoft Access displays the value according to the settings in the Regional Settings Properties dialog box in Windows Control Panel. You can change the output format of a date by using the Format property.

Entering text

Double quotation marks around an element of an expression indicate that the element is text.

When you type text in a validation or criteria expression, you can type the text without double quotation marks and Microsoft Access will insert them automatically.

For example, if you type the expression Paris, Microsoft Access displays the expression as follows:

"Paris"


 Use values in expressions

Use values in expressions

You can specify a value in an expression by using a literal value, a constant, a function, or an identifier:

  • A literal value represents a value such as a number, string, or date that Microsoft Access evaluates exactly as written. "New York," 100, and #1-Jan-94# are examples of literal values. Dates are enclosed in number signs (#), and strings in double (") quotation marks.

  • A constant represents a value that doesn't change. True, False, and Null are examples of constants that are defined automatically by Microsoft Access. You can also define your own constants in Visual Basic for Applications that you can use in Visual Basic procedures.

  • A function returns a value based on the results of a calculation or other operation. Microsoft Access includes many built-in functions; for example:
    • The Date function returns the current date.

    • The Sum function returns the sum of a set of field values.

    • The DLookup function returns a specific field value.

    You can also create your own functions using Visual Basic.

  • An identifier refers to the value of a field, control, or property. For example, the following identifier refers to the value of the DefaultValue property of the OrderDate control on the Orders form:

    Forms![Orders]![OrderDate].DefaultValue

You can combine the value of a field, control, or property with a literal string by using the & (concatenation) operator. For example, the following expression combines the literal string "[CategoryID] = " with the value of the CategoryID control on the Products form:

"[CategoryID] = " & Forms![Products]![CategoryID]

In some circumstances — for example, in a domain aggregate function such as DLookup — the value of the field, control, or property must appear in single (') or double (") quotation marks. The easiest way to accomplish this is to add a single quotation mark to the literal string, and then combine the expression with another literal string made up of a single quotation mark after the field, control, or property value, as follows:

"[CategoryID] = ' " & Forms![Products]![CategoryID] & " ' "

Existing Microsoft Access applications may use the vertical bar operators (| |) in place of an opening and closing combination of double quotation marks and & (concatenation) operators, as follows:

"[CategoryID] = '|Forms![Products]![CategoryID]|' "

However, the use of vertical bars is not recommended because they can produce unexpected results in some circumstances.

If you want an expression to produce a string that is enclosed in double quotation marks, you can either enclose the nested string in single quotation marks or three sets of double quotation marks. For example, the following expressions are equivalent:

Forms![Contacts]![City].DefaultValue = ' "Paris" '

Forms![Contacts]![City].DefaultValue = " " "Paris" " "

For more information on constants, click [image] .

For more information on creating your own functions, click [image] .

For more information on using identifiers in expressions, click [image] .


 Refer to a column in a list in an expression

Refer to a column in a list in an expression

You can refer to a column in a multiple-column list box or combo box by using the Column property of the list box or combo box control.

  • Type the identifier for the Column property, followed by the index number of the column in parentheses. Use 0 to refer to the first column, 1 to refer to the second column, and so on. For example, the following identifier refers to the second column of the Country list box control on the Customers form:

    [Forms]![Customers]![Country].Column(1)

Note When you run a macro or Visual Basic for Applications code containing an expression that refers to a form or report, the form or report must be open.

For more information on creating a multiple-column list box or combo box, click [image] .

For information on referring to the value of a control or property in an expression, click [image] .


 Refer to a form or report section or report group level in an expression

Refer to a form or report section or report group level in an expression

  • Type the identifier for the form or report, followed by the . (dot) operator and the name of the section or group level. For example, the following identifier refers to the detail section on the Orders form:

    [Forms]![Orders].Detail

Notes

  • When you run a macro or Visual Basic for Applications code containing an expression that refers to a form or report, the form or report must be open.

  • You can also refer to form or report sections or report group levels by index number using the Section property. For more information on the Section property, click [image] .

For more information on using identifiers in expressions, click [image] .


 Refer to a form, report, subform, or subreport in an expression

Refer to a form, report, subform, or subreport in an expression

You refer to an open form or report, or the subform or subreport of an open form or report, in an expression by typing its identifier.

To refer to an open form or report

  • Type the name of the Forms or Reports collection, followed by the ! operator and the name of the form or report. For example, the following identifier refers to the Orders form:

    Forms![Orders]

To refer to a subform or subreport

Refer to the subform or subreport control on the form or report that contains the subform or subreport, then use the Form or Report property of the control to refer to the actual subform or subreport.

  • Type the identifier for the form that contains the subform, followed by the name of its subform control, the . (dot) operator, and the Form property. For example, the following identifier refers to the Orders Subform subform on the Orders form:

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

Notes

  • You can use the Expression Builder to create an identifier for a form, report, subform, or subreport.

  • When you run a macro or Visual Basic for Applications code containing an expression that refers to a form or report, the form or report must be open.

For more information on creating an expression using the Expression Builder, click [image] .

For more information on using identifiers in expressions, click [image] .

For information on referring to the value of a control or property in an expression, click [image] .


 Refer to an object or its properties in expressions

Refer to an object or its properties in expressions

You use an identifier in an expression to refer to an object or its properties. For example, you can refer to an open form, an open report, a control on an open form or report, or any properties of the form, report, or control. The following identifier refers to the Visible property of a control:

Reports![Invoice]![ShipName].Visible

The full identifier for an object or property shows the relationship between items in the identifier. In this identifier:

  • Reports refers to the collection of open reports in the database. Microsoft Access automatically creates Forms and Reports collections for each database. The Forms collection is made up of all open forms, while the Reports collection is made up of all open reports.

  • [Invoice] refers to the Invoice report in the Reports collection.

  • [ShipName] refers to the ShipName control on the Invoice report.

  • Visible refers to the Visible property of the ShipName control.

It's often a good idea to refer to an object or property using its full identifier. In some cases, a full identifier is required. For example, to refer to a control on a form or report that isn't the current form or report, you must type its full identifier. The following expression displays the sum of the values in the Subtotal and Freight controls on the Orders form in a control on a different form:

= Forms![Orders]![Subtotal] + Forms![Orders]![Freight]

However, in some circumstances you can refer to a control or its properties without specifying a full identifier:

  • If you're referring to a control on the current form or report, you don't have to specify the form or report identifier. For example, to display the sum of the values in the Subtotal and Freight controls in a different control on the same form, set the ControlSource property of the control to:

    = [Subtotal] + [Freight]

  • If you're referring to a control on a subform or subreport, you don't have to specify the full identifier for the form or report using the Form or Report property. For example, you can use the following identifier to refer to the Quantity control on the Orders Subform subform:

    Forms![Orders]![Orders Subform]![Quantity]

    The full identifier for the Quantity control would be:

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

  • In a macro or action argument, you don't have to specify the identifier for the form or report from which the macro is run. For example, if you set an event property on a form to the name of a macro, you can refer to controls on the form in the macro's Condition column or action arguments without specifying the form's identifier.

  • In a Visual Basic for Applications procedure, you can use the Me keyword rather than the full identifier to refer to a control on the current form or report. For example, to assign the sum of the values in the Subtotal and Freight controls on a form to the variable OrderTotal in one of the form's event procedures, add the following statement to the event procedure:
    OrderTotal = Me![Subtotal] + Me![Freight]

Notes

  • When you run a macro or Visual Basic for Applications code containing an expression that refers to a form or report, the form or report must be open.

  • In a Visual Basic procedure, you can refer to an object by enclosing its name in parentheses and double (") quotation marks instead of using the ! operator. The parentheses syntax is required if you want to use a variable in an identifier. For example, the following identifiers are equivalent:
    Forms![Orders]![OrderDate]
Forms("Orders")("OrderDate")

For information on using the ! and . (dot) operators in expressions, click [image] .

For more information on referring to a form, report, subform, or subreport in an expression, click [image] .

For more information on referring to the value of a control or property in an expression, click [image] .


 Refer to the value of a control or property in an expression

Refer to the value of a control or property in an expression

You refer to the value of a control or property in an expression by typing its identifier.

To refer to the value of a control

  • Type the identifier for the form or report that contains the control, followed by the ! operator and the name of the control. For example, the following identifier refers to the value of the OrderID control on the Orders form:

    Forms![Orders]![OrderID]

    Tip If you're referring to a control on a subform or subreport, you don't have to specify the full identifier for the form or report using the Form or Report property. For example, you can use the following identifier to refer to the Quantity control on the Orders Subform subform:

    Forms![Orders]![Orders Subform]![Quantity]

To refer to the value of a property

  • Type the identifier for the form, report, or control to which the property applies, followed by the . (dot) operator, and the name of the property. For example, the following identifier refers to the DefaultValue property of the OrderDate control on the Orders form:

    Forms![Orders]![OrderDate].DefaultValue

Notes

  • You can use the Expression Builder to create an identifier for a control or property.

  • When you run a macro or Visual Basic for Applications code containing an expression that refers to a form or report, the form or report must be open.

For more information on creating an expression using the Expression Builder, click [image] .

For more information on using identifiers in expressions, click [image] .

For more information on using values in expressions, click [image] .

For more information on referring to a form, report, subform, or subreport in an expression, click [image] .


 Use the ! and . (dot) operators in expressions

Use the ! and . (dot) operators in expressions

You use the ! and . (dot) operators in an identifier to indicate the type of item that immediately follows.

The ! operator indicates that what follows is a user-defined item (an element of a collection). For example, use the ! operator to refer to an open form, an open report, or a control on an open form or report.

Identifier | Refers to
Forms![Orders] | The open Orders form
Reports![Invoice] | The open Invoice report
Forms![Orders]![OrderID] | The OrderID control on the open Orders form

The . (dot) operator usually indicates that what follows is an item defined by Microsoft Access. For example, use the . (dot) operator to refer to a property of a form, report, or control.

Note You can also use the . (dot) operator to refer to a field value in an SQL statement, a Visual Basic for Applications method, or a collection. For example, the identifier Forms![Orders].Controls refers to the Controls collection of the Orders form. However, because the Controls collection is the default collection for forms and reports, it's usually not necessary to refer to it explicitly.


 Guidelines for naming fields, controls, and objects

Guidelines for naming fields, controls, and objects

Names of fields, controls, and objects in Microsoft Access:

  • Can be up to 64 characters long.

  • Can include any combination of letters, numbers, spaces, and special characters except a period (.), an exclamation point (!), an accent grave (`), and brackets ([ ]).

  • Can't begin with leading spaces.

  • Can't include control characters (ASCII values 0 through 31).

  • Can't include a double quotation mark (") in table, view, or stored procedure names in a Microsoft Access project.

Although you can include spaces in field, control, and object names, most examples in the Microsoft Access documentation show field and control names without spaces because spaces in names can produce naming conflicts in Visual Basic for Applications in some circumstances.

When you name a field, control, or object, it's a good idea to make sure the name doesn't duplicate the name of a property or other element used by Microsoft Access; otherwise, your database can produce unexpected behavior in some circumstances. For example, if you refer to the value of a field called Name in a table NameInfo using the syntax NameInfo.Name, Microsoft Access displays the value of the table's Name property rather than the value of the Name field.

Another way to avoid unexpected results is to always use the ! operator instead of the . (dot) operator to refer to the value of a field, control, or object. For example, the following identifier explicitly refers to the value of the Name field rather than the Name property:

[NameInfo]![Name]

For more information on using the ! and . (dot) operators in expressions, click [image] .


Guidelines for naming Visual Basic procedures, variables, and constants

Names of procedures, variables, and constants in your Visual Basic for Applications code:

  • Can be up to 255 characters long.

  • Must begin with a letter.

  • Can include letters, numbers, or underscore characters (_).

  • Can't include punctuation characters or spaces.

  • Can't be a Visual Basic keyword.

A keyword is a word that Visual Basic uses as part of its language. This includes predefined statements (such as If and Loop), functions (such as Len and Abs), and operators (such as Or and Mod).


 Examples of expressions

Examples of expressions

You use expressions in many operations in Microsoft Access, including creating calculated controls, query and filter criteria, default values, validation rules, and macro conditions. Often, the easiest way to create an expression is to find an example of an expression that is similar to what you want to create, and then modify it to do what you want.

What examples do you want to see?

Examples of expressions used in forms and reports

Examples of expressions used in queries and filters

Examples of default value expressions

Examples of field validation rule expressions

Examples of macro condition expressions

Read more about what expressions are


Examples of expressions used in forms and reports

What do you want to do?

See examples of expressions that manipulate text

See examples of expressions for page numbers

See examples of expressions that perform arithmetic operations

See examples of expressions that refer to values of controls

See examples of expressions that count, sum, and average values by using aggregate functions

See examples of expressions that count, sum, and look up values by using domain aggregate functions

See examples of expressions that manipulate and calculate dates

See examples of expressions that return one of two possible values

Learn how to create an expression


 Examples of manipulating and calculating dates on forms, reports, and data access pages

Examples of manipulating and calculating dates on forms, reports, and data access pages

The following table lists examples of expressions that you can use in calculated controls on forms, reports, and data access pages.

Expression | Description
=Date() | Uses the Date function to display the current date in the form of mm-dd-yy, where mm is the month (1 through 12), dd is the day (1 through 31), and yy is the last two digits of the year (1980 through 2099).
=Format(Now(), "ww") | Uses the Format function to display the number of the week of the year the current date represents, where ww is 1 through 53.
=DatePart("yyyy", [OrderDate]) | Uses the DatePart function to display the four-digit year of the value of the OrderDate field.
=DateAdd("y", -10, [PromisedDate]) | Uses the DateAdd function to display a date that is 10 days before the value of the PromisedDate field.
=DateDiff("d", [OrderDate], [ShippedDate]) | Uses the DateDiff function to display the variance in days between the values of the OrderDate and ShippedDate fields.

Notes

  • In the ControlSource property of a calculated control, precede the expression with the = operator. On a data access page, you can omit the = operator, and type an alias instead; for example, type WeekNumber: Format(Now(), "ww").

  • When you set the Name property of a calculated control in a form or report, or set the ID property of a calculated control in a data access page, make sure that you use a unique name. Don't use the name or ID of one of the controls you used in the expression.

  • In an expression on a form or report, you can use the name of a control or the name of a field in the underlying record source. In an expression on a data access page, you can use only the name of a field that's in the data definition of the page.


 Examples of manipulating text values in forms, reports, and data access pages

Examples of manipulating text values in forms, reports, and data access pages

The following table lists examples of expressions that you can use in calculated controls on forms, reports, and data access pages.

Expression | Description
="N/A" | Displays N/A.
=[FirstName] & " " & [LastName] | Displays the values of the FirstName and LastName fields separated by a space.
=Left([ProductName], 1) | Uses the Left function to display the first character of the value of the ProductName field.
=Right([AssetCode], 2) | Uses the Right function to display the last 2 characters of the value of the AssetCode field.
=Trim([Address]) | Uses the Trim function to display the value of the Address field, removing any leading or trailing spaces.
=IIf(IsNull([Region]), [City] & " " & [PostalCode], [City] & " " & [Region] & " " & [PostalCode]) | Uses the IIf function to display the values of the City and PostalCode fields if Region is Null; otherwise, it displays the values of the City, Region, and PostalCode fields, separated by spaces.

Notes

  • In the ControlSource property of a calculated control, precede the expression with the = operator. On a data access page, you can omit the = operator, and type an alias instead; for example, type FullName: [FirstName] & " " & [LastName].

  • When you set the Name property of a calculated control in a form or report, or set the ID property of a calculated control in a data access page, make sure to use a unique name. Don't use the name or ID of one of the controls that you used in the expression.

  • In an expression on a form or report, you can use the name of a control or field in the underlying record source. In an expression on a data access page, you can use only the name of a field that's in the data definition of that page.


 Examples of performing arithmetic operations in forms, reports, and data access pages

Examples of performing arithmetic operations in forms, reports, and data access pages

The following table lists examples of expressions that you can use in calculated controls on forms, reports, and data access pages.

If you use this expression | Microsoft Access displays
=[Subtotal]+[Freight] | The sum of the values of the Subtotal and Freight fields.
=[RequiredDate]-[ShippedDate] | The difference between the values of the RequiredDate and ShippedDate fields.
=[Price]*1.06 | The product of the value of the Price field and 1.06 (adds 6 percent to the Price value).
=[Quantity]*[Price] | The product of the values of the Quantity and Price fields.
=[EmployeeTotal]/[CountryTotal] | The quotient of the values of the EmployeeTotal and CountryTotal fields.

Notes

  • In the ControlSource property of a calculated control, precede the expression with the = operator. On a data access page, you can omit the = operator, and type an alias instead; for example, type ExtendedPrice: [Quantity]*[Price].

  • When you set the Name property of a calculated control in a form or report, or set the ID property of a calculated control on a data access page, make sure to use a unique name. Don't use the name or ID of one of the controls that you used in the expression.

  • In an expression on a form or report, you can use the name of a control or the name of a field in the underlying record source. In an expression on a data access page, you can use only the name of a field that's in the data definition of the page.

  • When you use an arithmetic operator (+, -, *, /) in an expression, and the value of one of the controls in the expression is Null, the result of the entire expression will be Null. On a form or report, if some records in one of the controls that you used in the expression might have a Null value, you can convert the Null value to zero by using the Nz function; for example:

    =Nz([Subtotal])+Nz([Freight])

    For more information on the Nz function, click [image] .


Examples of referring to values on forms and reports

The following table lists examples of expressions you can use in calculated controls on forms.

If you use this expression | Microsoft Access displays
=Forms![Orders]![OrderID] | The value of the OrderID control on the Orders form.
=Forms![Orders]![Orders Subform]![OrderSubtotal] | The value of the OrderSubtotal control on the Orders Subform on the Orders form.
=Forms![Orders]![Orders Subform]![ProductID].Column(2) | The value of the third column in ProductID, a multiple-column list box on the Orders Subform on the Orders form. (0 refers to the first column, 1 refers to the second, and so on.)
=Forms![Orders]![Orders Subform]![Price]*1.06 | The product of the value of the Price control on the Orders Subform on the Orders form and 1.06 (adds 6 percent to the value of the Price control).
=Parent![OrderID] | The value of the OrderID control on the main or parent form of the current subform.

The following table lists examples of expressions you can use in calculated controls on reports.

If you use this expression | Microsoft Access displays
=Reports![Invoice]![OrderID] | The value of the OrderID control on the Invoice report.
=Reports![Summary]![Summary Subreport]![SalesTotal] | The value of the SalesTotal control on the Summary Subreport on the Summary report.
=Parent![OrderID] | The value of the OrderID control on the main or parent report of the current subreport.

Notes

  • In a calculated control, precede the expression with the = operator.

  • When you set the Name property of a calculated control, make sure you use a unique name. Don't use the name of one of the controls you used in the expression.


 Examples of returning one of two values on forms, reports, and data access pages

Examples of returning one of two values on forms, reports, and data access pages

The following table lists examples of expressions that you can use in calculated controls on forms, reports, and data access pages.

Expression | Description
=IIf([Confirmed] = "Yes", "Order Confirmed", "Order Not Confirmed") | Uses the IIf function to display the message "Order Confirmed" if the value of the Confirmed field is Yes; otherwise, it displays the message "Order Not Confirmed."
=IIf(IsNull([Country]), " ", [Country]) | Uses the IIf function to display an empty string if the value of the Country field is Null; otherwise, it displays the value of the Country control.
=IIf(IsNull([Region]), [City] & " " & [PostalCode], [City] & " " & [Region] & " " & [PostalCode]) | Uses the IIf function to display the values of the City and PostalCode fields if Region is Null; otherwise, it displays the values of the City, Region, and PostalCode fields.
=IIf(IsNull([RequiredDate] - [ShippedDate]), "Check for a missing date", [RequiredDate] - [ShippedDate]) | Uses the IIf function to display the message "Check for a missing date" if the result of subtracting ShippedDate from RequiredDate is Null; otherwise, it displays the difference between the values of the RequiredDate and ShippedDate fields.

Notes

  • In the ControlSource property of a calculated control, precede the expression with the = operator. On a data access page, you can omit the = operator, and type an alias instead; for example, type DisplayCountry: IIf(IsNull([Country]), " ", [Country]).

  • When you set the Name property of a calculated control in a form or report, or set the ID property of a calculated control in a data access page, make sure to use a unique name. Don't use the name or ID of one of the controls that you used in the expression.

  • In an expression on a form or report, you can use the name of a control or the name of a field in the underlying record source. In an expression on a data access page, you can use only the name of a field that's in the data definition of the page.


 Examples of using aggregate functions in forms and reports

Examples of using aggregate functions in forms and reports

The following table lists examples of expressions you can use in calculated controls on forms and reports.

Expression | Description
=Avg([Freight]) | Uses the Avg function to display the average of the values of the Freight control.
=Count([OrderID]) | Uses the Count function to display the number of records in the OrderID control.
=Sum([Sales]) | Uses the Sum function to display the sum of the values of the Sales control.
=Sum([Quantity]*[Price]) | Uses the Sum function to display the sum of the product of the values of the Quantity and Price controls.
=[Sales]/Sum([Sales])*100 | Displays the percentage of sales, determined by dividing the value of the Sales control by the sum of all the values of the Sales control. Note If the control's Format property is set to Percent, don't include the *100.

Notes

  • In a calculated control, precede the expression with the = operator.

  • When you set the Name property of a calculated control, make sure you use a unique name. Don't use the name of one of the controls you used in the expression.

  • You can't use the name of a control in an expression that uses an aggregate function; you must use only field names from a table, query, or SQL statement. For information about using aggregate functions with calculated controls, click [image] .


 Examples of using domain aggregate functions on forms and reports

Examples of using domain aggregate functions on forms and reports

The following table lists examples of expressions you can use in calculated controls on forms and reports.

Expression | Description
=DLookup("[ContactName]", "[Suppliers]", "[SupplierID] = Forms![SupplierID]") | Uses the DLookup function to display the value of the ContactName field in the Suppliers table where the value of the SupplierID field in the table matches the value of the SupplierID control on the active form.
=DLookup("[ContactName]", "[Suppliers]", "[SupplierID] = Forms![New Suppliers]![SupplierID]") | Uses the DLookup function to display the value of the ContactName field in the Suppliers table where the value of the SupplierID field in the table matches the value of the SupplierID control on the New Suppliers form.
=DSum("[OrderAmount]", "[Orders]", "[CustomerID] = 'RATTC'") | Uses the DSum function to display the sum total of values of the OrderAmount field in the Orders table where the CustomerID is RATTC.

Notes

  • In a calculated control, precede the expression with the = operator.

  • When you set the Name property of a calculated control, make sure you use a unique name. Don't use the name of one of the controls you used in the expression.

  • You can't use the name of a control in an expression that uses a domain aggregate function; you must use only field names from a table, query, or SQL statement. For information about using domain aggregate functions with calculated controls, click [image] .


 About toolbars, menu bars, and shortcut menus

About toolbars, menu bars, and shortcut menus

Toolbars, menu bars, and shortcut menus allow you to organize the commands in Microsoft Access the way you want so you can find and use them quickly. Toolbars can contain only buttons, only menus, or a combination of both. The built-in menu bar appears by default at the top of the screen and contains standard menus such as File, Edit, and View.

Access automatically personalizes menus and toolbars for you based on how often you use the commands. When you first start Access, the most basic commands appear. Then, as you work, Access adjusts the menus and toolbars so that only the commands and toolbar buttons you use most often appear. To look for a command you don't use often, or have never used before, click the arrows Double arrows pointing down at the bottom of the menu to expand it to show all commands. You can also double-click the menu to expand it. When you expand one menu, all of the menus are expanded until you choose a command or perform another action. When you click a command on the expanded menu, it is immediately added to the personalized menu. A menu command is dropped from the personalized menu if you use Access many times without using that command. If you want, you can specify that Access always show the full set of commands for each menu.

Toolbars can be positioned next to each other on the same row. When you put multiple toolbars on the same row, there may not be enough room to display all of the buttons. If there isn't enough room, the buttons that you have used most recently are displayed. You can resize a toolbar to display more buttons or show all buttons on a toolbar. To see a list of buttons that won't fit on a built-in, docked toolbar, click More Buttons [image] at the end of the toolbar. When you use a button that is not displayed on the toolbar, that button is moved to the toolbar, and a button that has not been used recently is dropped to the More Buttons [image] list.

As you work with Access, the menus and toolbars are personalized to show the commands that you use most often. If you want, you can return the toolbar and menu display to its initial state when you first started Access.

You can also customize menus and toolbars yourself. You can customize the built-in menu bar by adding or removing buttons and menus or by moving the menu to a different location. Besides customizing the built-in menu bar, shortcut menus, and toolbars, you can also create your own custom toolbars, menu bars, and shortcut menus.

To create and customize toolbars, menu bars, and shortcut menus, and to set properties that affect how they look and behave, use the Customize dialog box — available by pointing to Toolbars on the View menu, and then clicking Customize.

Note In the PivotTable List, spreadsheet, and chart tools on a data access page, certain toolbar functionalities differ from the rest of Microsoft Access.

More information

How to work with toolbars

How to work with menu bars and shortcut menus


 Work with toolbars

Work with toolbars

What do you want to do?

Read about toolbars, menu bars, and shortcut menus

Show or hide a toolbar, menu bar, or shortcut menu

Create a custom toolbar for the current database

Create a toolbar for all databases

Move a toolbar or menu bar

Add a button to a toolbar

Delete a toolbar button

Move or copy a toolbar button

Change the image or text on a toolbar button or menu command

Restore toolbars or menu bars, or individual buttons, commands, or menus

Troubleshoot toolbars, menu bars, and shortcut menus

Note For more specific information about toolbars, click Office Assistant [image] on the toolbar, and then type a more detailed question.


 Work with menu bars and shortcut menus

Work with menu bars and shortcut menus

What do you want to do?

Read about toolbars, menu bars, and shortcut menus

Show or hide a toolbar, menu bar, or shortcut menu

Create a custom menu bar for the current database

Create a custom shortcut menu for the current database

Convert menu macros from previous versions of Microsoft Access to menu bars and shortcut menus

Add a custom menu to a menu bar or toolbar

Move or copy a menu to a menu bar or toolbar

Delete a menu from a menu bar or toolbar

Move or copy a menu command

Add a command to a menu

Delete a command from a menu

Change the image or text on a toolbar button or menu command

Restore toolbars or menu bars, or individual buttons, commands, or menus

Troubleshoot toolbars, menu bars, and shortcut menus

Note For more specific information about menu bars or shortcut menus, click Office Assistant [image] on the toolbar, and then type a more detailed question.


Create a custom menu bar for the current Access database or Access project

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, click New.

  3. In the Toolbar Name box, type the name you want, and then click OK.

  4. On the Toolbars tab, click Properties.

  5. In the Type list, click Menu Bar.

  6. Set any other properties you want, and then click Close.

    The new menu bar is now placed to the right of the Customize dialog box.

  7. To complete the menu bar, do the following:
    • Add custom menus. For more information, click [image] .

    • Add a built-in menu. For more information, click [image] .

Notes

  • Microsoft Access supports menu bar macros for applications created with a prior version of Microsoft Access. For more information, click [image] .

  • You can attach the custom menu bar to a form or report. For more information, click [image] . Or, you can designate the bar as the global menu bar. For more information, click [image] .


Create a custom shortcut menu for the current Access database or Access project

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, click New.

  3. In the Toolbar Name box, type the name you want, and then click OK.

  4. On the Toolbars tab, click Properties.

  5. In the Type list, click Popup.

  6. Set the AllowCustomizing property the way you want, and then click Close.

    Microsoft Access adds the shortcut menu to the Shortcut Menus toolbar, from which you customize all shortcut menus.

  7. In the Toolbars box on the Toolbars tab, click Shortcut Menus.

  8. On the Shortcut Menus toolbar, click the Custom category.

  9. To complete the menu, do the following.
    • Add commands from the Customize dialog box. For more information, click [image] .

    • Move or copy commands from other menus. For more information, click [image] .

Notes

  • Microsoft Access supports menu macros for applications created with a prior version of Microsoft Access. For more information, click [image] .

  • You can attach the custom shortcut menu to a form, report, or control. For more information, click [image] . Or, you can designate the menu as the global shortcut menu. For more information, click [image] .


 Import custom toolbars and menus from another Access database or Access project

Import custom toolbars and menus from another Access database or Access project

You can import all the custom menus and toolbars from a Microsoft Access database or Microsoft Access project. However, Microsoft Access won't import a toolbar, menu bar, or shortcut menu if it has the same name as one in the database you're importing to.

  1. Open a database.

  2. On the File menu, point to Get External Data, and then click Import.

  3. In the Files Of Type box, make sure Microsoft Access (*.mdb, *.adp) is selected.

  4. In the Look In box, select the drive and folder for the Microsoft Access database (.mdb or .adp) you want to import from, and then double-click the database.

  5. In the Import Objects dialog box, click Options.

  6. Under Import, click Menus And Toolbars.


 Convert a previous-version menu macro to a menu bar or shortcut menu

Convert a previous-version menu macro to a menu bar or shortcut menu

This procedure creates the new style of menu bar or shortcut menu from macros you created in a previous version of Microsoft Access.

  1. In the Database window, click Macros [image] under Objects, and then click the name of the macro you want to create a menu bar or shortcut menu for.

    To create the new style of menu bar or shortcut menu from macros you previously used for custom menus, select only the top-level menu bar macro. You don't need to select the macro group for each menu that appears on the menu bar.

  2. On the Tools menu, point to Macro, and then click Create Menu From Macro or Create Shortcut Menu From Macro.

Notes

  • You can now customize the menu bar or shortcut menu using the Customize dialog box available by pointing to Toolbars on the View menu, and then clicking Customize.

  • Microsoft Access won't delete the original macro (or macros if you're working with a menu bar macro and the associated menu macro groups) after it creates the new menu bar or shortcut menu. The new menu bar still depends on the original macro or macros, except for macros that contain only AddMenu actions or RunCommand (formerly DoMenuItem) actions.


 Create a toolbar from a macro

Create a toolbar from a macro

  1. In the Database window, click Macros [image] under Objects, and then click the name of the macro you want to create a toolbar for.

  2. On the Tools menu, point to Macro, and then click Create Toolbar From Macro.

Note Microsoft Access won't delete the original macro (or macros if you're working with a menu macro and the associated menu macro groups) after it creates the new toolbar. The new toolbar still depends on the original macro or macros, except for macros that contain only AddMenu actions or RunCommand (formerly DoMenuItem) actions.


Maintain or update menus previously created with macros

Microsoft Access 2000 still supports menu bar macros for applications created with versions of Access prior to Access 2000. In Access 2000 and later versions, menu bars and shortcut menus (as well as toolbars) are created and customized from the Customize dialog box available by pointing to Toolbars on the View menu. You can also use the dialog box to customize the built-in menu bar and toolbars.

Note You can also work with menu bars, shortcut menus, and toolbars using Visual Basic for Applications. For more information, click [image] .

What do you want to do?

Convert menu macros from previous versions of Microsoft Access to menu bars and shortcut menus

Maintain existing menu bar macros by using the AddMenu action

Read about menu bar macros in a converted Microsoft Access database


Rename a custom shortcut menu

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, click Properties.

  3. In the Selected Toolbar box, click the shortcut menu you want to rename.

  4. In the Toolbar Name box, type the new name.


Rename a custom toolbar or menu bar

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, select the name of the toolbar or menu bar.

    Note Selecting or clearing a check box in the Toolbars dialog box shows or hides that toolbar or menu bar.

  3. Click Rename.

  4. In the Toolbar name box, type the new name.

Note You cannot rename a built-in toolbar or menu bar.


Delete a custom shortcut menu

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, click Properties.

  3. In the Selected Toolbar box, click the name of the custom shortcut menu you want to delete.

  4. In the Type list, change the type to Toolbar, and then close the property sheet.

    The name of the shortcut menu now appears in the Toolbars box on the Toolbars tab.

  5. Select the name of your custom shortcut menu in the Toolbars box, and then click Delete.


Delete a custom toolbar or menu bar

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, select the custom toolbar or menu bar you want to delete.

  3. Click Delete.

Note You cannot delete a built-in toolbar or menu bar. When you select a built-in toolbar or menu bar, the Delete button isn't available. However, the Reset button becomes available; clicking it will restore the toolbar or menu bar to its default buttons or menus and submenus.


 Add a button to a toolbar

Add a button to a toolbar

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the toolbar you want to add a button to.

  3. Click the Commands tab.

  4. In the Categories box, click a category for the command you want the button to perform.
    To add a | Click
    Built-in button | The appropriate menu or view category
    Buttons for navigating HTML pages | Web
    Buttons for working with SourceSafe | Source Code Control
    Button for creating custom controls | ActiveX Controls
    Button that displays a form, report, or other database object in its default view One of the following: All Tables, All Queries, All Forms, All Reports, All Web Pages.

    If you're in a Microsoft Access project, you'll see All Database Diagrams, All Views, and All Stored Procedures.
    Button that runs a macro | All Macros

  5. Drag the button, object, or ActiveX control you want from the Commands box to the displayed toolbar.

Notes

  • You can also add buttons that run Visual Basic functions. For more information, click [image] .

  • To quickly add a button that opens a database object, drag the object from the Database window to the toolbar.

  • You can display shortcut key text on the button. For more information, click [image] .

  • Microsoft Access can automatically create a toolbar containing buttons that run existing macros. For more information, click [image] .

Tip To quickly add a built-in button to a built-in toolbar, click More Buttons [image] on a docked toolbar, or click the arrow Arrow pointing down in the upper-left corner of a floating toolbar; click Add or Remove Buttons, and then select the check box next to the button you want to add.


Add a custom button that runs a Visual Basic function to a toolbar

  1. Create the function you want the button to run.

    How?

  2. On the View menu, point to Toolbars, and then click Customize.

  3. If it isn't already displayed, show the toolbar you want to add the button to.

    How?

  4. In the Customize dialog box, click the Commands tab.

  5. In the Categories box, click File.

  6. Drag the Custom command from the Commands box to the displayed toolbar.

  7. With the Customize dialog box open, right-click the button on the toolbar, and then on the shortcut menu, type a new name for the button in the Name box.

  8. On the same shortcut menu, click Properties.

  9. In the On Action box, type the name of the function you want to run in the format =functionname(). For example, for a custom function named SetCaption(), type =SetCaption(). For a built-in function, enter the name of the function and any required arguments, for example =MsgBox(IIf(Instr(Time(), "PM"), "Good Afternoon", "Good Morning")).

  10. Specify any other properties for the button.


Add a custom command that runs a Visual Basic function to a menu

  1. Create the function you want the command to run.

    How?

  2. On the View menu, point to Toolbars, and then click Customize.

  3. If it isn't already displayed, show the menu bar, shortcut menu, or toolbar containing the menu that you want to add the command to.

    How?

  4. In the Customize dialog box, click the Commands tab.

  5. In the Categories box, click File.

  6. Drag the Custom command from the Commands box over the menu on the menu bar or the toolbar, or under the appropriate category on the Shortcut Menus toolbar. When the menu displays a list of menu commands (or an empty box if it's new), point to the location where you want the command to appear on the menu, and then release the mouse.

  7. With the Customize dialog box open, right-click the command on the menu, and then on the shortcut menu, type a new name for the command in the Name box.

  8. On the same shortcut menu, click Properties.

  9. In the On Action box, type the name of the function you want to run in the format =functionname(). For example, for a custom function named SetCaption(), type =SetCaption(). For a built-in function, enter the name of the function and any required arguments, for example =MsgBox(IIf(Instr(Time(), "PM"), "Good Afternoon", "Good Morning")).

  10. Specify any other properties for the command.

Note If you add a command to a built-in menu (for example, the Edit menu), that command appears in all views having that built-in menu.


 Add a command to a menu

Add a command to a menu

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the menu bar, shortcut menu, or toolbar you want to add a command to.

  3. Click the Commands tab.

  4. In the Categories box, do any of the following:
    To add a | Click
    Built-in command | The appropriate menu or view category
    Buttons for navigating HTML pages | Web
    Buttons for working with SourceSafe | Source Code Control
    Command for creating custom controls | ActiveX Controls
    Command that displays a form, report, or other database object in its default view One of the following: All Tables, All Queries, All Forms, All Reports, All Web Pages.

    If you're in a Microsoft Access project, you'll see All Database Diagrams, All Views, and All Stored Procedures.
    Command that runs a macro | All Macros
  5. Drag the command you want from the Commands box over the menu on the menu bar, Shortcut Menus toolbar, or other toolbar. When the menu displays a list of menu commands (or a blank box if it's new), point to the location where you want the command to appear on the menu, and then release the mouse.

Notes

  • You can also add a command that runs a Visual Basic function. For more information, click [image] .

  • You can display shortcut key text for the command. For more information, click [image] .

  • If you add a command to a menu (for example, the Edit menu), that command appears in all views that have that menu.


Add a submenu to a built-in or custom menu

  1. On the View menu, point to Toolbars, and then click Customize.

  2. If it isn't already displayed, show the toolbar or menu bar with the menu you want to add a submenu to.

    How?

  3. In the Customize dialog box, click the Commands tab.

  4. In the Categories box, click New Menu.

  5. From the Commands box, drag New Menu over the menu you want to add the submenu to until the top-level menu drops down, and then add New Menu in the desired location.

  6. Right-click the new submenu, and then type a name in the Name box on the shortcut menu. Press ENTER.

  7. Complete the menu by doing the following:
    • Adding commands from the Customize dialog box. For more information, click [image] .

    • Moving or copying commands from other menus. For more information, click [image] .


Add a built-in menu to a toolbar or menu bar

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the menu bar or toolbar you want to add a built-in menu to.

    How?

  3. Click the Commands tab.

  4. In the Categories box, click Built-in Menus.

  5. Drag the menu you want from the Commands box to the toolbar or menu bar.

Note If a menu command does not appear in the Commands box, you can make it available by clicking Built-in Menus in the Categories box and then adding the built-in menu that contains that command to the toolbar or menu bar. However, if you change the built-in menu on the toolbar or menu bar, that change appears in all views that have that menu.


Add a custom menu to a menu bar or toolbar

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the menu bar or toolbar you want to add a custom menu to.

  3. Click the Commands tab.

  4. In the Categories box, click New Menu.

  5. Drag New Menu from the Commands box to the displayed menu bar or toolbar.

  6. Right-click the new menu on the menu bar or toolbar, and then type a name in the Name box on the shortcut menu. Press ENTER.

  7. To complete the menu, do the following:
    • Add commands from the Customize dialog box. For more information, click [image] .

    • Move or copy commands from other menus. For more information, click [image] .


 Rename a menu command or toolbar button

Rename a menu command or toolbar button

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the toolbar, menu bar, or shortcut menu with the menu command or toolbar button you want to change.

  3. With the Customize dialog box open, do one of the following:
    • To rename a menu command, click the menu on the menu bar or toolbar, or click the shortcut menu that contains the command you want to rename. Right-click the menu command you want to rename, type a new name in the Name box on the shortcut menu, and then press ENTER.

    • To rename a toolbar button, right-click the button on the toolbar, type a new name in the Name box on the shortcut menu, and then press ENTER.

Notes

  • If a toolbar button does not display text, you won't see the name change except when you view the ScreenTip. For information about displaying text, an icon, or both on a toolbar button, click [image] .

  • When you specify a new name for a menu command or toolbar button, you can assign an access key. For more information, click [image] .


 Delete a toolbar button

Delete a toolbar button

  1. Show the toolbar you want to change.

  2. If the Customize dialog box is open, drag the button off the toolbar away from any other toolbars or the menu bar; otherwise, hold down ALT and drag the button off the toolbar.

Note When you delete a built-in button, the button is still available in the Customize dialog box. However, when you delete a custom button, it is permanently deleted. To remove and save a custom button for later use, create a toolbar for storing unused buttons, move the button to this storage toolbar, and then hide the storage toolbar.

Tip To quickly delete a built-in button from a built-in toolbar, click More Buttons [image] on a docked toolbar, or click the arrow Arrow pointing down in the upper-left corner of a floating toolbar; click Add or Remove Buttons, and then clear the check box next to the button you want to delete.


Delete a command from a menu

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the menu bar, shortcut menu, or toolbar that contains the menu command you want to delete.

  3. With the Customize dialog box open, click the menu on the menu bar or toolbar, or click the shortcut menu that contains the command you want to delete.

  4. Drag the command you want to delete off the menu away from any other menus or toolbars.

Note If you delete a command from a built-in menu (for example, the Edit menu), the command is deleted from that menu in all views that previously had that menu with that command.


Delete a menu from a menu bar or toolbar

  1. Show the toolbar or menu bar you want to delete a menu from.

  2. If the Customize dialog box is open, drag the menu off the menu bar or toolbar away from any other toolbars or the menu bar; otherwise, hold down ALT, and then drag the menu off.

Tip When you delete a built-in menu, the menu is still available in the Customize dialog box. However, when you delete a custom menu, it is permanently deleted. To remove and save a custom menu for later use, create a toolbar for storing unused menus, move the menu to this storage toolbar, and then hide the storage toolbar.


 Have Microsoft Access automatically dial a selected phone number

Have Microsoft Access automatically dial a selected phone number

You must have a working Hayes or Hayes-compatible modem to use this procedure.

  1. Open a table or form in Datasheet view or a form in Form view.

  2. On the View menu, point to Toolbars, and then click Customize.

  3. Click the Commands tab in the Customize dialog box.

  4. Click Records in the Categories list.

  5. Drag AutoDialer [image] to the Form view or Datasheet view toolbar, or to a custom toolbar.

  6. Click Close.

  7. In the form or datasheet, select the phone number you want to dial.

  8. Click AutoDialer [image] on the toolbar.

  9. Check to see that the phone number is entered correctly, and then click OK.

Note You can change your modem options by clicking Setup in the AutoDialer dialog box.


Change the image or text on a toolbar button or menu command

On a toolbar button, you can display text, an icon, or both. On a menu command, you can display both an icon and text or just text. You can change the text that's displayed for a toolbar button or menu command. You can also change the icon image on any toolbar button or menu command, except for those that display a list or a menu when you click them. You change the image by copying and pasting from other toolbar buttons or menu commands, choosing from a predefined list of images, or creating an image in a graphics program and then pasting it onto the button or menu command. You can also edit an existing button or menu command image.

What do you want to do?

Display text only or an icon and text on a menu command

Display text, an icon, or both on a toolbar button

Rename a menu command or toolbar button

Copy an image from one toolbar button or menu command to another

Copy an image from a graphics program to a toolbar button or menu command

Choose from a predefined list of images for a toolbar button or menu command

Edit a toolbar button image or a menu command image


Choose an existing image for a toolbar button or menu command

  1. On the View menu, point to Toolbars, and then click Customize.

  2. If it isn't already displayed, show the toolbar, menu bar, or shortcut menu with the toolbar button image or menu command image you want to change.

    How?

  3. With the Customize dialog box open, do one of the following:
    • To change a toolbar button image, right-click the button on the toolbar, point to Change Button Image on the shortcut menu, and then click an image.

    • To change a menu command image, click the menu name on the menu bar or toolbar, or click the shortcut menu that contains the command with the image you want to change. Right-click the menu command, point to Change Button Image on the shortcut menu, and then click an image.

Note If you change the image for a command on a built-in menu (for example, the Edit menu), that image appears in all views showing that menu with that command.


Move or copy a toolbar button

  1. Show the toolbar with the button you want to move or copy and the toolbar you want to move or copy the button to.

  2. Do one of the following:
    • To move a toolbar button when the Customize dialog box is open, drag the button to the new location on the same toolbar or on another toolbar. If the dialog box isn't open, hold down ALT and drag the button to the new location.

    • To copy a toolbar button when the Customize dialog box is open, hold down CTRL and drag the button to the new location. If the dialog box isn't open, hold down CTRL+ALT and drag the button to the new location.

Note You can move or copy a button from a toolbar to a menu, too.


Move menus or menu commands

What do you want to do?

Move or copy a menu to a menu bar or toolbar

Move or copy a menu command


Move or copy a menu command

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the menu bar, shortcut menu, or toolbar that contains the menu with the command you want to move or copy. If you're copying or moving the command to a different toolbar or menu bar, show that bar, too.

  3. With the Customize dialog box open, click the menu on the menu bar or toolbar, or click the shortcut menu that contains the command you want to copy or move.

  4. Do one of the following:
    • To move the command, drag it over the menu where you want to place it. When the menu displays a list of commands (or an empty box if it's new), point to where you want the command to appear on the menu, and then release the mouse button.

    • To copy the command, hold down CTRL and drag the command over the menu where you want to place it. When the menu displays a list of commands, point to where you want the command to appear on the menu, and then release the mouse button.

Note If you move or copy a command to a built-in menu (for example, the Edit menu), the command appears on that menu in all views that have that menu.


Rename a menu on a menu bar or toolbar

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the menu bar or toolbar that contains the menu you want to rename.

  3. Leave the Customize dialog box open. On the menu bar or toolbar, right-click the menu you want to change, and then type the name in the Name box on the shortcut menu.


Restore toolbars or menu bars, or individual buttons, commands, or menus

You can restore an entire built-in toolbar or menu bar, all of the original buttons or menus and commands, or an individual button, command, or menu.

What do you want to do?

Restore all default settings for a toolbar or menu bar, including its property settings and the settings for individual buttons, menus, and commands

Restore original buttons, menus, and commands on a built-in toolbar, menu bar, or shortcut menu

Restore how an individual toolbar button or menu command appears

Restore a menu

Not sure which choice you want?


Change the width of a combo box on a toolbar

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the toolbar you want to change.

  3. With the Customize dialog box open, click the combo box, such as Font or Font Size, on the toolbar.

  4. Point to the left or right edge of the box. When the pointer changes to a double-headed arrow, drag the edge of the box to change its width.


Assign a hyperlink to a toolbar button or menu command

When you assign a hyperlink to a toolbar button or menu command, the hyperlink replaces the command currently assigned to that button or menu command. You cannot assign a hyperlink to a button that displays a list or menu when the button is clicked.

  1. Display the toolbar you want to change.

  2. If the button you want to assign a hyperlink to is not on a toolbar, add a button to the toolbar.

    If the menu command you want to assign a hyperlink to is not on a menu, add the command to a menu.

  3. On the Tools menu, click Customize.

  4. Right-click the toolbar button, point to Assign Hyperlink on the shortcut menu, and then click Open.

  5. Under Link to, click the source you want to link to.

  6. Select the options you want.

    For Help on an option, click the question mark [image] and then click the option.


 Show all the buttons on a toolbar

Show all the buttons on a toolbar

  • Use the move handle Left edge of a docked toolbar on the toolbar to drag the toolbar to its own row, or to a location other than the edge of the program window, so that the toolbar becomes a floating toolbar.


Show all the commands on the menus

  1. On the Tools menu, click Customize, and then click the Options tab.

  2. Clear the Menus show recently used commands first check box.

Note The Menus show recently used commands first check box affects all of your Microsoft Office programs.


Show default toolbar buttons and menu commands

  1. On the Tools menu, click Customize, and then click the Options tab.

  2. Click the Reset my usage data button.

Notes

  • The Reset my usage data button affects the buttons shown on a built-in toolbar only if the toolbar is not wide enough to display all the buttons, and affects the menu commands shown on the personalized built-in menus only if you have the Menus show recently used commands first check box selected on the Options tab in the Customize dialog box (Tools menu).

  • The Reset my usage data button affects only the toolbar buttons and menu commands in Microsoft Access.

  • The Reset my usage data button does not change the location of toolbars, does not remove any buttons or commands you've added by using the Customize dialog box, and does not add buttons or commands you've deleted.


 Create shortcut key text for a built-in toolbar button or menu command

Create shortcut key text for a built-in toolbar button or menu command

This procedure only creates the shortcut key text. It doesn't assign the action you want the key to perform.

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the toolbar or menu bar you want to work with, if it isn't already displayed.

    How?

  3. With the Customize dialog box open, right-click the built-in toolbar button or menu command you want to specify shortcut text for.

  4. Click Properties on the shortcut menu.

  5. In the Shortcut Text property box, type the shortcut key or key combination that you want to display. (The Shortcut Text property isn't available for custom buttons or commands.)

Notes

  • To assign the action you want the shortcut keys to perform, you must create an AutoKeys macro. For more information, click [image] .

  • For a command on a menu, the shortcut key text appears to the right of the command. For a toolbar button, the shortcut key text appears in the ToolTip, and only if you have selected the Show Shortcut Keys In ScreenTips box on the Options tab (Customize dialog box). For more information, click [image] .


Create What's This tips for toolbar buttons or menu commands

What's This tips appear when you click What's This? on the Help menu or press SHIFT+F1, and then click a toolbar button or menu command.

Creating the tip

  1. Create the source file using the text editor or word-processing program of your choice. Make sure to save the source file in Rich Text Format. For information on creating the source file, see the Help that comes with the Windows Help Compiler.

  2. Compile the Help file using the Windows Help Compiler.

    Note For best results, put the Help file in the same folder as your application. That way, each site using your application can use the same setting for the HelpFile property, but install the application in the folder of their choice. If you omit a path setting in this property, Microsoft Access looks for the Help file in the folder where your application is installed.

Assigning the tip to a toolbar button or menu command

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the toolbar or menu bar you want to work with, if it isn't already displayed.

    How?

  3. With the Customize dialog box open, right-click the toolbar button or menu command you want to assign a tip to, and then click Properties on the shortcut menu.

  4. In the HelpFile property box, specify the path and file name for the compiled Help file.

  5. In the HelpContextID property box, type the number of the topic (other than 0).

Notes

  • You must map the values set for the HelpContextID property to the context strings in your Help system. For more information, see the Help file that comes with the Windows Help Compiler.

  • You can't display custom What's This tips through the Office Assistant.

  • The Windows Help Compiler is included with Microsoft Office 2000 Developer Edition; Microsoft Visual Basic for Applications; Microsoft Visual C++; and the Microsoft Windows Software Development Kit (SDK). You can also order a Help Authoring Kit from Microsoft. To find out more about what's included in Microsoft Office 2000 Developer Edition, click [image] .


Create a custom ToolTip (ScreenTip) for a toolbar button

ToolTips appear when the mouse pointer rests on a button or combo box on a toolbar.

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the toolbar you want to work with, if it isn't already displayed.

    How?

  3. With the Customize dialog box open, right-click the toolbar button you want to specify a tip for, and then click Properties on the shortcut menu.

  4. In the ScreenTip property box, type the tip that you want to display.

Notes

  • If you don't specify a custom ToolTip, Microsoft Access by default displays the text specified in the Caption property.

  • If the ToolTip doesn't appear when the mouse pointer rests over the button or combo box, verify that you have selected the Show ScreenTips On Toolbars box on the Options tab (Customize dialog box).


 Assign an access key to a menu or command

Assign an access key to a menu or command

You can use an access key instead of the mouse to move the focus to a menu or command. For example, press the access keys ALT+T to move the focus to the Tools menu, then press the access key A to select the AutoCorrect command.

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the toolbar or menu bar you want to work with, if it isn't already displayed.

    How?

  3. With the Customize dialog box open, right-click the menu or command you want to specify an access key for.

  4. In the Name box, type an ampersand (&) before the character you want to use as the access key.

    On the menu or command, Microsoft Access adds an underscore to the character you've designated as the access key.

Note Use a different access key for each command on a given menu.


 Attach a custom menu bar to a form or report

Attach a custom menu bar to a form or report

Once attached, the custom menu bar replaces the built-in menu bar for the form or report.

  1. Create the menu bar.

    How?

  2. Open the form or report in Design view.

  3. Click the form selector or report selector in Design view.

  4. On the toolbar, click Properties [image] .

  5. In the MenuBar property box, specify the menu bar name.

    Repeat this procedure for each form or report you want to attach the menu bar to.


 Attach a custom toolbar to a form or report

Attach a custom toolbar to a form or report

Once attached, the toolbar replaces the built-in toolbar for the form or report.

  1. Create the toolbar.

    How?

  2. Open the form or report in Design view.

  3. Click the form selector or report selector in Design view.

  4. On the toolbar, click Properties [image] .

  5. In the Toolbar property box, specify the toolbar name.

    Repeat this procedure for each form or report you want to attach the toolbar to.


 Attach a shortcut menu to a form, form control, or report

Attach a shortcut menu to a form, form control, or report

Once attached, the shortcut menu replaces the built-in shortcut menu for a form, a control, or a report.

  1. Create the shortcut menu.

    How?

  2. Open the form or report in Design view.

  3. Click the form selector, report selector, or control in Design view.

  4. On the toolbar, click Properties [image] .

  5. In the ShortcutMenuBar property box, specify the shortcut menu name.

    For a form, also make sure the ShortcutMenu property is set to Yes.

    Repeat this procedure for each form, report, or control you want to attach the shortcut menu to.


Control toolbar or menu bar docking

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, click Properties.

  3. In the Selected Toolbar box, select the name of the toolbar or menu bar you want to set properties for.

  4. In the Docking box, click the setting you want to use.

Notes

  • For any setting other than Can't Change, make sure that the Allow Moving box is also selected.

  • This setting is not affected by the Allow Toolbar/Menu Changes setting in the Startup dialog box (Tools menu).


Control whether custom toolbars and menu bars appear on the Toolbars menus

By default, you can show and hide custom toolbars and menu bars by choosing them from the submenu you see when you point to Toolbars on the View menu or from the shortcut menu you get when you right-click on a toolbar button or menu. You can prevent users from doing this by removing the names of the toolbars or menu bars from these menus.

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, click Properties.

  3. In the Selected Toolbar box, select the name of the toolbar you want to set properties for.

  4. Select or clear the Show On Toolbars Menu box.

Notes

  • If you clear this option, you can still show and hide toolbars or menu bars from the Customize dialog box. For information on preventing users from accessing the Customize dialog box, click [image] .

  • If you select this option, make sure the Allow Showing/Hiding box is also selected.


Prevent or allow changing specific toolbars, menu bars, or shortcut menus

"Changing" in this instance means adding, moving, removing, or setting properties for buttons, commands, or menus.

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, click Properties.

  3. In the Selected Toolbar box, select the name of the toolbar, menu bar, or custom shortcut menu you want to set properties for.

  4. Select or clear the Allow Customizing box.

Note Once you've finished setting properties for all the toolbars, menu bars, and shortcut menus, you can prevent users from accessing the Customize dialog box and changing the settings. For more information, click [image] .


Prevent or allow movement of toolbars or menu bars

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, click Properties.

  3. In the Selected Toolbar box, select the name of the toolbar or menu bar you want to set properties for.

  4. Select or clear the Allow Moving box.

Note This setting is not affected by the Allow Toolbar/Menu Changes setting in the Startup dialog box (Tools menu).


 Prevent or allow resizing of toolbars or menu bars

Prevent or allow resizing of toolbars or menu bars

You can resize floating toolbars or menu bars.

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, click Properties.

  3. In the Selected Toolbar box, select the name of the toolbar or menu bar you want to set properties for.

  4. Select or clear the Allow Resizing box.

Note This setting is not affected by the Allow Toolbar/Menu Changes setting in the Startup dialog box (Tools menu).


Prevent or allow showing and hiding specific toolbars or menu bars

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, click Properties.

  3. In the Selected Toolbar box, select the name of the toolbar or menu bar you want to set properties for.

  4. Select or clear the Allow Showing/Hiding box.

Notes

  • You can hide all built-in toolbars automatically to prevent users from working with them. For more information, click [image] .

  • If you clear this option, make sure the Show On Toolbars Menu box is also cleared; otherwise the toolbar or menu bar will appear on the menu, but you won't be able to select it.


Animate menus to slide down or unfold when displayed

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Options tab, select the menu animation you want to use.


 Show or hide a toolbar, menu bar, or shortcut menu

Show or hide a toolbar, menu bar, or shortcut menu

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, select or clear the check box for the item you want to show or hide. To show a particular shortcut menu, select Shortcut Menus, click the category for the shortcut menu you want to show, then click the name of the shortcut menu. To show any custom shortcut menus, click the Custom category.

Tips

  • To quickly hide a floating toolbar, click its Close button.

  • To quickly show or hide a custom toolbar or menu bar, right-click any toolbar or menu bar, and then click the name of the bar on the shortcut menu.


Show or hide shortcut keys in ScreenTips (ToolTips)

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Click the Options tab.

  3. Select or clear the Show Shortcut Keys In ScreenTips check box.

Note This setting affects all Microsoft Office programs except Microsoft Excel.


Show or hide toolbar ScreenTips (ToolTips)

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Click the Options tab.

  3. Select or clear the Show ScreenTips On Toolbars check box.

Note This setting affects all Microsoft Office programs.


 Move a toolbar or menu bar

Move a toolbar or menu bar

  1. Do one of the following:
    • On a docked toolbar or menu bar, click the move handle Left edge of a docked toolbar.

    • On a floating toolbar or menu bar, click the title bar.
  2. Drag the toolbar or menu bar to a new location. If you drag a toolbar or menu bar to the edge of the program window, it becomes docked.

Note When you move one docked toolbar, this may affect the location and size of other toolbars on the same row.


 Resize a toolbar or menu bar

Resize a toolbar or menu bar

  • To resize a floating toolbar or menu bar, move the pointer over any edge until it changes to a double-headed arrow, and then drag the edge.

  • To resize a docked toolbar that is in the same row as another toolbar, click the move handle Left edge of a docked toolbar and then drag the edge of the toolbar.

Notes

  • You can't resize a docked toolbar that is on its own row, that is the leftmost toolbar in a horizontal row, or that is the topmost toolbar in a vertical row of toolbars.

  • When you resize one docked toolbar, this may affect the location and size of other toolbars on the same row.


 Keep color and style palettes displayed while designing a form or report

Keep color and style palettes displayed while designing a form or report

To keep a palette displayed the entire time you're designing a form, report, or data access page, drag the palette away from its toolbar button.

  1. In form Design view, report Design view, or data access page Design view, click the arrow next to one of the following buttons on the Formatting toolbar, depending on the palette you want to use.
    This
    button     		Displays
    this palette     		For
    selecting
    Fill/Back Color | Background colors for a control or section.
    Font/Fore Color | A font color for a control.
    Line/Border Color | The color of a control's border.
    Line/Border Width | The thickness of a control's border.
    Special Effect | A flat, raised, or sunken effect for a control or section.
  2. Click the bar at the top of the palette and drag the palette away from the button.


Show font names in the Office interface font

  1. On the Tools menu, click Customize, and then click the Options tab.

  2. Clear the List font names in their font check box.

Note The List font names in their font check box affects all of your Microsoft Office programs.


 About tracking work and finding files using Microsoft Outlook

About tracking work and finding files using Microsoft Outlook

Microsoft Outlook is a messaging and collaboration client you can use to send mail; schedule meetings, events, and appointments; store a list of contacts; maintain a task list for yourself and assign tasks to others; and track your activities. If you've installed Outlook, you can use some of its features from within your other Microsoft Office programs.

If Outlook isn't available, click Programs on the Start menu, and then click Microsoft Outlook to install it.

  • With the Outlook Journal, you can automatically track all files you create in any Office program. For example, if you need to track databases based on when they're created and revised instead of where they're located, you can have Outlook create a journal entry each time you work on a database. Each entry represents one activity. How to automatically track databases in the Outlook Journal.

  • If you want to track only one file in an Office program or track files in programs other than Office, you can track individual files by manually recording each activity you perform on the file in the Outlook Journal. How to manually record work on any file in the Outlook Journal.

  • You can link tasks, journal entries, spreadsheets, documents, databases, and presentations to a contact that you correspond with so that you can keep track of all items related to a contact. For example, if you want to track databases based on one or more contacts responsible for working on a particular database, you can link contact information to a database and other related items, such as spreadsheets, e-mail messages, and appointments. Link tasks, journal entries, and documents to a contact.

  • If you have installed the Microsoft Outlook Integrated File Management system, you can use Outlook to find files for any Office program, files on the network, and Outlook items. You can sort, group, and change the view for your search results. You can also open an item or file in the search results by double-clicking it. You can save search results as a file you can share with others, and you can open a search by double-clicking a saved search file. How to use Microsoft Outlook to find files or Outlook items.


Track work on a database and find files by using Microsoft Outlook

What do you want to do?

Automatically track databases in the Outlook Journal

Manually record work on any file in the Outlook Journal

Use Microsoft Outlook to find files or Outlook items

Link tasks, journal entries, and documents to a contact

Not sure which choice you want?


Automatically track databases in the Outlook Journal

  1. Start Outlook.

  2. On the Tools menu, click Options.

  3. Click the Preferences tab, and then click Journal Options.

  4. In the Also record files from list, select the Microsoft Access check box.

Note Databases that are automatically recorded in the Outlook Journal sometimes take a few minutes to appear in the Journal.


 Manually record work on any file in the Outlook Journal

Manually record work on any file in the Outlook Journal

  1. Make sure the file you want to record work for is not open.

  2. Start Outlook.

  3. On the Outlook Bar, click Other or Other Shortcuts.

  4. Double-click My Computer [image] and then locate the file you want to record.

    If My Computer is not available, you need to install the Microsoft Outlook Integrated File Management system. Learn how to install a program or component.

  5. On the Outlook Bar, click My Shortcuts and make sure that Journal [image] is visible.

  6. Drag the file you want to record onto Journal [image].

  7. Select the options you want, and then click Save and Close [image] .


Use Microsoft Outlook to find files or Outlook items

  • Click the Windows Start button, point to Find, and then click Using Microsoft Outlook.

Note To search for all files on your computer, you must have the Microsoft Outlook Integrated File Management system installed on your computer. How to install a program or component.


 Manage time, contacts, tasks, and messages from the Office Shortcut Bar

Manage time, contacts, tasks, and messages from the Office Shortcut Bar

If you use Microsoft Office and you installed Microsoft Outlook when you installed Office, the Office toolbar on the Office Shortcut Bar provides six, single-click shortcuts to the most common Microsoft Outlook features.

Click | To
New Message | Send an e-mail message from Outlook.
New Appointment | Add a new appointment to your Calendar in Outlook.
New Task | Add a new task to your task list in Outlook.
New Contact | Create a contact in Outlook.
New Journal | Manually record an activity in the Journal in Outlook.
New Note | Create a note in Outlook.


 Send a data access page as the body of an e-mail message

Send a data access page as the body of an e-mail message

Important A data access page is connected to an OLE DB data source, either a Microsoft Access database or Microsoft SQL Server database. For the data access page to work properly, the database must be available to users of the page. Learn about sharing the OLE DB data source of a page.

  1. In the Database window, click Pages under Objects, and then the name of the page you want to send as the body of an e-mail message.

  2. On the File menu, click Send To and then choose Mail Recipient.

    Access opens the data access page in Page Design view so that you can make changes, such as adding text or notes to the data access page for the mail recipient, before you send the data access page.

  3. Enter recipient names in the To and Cc boxes. Separate names with a semicolon (;).

    To select recipient names from a list, click To or Cc. The name of the object is displayed in the Subject box by default, but you can type your own subject name. You can manually check names before sending the message. You can also set additional options for the e-mail message.

  4. Click Send on the message header.


 Send a database object's output as an attachment to an e-mail message

Send a database object's output as an attachment to an e-mail message

  1. In the Database window, click the type of database object you want under Objects, and then click the name of the database object you want to send as an attachment.

    If you want to send a selection of a datasheet, open the datasheet and select the portion of the datasheet before continuing.

  2. On the File menu, click Send To and then select Mail Recipient (as Attachment).

  3. Click the file format you want to attach, and then click OK.

    Microsoft Access opens a new e-mail message and attaches the output of the object in the format you selected.

  4. Enter recipient names in the To and Cc boxes. Separate names with a semicolon (;).

    To select recipient names from a list, click To or Cc. The name of the object is displayed in the Subject box by default, but you can type your own subject name. You can manually check names before sending the message. You can also set additional options for the e-mail message.

  5. Click Send on the message header.

Notes

  • You can attach a database object in an e-mail mail message in one of the following output formats: HTML (.htm, .html), Microsoft Excel (.xls), Microsoft MS-DOS text (.txt), Rich Text Format (.rtf), in the case of a data access page, data access page (.htm, .html), or, in the case of a report, report snapshot (.snp).

  • Although you cannot attach a database object in either Microsoft Internet Information Services (.htx, .idc) or Microsoft Active Server Pages (.asp) output formats, you can export the object to the desired output format and then attach the files in a mail program, such as Microsoft Outlook. Learn about exporting data.

  • You can only send a page in data access page (.htm, .html) output format. You can only send modules in MS-DOS text (.txt) output format. You cannot send macros or database diagrams (Microsoft Access project only).


Set options for sending an e-mail message

What do you want to do?

Set the importance and sensitivity level

Set the importance level for a message

Set a message flag

Mark a message as private, personal, or confidential

Set the security level

Add security to messages

Track messages and replies

Receive notification when a message is delivered

Receive notification when a message is read

Add voting buttons to an e-mail message

Set delivery options

Save a copy of a message you send

Make a sent message unavailable after a specified date

Delay delivery of a message

Have replies to your message sent to another user

About assigning messages to categories

Assign a message to a category

Set an e-mail account

Choose which e-mail account to use to send a message

Get information about your Microsoft Outlook installation

Not sure which choice you want?


 Manually check names before sending a message

Manually check names before sending a message

Before you send the output of a database object, or a data access page as an e-mail message, recipient names you type in the To, Cc, and Bcc boxes are automatically checked against names in the Address Book. If an exact match is found, the name is underlined. If multiple names are found that match the name you type, the Check Names dialog box is displayed so that you can select the correct name.

  1. Display the message header by sending a database object as an attachment or sending a data access page as the body of an e-mail message.

  2. Enter recipient names in the To and Cc boxes. Separate names with a semicolon (;).

    To select recipient names from a list, click To or Cc.

  3. Click Check Names [image].

    Tip You cam also press CTRL+K.


 System requirements for sending and viewing a data access page

System requirements for sending and viewing a data access page

The following are system requirements for sending and viewing a data access page.

System requirements for sending a data access page

To send a data access page through e-mail you need one of the following:

  • Microsoft Outlook 2000

  • Outlook Express version 5.0

  • Microsoft Exchange

System requirements for viewing a data access page sent through e-mail

To view a data access page sent as an e-mail message, recipients need on of the following:

  • Microsoft Outlook 2000

  • Outlook Express version 5.0

  • The combination of Microsoft Outlook 98 and Microsoft Internet Explorer 5 or later

  • The combination of Outlook Express and Microsoft Internet Explorer 5 or later

Notes

  • Sending a data access page through e-mail might not work across electronic mail gateways.

  • It is recommended that you send a data access page as an attachment in an e-mail message if the recipient is using Microsoft Office 97 or earlier.


 Open recently browsed files

Open recently browsed files

  1. If the Web toolbar isn't displayed, on the View menu, point to Toolbars, and then click Web.

  2. On the Web toolbar, click Back [image] to open the previous document in the History list. To open the next document, click Forward [image] .


 Open the Web search page

Open the Web search page

  1. If the Web toolbar isn't displayed, on the View menu, point to Toolbars, and then click Web.

  2. On the Web toolbar, click Search the Web [image] .

Note A search page provides an organized way to find and go to other Internet sites or to files on an intranet.


 Open the Web start page

Open the Web start page

  1. If the Web toolbar isn't displayed, on the View menu, point to Toolbars, and then click Web.

  2. On the Web toolbar, click Start Page [image] .

Note When you start a World Wide Web browser, the start page is the first page that appears in the browser. You can set this location to any Web site, or to a file on your computer hard disk.


 Refresh the display of the active file or Web page

Refresh the display of the active file or Web page

A Web page may be modified by the author while you have it open. When you refresh a document, it gets the latest version of the original file located on the network server, the Internet, or your hard disk.

  1. If the Web toolbar isn't displayed, on the View menu, point to Toolbars, and then click Web.

  2. On the Web toolbar, click Refresh Current Page [image] .


 Show or hide all toolbars except the Web toolbar

Show or hide all toolbars except the Web toolbar

  1. If the Web toolbar isn't displayed, on the View menu, point to Toolbars, and then click Web.

  2. On the Web toolbar, click Show Only Web Toolbar [image] .


 Set a hyperlink base for an Access database or Access project

Set a hyperlink base for an Access database or Access project

You can set the path of the relative links in a Microsoft Access database or Microsoft Access project by setting the HyperlinkBase property. Learn about relative links and setting a hyperlink base.

  1. Open the database you want to set a hyperlink base for.

  2. On the File menu, click Database Properties, and then click the Summary tab.

    In the Hyperlink base box, type the path of the relative link you want to use for all the hyperlinks you create in this database. The path may point to a location on your hard drive, a network drive, an intranet or the Internet.


 Turn off automatic completion of file names and URLs

Turn off automatic completion of file names and URLs

If you have Microsoft Internet Explorer 4.0 or later, you can turn off the feature that automatically suggests a match for file names and URLs as you type them in the Insert Hyperlink dialog boxes in Office programs, and in the Address box in Internet Explorer.

  1. Start or switch to Internet Explorer.

  2. Do one of the following:

    If you have Microsoft Internet Explorer 4.0, click Internet Options on the View menu, and on the Advanced tab, clear the Use AutoComplete check box.

    If you have Microsoft Internet Explorer 5, click Internet Options on the Tools menu, and on the Advanced tab, clear the Use inline AutoComplete in integrated shell check box.


Work with FTP

What do you want to do?

Add an FTP site to the list of Internet sites

Remove an FTP site from the list of Internet sites

Change the logon name or password for an FTP site

Save a data access page to an FTP site


 About the Web toolbar

About the Web toolbar

The Web toolbar is available in Access to make it easy to browse Office documents that contain hyperlinks. You can use the Web toolbar to open a start page or a search page in your Web browser. When you find interesting locations on the Web, you can use the Web toolbar to add them to your Favorites folder so you can quickly find them again. The Web toolbar keeps a list of the last 25 locations you've used the toolbar or a hyperlink to jump to, making it easy to return to any item on the list.


 About the three types of Web pages Microsoft Access creates

About the three types of Web pages Microsoft Access creates

This topic provides reference information about:

Data access pages

Server-generated HTML

Static HTML

Data access pages

You create a data access pages as a database object that contains a shortcut to the location of the page's corresponding HTML file. Learn about creating data access pages.

Use pages to view, edit, update, delete, filter, group, and sort live data from either a Microsoft Access database or a Microsoft SQL Server database, in Microsoft Internet Explorer 5 or later. A page can also contain additional controls called including a spreadsheet, a PivotTable list, and a chart.

To make your pages available on the World Wide Web, you publish the pages to Web Folders or a Web server, and make the Access database or SQL Server database available to users of the page.

Internet Explorer needs to download the page only once from the Web server to let you view and interact with the data on the page. Because a page uses Dynamic HTML, access to the database is generally very efficient in a client/server environment.

Return to top

Server-generated HTML

You can create server-generated HTML files, either ASP or IDC/HTX, from tables, queries, and forms. Server-generated HTML files are displayed in a table format in a Web browser. Use server-generated HTML files when you want to use any Web browser, your data changes frequently, you need to see live data in a table connected to an ODBC data source, but you only need to see read-only data.

Once you output ASP or IDC/HTX files, you must publish these files to be processed on a supported Web server product and platform.

Each time a user opens or refreshes an ASP or HTX file from a Web browser, the Web server dynamically creates an HTML file, and then sends that HTML file to the Web browser.

Return to top

Static HTML

You can create static HTML files from tables, queries, forms, and reports. In a Web browser, reports display in a report format, and tables, queries, and forms display in a datasheet format. Use static HTML files when you want to use any Web browser that supports HTML version 3.2 or later and your data does not change frequently.

To make your static HTML files available on the World Wide Web, you publish the files to Web Folders or a Web server.

When you access the data through a Web browser, the browser only needs to download the static HTML file once from the Web server to let you view the data. However, the resulting HTML files are a snapshot of the data at the time you published your files. There is no ODBC data source connected to the static HTML file, and If your data changes, you must export your files again to be able to view new data in a Web browser.

Return to top


 About Web page client/server products and platforms

About Web page client/server products and platforms

The following table summarizes supported products, platforms, and Web page output format files.

Web page
output file format

HTML
Version

 Supported client browser

Supported server
product and platform
data access pages (*.htm, *.html) Dynamic HTML 4.0 or later Microsoft Internet Explorer 5 or later All Web server products and platforms

Note IIS 4.0 on Microsoft Windows NT Server 4.0 is required to prevent cross-domain access. Learn about securing a data access page.
Server-generated HTML, ASP (*.asp) All Web browsers
  • IIS 3.0 with Active Server Pages on Windows NT Server 4.0

  • IIS 4.0 on Windows NT Server 4.0

  • Personal Web Server with Active Server Pages on Microsoft Windows NT Workstation 4.0

  • Personal Web Server with Active Server Pages on Microsoft Windows 95
Server-generated HTML, IDC/HTX (*.idc, *.htx) All Web browsers
  • Microsoft Internet Information Server (IIS) 1.x with Internet Database Connector add-in on Windows NT Server 3.51

  • IIS 2.0 on Windows NT Server 3.51

  • IIS 3.0 with Active Server Pages on Windows NT Server 4.0

  • IIS 4.0 on Windows NT Server 4.0

  • Personal Web Server on Windows NT Workstation 4.0

  • Personal Web Server on Windows 95
Static HTML (*.htm, *.html) HTML 3.2 or later All Web browsers All Web server products and platforms

Note To use any Web page from a client computer, you need a Web browser, such as Microsoft Internet Explorer, and a modem or network connection to the Internet or intranet server where the Web pages are located. For information about how to set up Internet access, see the Microsoft Office 2000 Resource Kit. For information about how to obtain the Resource Kit, click [image] .


 How your Web server processes server-generated HTML format

How your Web server processes server-generated HTML format

This topic provides reference information about:

How your Web server processes IDC/HTX files

How your Web server processes ASP files

How your Web server processes IDC/HTX files

When you output a table, query, or form as IDC/HTX files, instead of an .html file, Microsoft Access creates an HTML extension file (.htx).and an Internet Database Connector file (.idc). Internet Database Connector (httpodbc.dll) is a component of Microsoft Internet Information Server.

The .idc file contains a query in the form of an SQL statement and information that Microsoft Internet Information Server uses to connect to an ODBC data source, in this case, either a Microsoft Access database or Microsoft SQL Server database. The connection information includes the data source name and often a user name and password, both of which are optional.

The .htx file is an HTML file that contains formatting tags and instructions, and, instead of data, placeholders indicating where to insert the values returned from the query in the .idc file.

After you publish your IDC/HTX files to a Web Server, Microsoft Internet Information Server, upon request from a Web browser, opens the database (by using the appropriate ODBC driver and the .idc file connection information), runs the query in the .idc file to access the data, merges the results and .htx file into one .html file, and then sends the dynamically created .html file to the Web browser for display as a Web page.

Return to top

How your Web server processes ASP files

When you output a table, query, or form as an ASP file, instead of an .html file, Microsoft Access creates a Microsoft Active Server Page (.asp) file. Active Server is a component of Microsoft Internet Information Server 3.0 or later.

The .asp file contains HTML tags interspersed with one or more queries in the form of SQL statements, template directives, and Visual Basic Script code containing references to ActiveX Server Controls. The .asp file also contains ODBC connection information to connect to an ODBC data source, in this case, an Access or Microsoft SQL Server database. The connection information includes the data source name, and often a user name and password, both of which are optional.

After you publish your ASP files to a Web Server, Microsoft Internet Information Server, upon request from a Web browser, runs the Visual Basic Scripting code, calls the ActiveX Server Controls, opens the database (using the appropriate ODBC driver and the .asp file connection information), runs the queries in the .asp file to access the data, merges the results and HTML tags in the .asp file into one .html file, and then sends the dynamically created .html file to the Web browser for display as a Web page.

Return to top


 About Web Folders

About Web Folders

Before you can create, copy, save, or manage folders and files on a Web server, you must have access to one. To find a Web server that you can connect to, see your system administrator.

This topic provides reference information about:

Saving files to Web servers

Viewing and managing folders and files

More information

Saving files to Web servers

You can use the Web Folders feature to save a data access page to a Web server. You can access Web Folders from Windows Explorer or from Microsoft Access in the Open (File menu), Save As Data Access Page (page File menu), or Locate Web Page (Edit Web page that already exists object shortcut) dialog boxes.

The Add a Web Folder Wizard is located in the Web Folders root directory in Windows Explorer. You can use this wizard to create a folder that is a shortcut to a Web server. Each of these shortcuts is called a Web folder. You can also create a Web folder in Microsoft Access from the Open, Save As Data Access Page, or Locate Web Page dialog boxes by clicking Web Folders [image] on the Places Bar, and then clicking Create New Folder [image]. After you create the Web folder, you can save data access page files and folders to it.

Return to top

Viewing and managing the contents of Web folders

You can view and manage data access page folders and files in a Web folder in three ways:

In Windows Explorer When you view the contents of a Web folder, you see a list of folders and files, and their associated URLs. You can move, copy, rename, and delete these files and folders just as if they were on a regular file server, and you can view the folder and file properties. You can also drag and drop files between Web servers, between a Web server and a file server, and between a Web server and your hard disk.

In Access From the Open (File menu) or Locate Web Page (Edit Web page that already exists object shortcut) dialog boxes, you can view and open the contents of Web folders. From the Save As Data Access Page dialog box (page File menu), you can save a copy of a data access page to a Web folder. You can also create a Web folder by clicking Web Folders [image] on the Places Bar, and then clicking Create New Folder [image].

In a browser If you connect to a Web server that runs Microsoft Office Server Extensions, you can view the contents of Web folders and associated file system properties in your browser.

Return to top

More information

Create a Web folder

Open a data access page on a Web Server

Save a copy of a data access page to a Web Server in Access

Save a copy of a data access page to a Web Server in Windows Explorer

Where to save your data access pages on the Web

Guidelines for managing Web files and links

Return to top


 Create a Web folder

Create a Web folder

Before you can create a Web folder, you should see your system administrator for the URL of a Web server that you can save files to.

  1. In My Computer or Windows Explorer, double-click Web Folders.

  2. Double-click Add a Web Folder.

  3. Follow the instructions in the Add a Web Folder Wizard.

  4. To save files to the Web server, drag them and any supporting folders to the newly created Web folder.

Notes

  • To create a Web folder from within Microsoft Access: in the Open dialog box (File menu), Save As Data Access Page dialog box (data access page File menu), or Locate Web Page dialog box (Edit Web page that already exists object shortcut), click Web Folders [image] on the Places Bar, click Create New Folder [image], and then follow the instructions in the Add a Web Folder Wizard.

  • To quickly create a Web folder in Microsoft Access for an existing Web server location, type the Web address in the File name box of the Save As Data Access Page dialog box (page File menu). For example, type http://myserver to create a Web folder to that destination.


 About where to save on the Web

About where to save on the Web

The steps that you take to save your data access pages to the Web depend on where you want to share them. This topic provides reference information about:

Making your data access pages available on an intranet

Making your data access pages available on the Internet

Managing Web pages on an intranet or the Internet

More information

Making your data access pages available on an intranet

If your company uses an intranet that is based on Internet protocols, you can use Web Folders to save copies of your data access pages to a Web server. You must have access to a Web server before you can copy or manage folders and files on a Web server. To get the URL of a Web server that you can save files to, see your system administrator.

  • If your Web server supports Web folders, you can use Web folders to save copies of your Web pages to the Web server. Before you can copy or manage folders and files on a Web server, see your system administrator or Internet service provider to get access and the URL of a Web server you can save files to. Learn about Web Folders.

  • If your Web server supports File Transfer Protocol (FTP) you can save a data access page to an FTP site. See your system administrator or Internet service provider to get access to an FTP site you can save files to.

  • If you have questions about saving your data access pages to the intranet, see your system administrator.

Return to top

Making your data access page available on the Internet

To make your data access pages available on the Internet, you need to either locate an Internet service provider that allocates space for data access pages or install Web server software on your computer. Some factors to consider in setting up your computer as a Web server are your computer's speed and availability. If you don't want to leave your computer on all day or most of the day, you might not want to set up your computer as a Web server.

Here are some options for saving your Web pages on the Internet.

  • If your Web server supports Web folders, you can use Web folders to save copies of your Web pages to the Web server. Before you can copy or manage folders and files on a Web server, see your system administrator or Internet Service Provider to get access and the URL of a Web server you can save files to. Learn about Web Folders.

  • If your Web server supports FTP, you can save a data access page to an FTP site. See your system administrator or Internet Service Provider to get access to a location you can save files to.

  • If you have questions about saving your data access pages to the Internet, see your system administrator or Internet Service provider.

Return to top

Managing data access pages on an intranet or the Internet

If you are working with an Internet service provider or your organization's Web administrator, you should ask how the data access pages, graphics files, and other files should be structured on the server. For example, find out whether you need to create separate folders for bullets and pictures, or whether you need to store all the files in one location. If you plan to use forms or image maps, ask about any limitations on using these items, as they require additional server support. Learn about guidelines for managing Web files and links.

Return to top

More information

Publish data access pages and other Web pages

Troubleshoot data access page options

Return to top


 Guidelines for managing Web files and links

Guidelines for managing Web files and links

This topic provides reference information about:

Managing and naming supporting files

Testing links

More information

When you create a data access page, Microsoft Access manages the related files and plans the links and hyperlinks so that the images appear and the links work when the pages are placed on the final Web server.

Managing and naming supporting files

When you save your file as a data access page in Design view, all supporting files — such as bullets, background textures, and graphics — are by default organized in a supporting folder. If you move or copy your data access page to another location, you must also move the supporting folder so that you maintain all links to your page.

For example, suppose you have a page called Page1.htm. It includes bullets, which are stored in a supporting folder called Page1_files. The relative paths for the image files are \Page1_files\image001.gif and \Page1_files\image002.gif. If you move Page1.htm, you must also move the supporting folder (Page1_files) to the new location.

By default, the name of the supporting folder is the name of the data access page plus an underscore (_), a period (.), or a hyphen (-) and the word "files." The word "files" will appear in the language of the version of Microsoft Office 2000 used to save the file as a data access page. For example, suppose you use the Dutch language version of Office 2000 to save a file called Page1 as a data access page. The default name of the supporting folder would be Page1_bestanden. Learn more about the default name for supporting folders.

Return to top

Testing links

After you have published your data access page to the Internet or an intranet, you should test them in a Web browser. Make sure that all the graphics are displayed and that hyperlinks go to the correct destinations.

Return to top

More information

Create a hyperlink on a data access page

About bound hyperlinks in a data access page

Return to top


 Publish a data access page to Web Folders or any Web server

Publish a data access page to Web Folders or any Web server

Important A data access page is connected to an OLE DB data source, either a Microsoft Access database or Microsoft SQL Server database. For the page to work properly, the database must be available to users of the page. Learn about sharing the OLE DB data source of a page.

To publish a data access page file by saving it to Web Folders

  • When you first create the page, save it to a Web folder underneath Web Folders. If you create the page in a location other than a Web folder underneath Web Folders, you can move the corresponding HTML file and related files and folders by using the Save As command on the File menu in Access. By using the Save As command, you can create a new data access page, and specify a Web folder underneath Web Folders.

Learn about creating a page.

Learn about saving a page to Web Folders.

Notes

  • Microsoft Access automatically saves related files such as graphics, style sheets, linked files, and the folders that contain these files when you save any Web page to Web Folders. Learn about managing Web files and links.

  • You can only use the Web Folders shortcut or enter a Uniform Resource Locator (URL) in the File name box of the Open dialog box when you edit a Web page that already exists or create a data access page in page Design view. Learn about Web Folders.

To publish a data access page to any Web server

  1. Copy the HTML file corresponding to the page and any other related files and folders in Windows Explorer to a folder underneath the root directory of the Web server. The default root directory is \Webshare\Wwwroot for Personal Web Server and \Inetpub\Wwwroot for Microsoft Internet Information Server.

  2. Copy related files such as graphics, style sheets, linked files, and any folders that may contain these files to the folder, or make sure the related files can be located by the Web server. Learn about managing Web files and links.


 About sharing the database connected to a data access page

About sharing the database connected to a data access page

The Microsoft Access database or Microsoft SQL Server database that is the OLE DB data source for a data access page must be on a shared server or computer in order for other users to view and interact with the page in a Web browser or in a mail message.

It's a good idea to place the database on a shared server or computer before you create your page. If you move the database that the page is connected to after you create the page, you must change the OLE DB data source connection of the page. To do so, in page Design view, right-click on the database icon in the field list, and then click Connection.

Important Make sure you use a universal naming convention (UNC) path, instead of relying on the drive letter of a mapped network drive in Windows Explorer. A drive letter can vary on a computer or may not always be defined, whereas a UNC path is a reliable and consistent way for the page to locate the data source.

Although the data source of a page can only be an Access database or SQL Server database, you can make other data formats accessible from a page by using linked tables from an Access database.

To make your data access pages as secure as possible, you must put the Access database or SQL Server database on the same Web server as the data access page.

More information

Sharing an Access database

Sharing an SQL Server database

Importing and linking to other data formats

Securing a data access page


 Publish server-generated HTML files to a Web server

Publish server-generated HTML files to a Web server

To use server-generated HTML files (either ASP or IDC/HTX) on a Web server, you need to do the following.

  1. Install the appropriate software on the computer that will be the Web server and that will process the server-generated HTML files.

  2. Create a folder under the root directory to contain the ASP or IDC/HTX files. The default root directory is \Webshare\Wwwroot for Personal Web Server and \Inetpub\Wwwroot for Microsoft Internet Information Server.

  3. Define the appropriate privileges for the folder Execute for Windows NT 4.0 or later and Execute Scripts for Windows 95 or later. For more information about sharing a folder, see Windows Help.

  4. Copy the ASP or IDC/HTX files to the folder. Copy related files such as graphics, linked files, and any folders that may contain these files to the folder, or make sure the related files can be located by the Web server software. Learn about managing Web pages and links.

  5. Either copy the Microsoft Access database or Microsoft SQL Server database to the folder, or define its network location in the ODBC data source definition in step 6.

  6. Define the ODBC data source as a System DSN on the Web server. Make sure that the data source name is the same name as the one you entered in the appropriate Output Options dialog box when you output the ASP or IDC/HTX files. Learn about defining an ODBC data source.

  7. If desired, define database security for the ODBC data source, but ensure that users can access the ODBC data source.

    For a Microsoft Access database, create a user-level security username and password to allow users to access the Access database from the Web page. If you do not create a user-level security username or password, the default username is Admin, and no password is used. Learn about user-level security in an Access database.

    For a Microsoft Access project, in the Username and Password boxes, create a database username and password to allow users to access the Microsoft SQL Server database from the Web page. If you do not create a username or password, the default username is Sa, and no password is used. Learn about SQL Server database security.

    The username and password must match the username and password that you enter in the User to Connect As and Password for User boxes of the Microsoft Active Server Pages Output Options or HTX/IDC Output Options dialog boxes that appear when you output the ASP or IDC/HTX files.

Note If you need to export multiple datasheets, you can automate the operation by creating a macro or creating a Visual Basic for Applications program. This is particularly useful when you frequently export datasheets to test and build a Web site.


 Publish static HTML files to Web Folders or any Web server

Publish static HTML files to Web Folders or any Web server

  1. To publish a static HTML file to Web Folders, copy the static HTML file(s) to a Web folder under Web Folders by using Windows Explorer. More information about Web Folders.

    To publish a static HTML file to any Web server, copy the static HTML file to a folder under the root directory of the Web server by using Windows Explorer. The default root directory is \Webshare\Wwwroot for Personal Web Server and \Inetpub\Wwwroot for Microsoft Internet Information Server.

  2. Copy related files such as graphics, style sheets, linked files, and any folders that may contain these files to the folder, or make sure the related files can be located by the Web server. Learn about managing Web files and links.

Note If you need to export multiple tables, queries, forms, and reports, you can automate the operation by creating a macro or creating a Visual Basic for Applications program. This is particularly useful when you frequently export tables, queries, forms, and reports to test and build a Web site.


 Default names for data access page supporting folders

Default names for data access page supporting folders

When you save your data access page in Design view, all supporting files — such as bullets, background textures, and graphics — are by default organized in a supporting folder. By default, the name of the supporting folder is the name of the data access page plus an underscore (_), a period (.), or a hyphen (-) and the word "files." The word "files" will appear in the language of the version of Microsoft Office 2000 used to save the file as a data access page. For example, suppose you use the Dutch language version of Office 2000 to save a file called Page1 as a data access page. The default name of the supporting folder would be Page1_bestanden.

Note If you save your data access page with a short file name (maximum of eight characters, plus a three-character file extension) by clearing the Use long file names whenever possible check box in the Web Options dialog box, the supporting folder is the name of the data access page without the word "files."

The following table shows the translation for "files" in each language version of Office 2000.

Office 2000 language | Default name for Web page supporting folder
Arabic | ".files"
Basque | "_fitxategiak"
Brazilian | "_arquivos"
Bulgarian | ".files"
Catalan | "_fitxers"
Chinese (Simplified) | ".files"
Chinese (Traditional) | ".files"
Croatian | "_datoteke"
Czech | "_soubory"
Danish | "-filer"
Dutch | "_bestanden"
English | "_files"
Estonian | "_failid"
Finnish | "_tiedostot"
French | "_fichiers"
German | "-Dateien"
Greek | ".files"
Hebrew | ".files"
Hungarian | "_elemei"
Italian | "-file"
Japanese | ".files"
Korean | ".files"
Latvian | "_fails"
Lithuanian | "_bylos"
Norwegian | "-filer"
Polish | "_pliki"
Portuguese | "_ficheiros"
Romanian | ".files"
Russian | ".files"
Serbian (Cyrillic) | ".files"
Serbian (Latin) | "_fajlovi"
Slovakian | ".files"
Slovenian | "_datoteke"
Spanish | "_archivos"
Swedish | "-filer"
Thai | ".files"
Turkish | "_dosyalar"
Ukranian | ".files"
Vietnamese | ".files"


 Save a copy of a data access page to a Web server in Windows Explorer

Save a copy of a data access page to a Web server in Windows Explorer

  1. In Windows Explorer, right-click the file that you want to copy or move to a Web server.

  2. On the shortcut menu, click Copy.

  3. Double-click Web Folders.

  4. In the list of Web folder sites, double-click the folder that you want, and then right-click the destination folder you want to save the data access page to.

  5. On the shortcut menu, click Paste.

  6. If you don't see the Web server that you want to save your data access page to, double-click Add a Web Folder at the root directory of Web Folders to add a new Web folder. How to create a Web folder.

Tip When you save a data access page, all supporting files — such as bullets, background textures, and graphics — are by default organized in a supporting folder. If you move or copy your page to another location, you must also move the supporting folder so that you maintain all links to your page. Learn more about managing Web files and links.


 Save a copy of a data access page to a Web server in Access

Save a copy of a data access page to a Web server in Access

You can save a copy of a Microsoft Access data access page to a Web server.

  1. In the Database window, click Pages [image] under Objects.

  2. Double-click the data access page that you want to open.

  3. On the File menu, click Save As.

  4. In the Save Data Access Page <object name> To box, type the name of the new data access page.

  5. On the Places Bar, in the Save As Data Access Page dialog box, click Web Folders.

  6. In the list of Web folder sites, double-click the folder that you want, and then double-click the location you want to save the data access page to.

  7. Click Save.

Tip To quickly create a Web folder in Microsoft Access for an existing Web server location, type the Web address in the File name box of the Save As Data Access Page dialog box (page File menu). For example, type http://myserver to create a Web folder to that destination.


 Open a data access page on a Web server in Access

Open a data access page on a Web server in Access

  1. In the Database window, click Pages [image] under Objects.

  2. Double-click the Edit Web page that already exists object shortcut.

  3. On the Places Bar, click Web Folders [image] , and then double-click the folder on the Web that contains the data access page that you want to open.

  4. In the folder list, locate and open the folder that contains the data access page.

  5. Double-click the page you want to open.

Note Make sure your supporting files folder is also in the same folder so that any links are maintained. Learn about guidelines for managing Web files and links.

Tips

  • To quickly open a data access page on a Web server, in the File name box, type the address for the page you want to open, and then press ENTER. For example, you might type http://sales/february/Page1.htm to open a page from the sales department. If a Web folder at http://sales/february doesn't already exist, it will be created automatically when you type an address in the File name box.

  • If the Web toolbar is displayed, you can type the address in the Address box, and then press ENTER to quickly open the page in your browser.


 About online meetings

About online meetings

This topic provides reference information about:

Hosting an online meeting

Participating in an online meeting

Collaborating in an online meeting

More information

The integration of the Microsoft NetMeeting program with Microsoft Office allows you to share and exchange information with people at different sites in real time as if everyone were in the same room. You can initiate an online meeting from within any Office application. (You can also work directly in the NetMeeting program by clicking NetMeeting on the Windows Start menu.) When you start an online meeting from within an Office application, NetMeeting automatically starts in the background and allows you to begin sharing the contents of your file. You can either host an online meeting or be invited to participate in one.

Hosting an online meeting

Start the meeting You can either schedule the meeting in advance by using Microsoft Outlook (see Microsoft Outlook Help) or start an impromptu online meeting from within the Microsoft Access database, Microsoft Access project, or data access page you want to share. If the participants are available and they decide to accept your invitation, the online meeting begins.

Control the Access database, Access project, or data access page At the start of an online meeting, you are the only person who has control of the Access database, Access project, or data access page, although all participants can see it on their screens. You can allow participants to make changes by turning on collaboration, and you can also turn off collaboration at any time. When collaboration is turned off, the other participants can no longer make changes, but they will be able to watch you work. When collaboration is turned on, each person in the online meeting can take turns editing and controlling the Access data file. When someone else is in control, you will not have the use of your cursor not only in the Access data file, but also for any other purpose. The initials of the person in control appear next to the pointer.

Add participants to a meeting in progress You can invite participants at any time to join an online meeting already in progress. Participants whom you invite to an impromptu online meeting must have NetMeeting running on their computers for them to receive your online meeting invitation. How to start Microsoft NetMeeting.

Return to top

Participating in an online meeting

When you're invited to participate in an online meeting, you'll receive a message requesting you to join an upcoming or ongoing online meeting at a specified time and date. When you accept a call to join an online meeting, the Online Meeting toolbar and the Microsoft Access database, Microsoft Access project, or data access page that is being shared appear on your screen.

Return to top

Collaborating in an online meeting

In an online meeting, you can share applications and documents, send text messages in Chat, transfer files, and work on the Whiteboard. By collaborating, participants can take control of the Access database, Access project, or data access page to review and edit its contents. During an online meeting, only one person at a time can control the Access data file, but multiple users can work in Chat or the Whiteboard simultaneously if collaboration is turned off. The host of the online meeting is the only person who needs to have the shared document and its application installed.

Return to top

More information

Use NetMeeting for an online meeting

Return to top


 Use NetMeeting for an online meeting

Use NetMeeting for an online meeting

Microsoft NetMeeting provides desktop data capabilities that allow you to communicate and collaborate with other people in real time over the Internet or corporate intranets.

Note The first time you start an online meeting, you'll be prompted to select a directory server to connect to. You can select any of the directory servers from the list in the Server name box under Directory. If you're a corporate user, you should ask your system administrator for the name of a directory server you can connect to.

Learn about online meetings.

  1. Start an online meeting

    Start an impromptu online meeting

  2. Participate in an online meeting

    Join an online meeting

    Remove participants from an online meeting

    Add participants to an online meeting already in progress

  3. Ways to communicate during an online meeting

    Control a Microsoft Access database, Microsoft Access project, or data access page in an online meeting

    Work on the Whiteboard in an online meeting

    Send typed messages in an online meeting

  4. End an online meeting

    End an online meeting


Start NetMeeting

  • On the Windows Start menu, point to Programs, and then click NetMeeting.


Join an online meeting

Do one of the following:

  • If you are hosting an online meeting and you receive a Microsoft Outlook online meeting reminder for a meeting, click Start this NetMeeting. Click Dismiss this reminder to decline an online meeting request.

  • If you're invited to participate in an online meeting and you receive a Microsoft Outlook online meeting reminder for a meeting, click Join this NetMeeting. Click Dismiss this reminder to decline an online meeting request.

  • When you receive an online meeting call, click Accept in the Join Meeting dialog box. Click Ignore to decline an online meeting. (You must have Microsoft NetMeeting running on your computer in order to receive an online meeting call.)


 Control an Access database, Access project, or data access page in an online meeting

Control an Access database, Access project, or data access page in an online meeting

The host controls the Microsoft Access database, Microsoft Access project, or data access page when the meeting starts. The host can allow collaboration by the participants and can turn off collaboration at any time. When collaboration is turned on, any participant can control the Access database, Access project, or data access page, but only one person at a time can have control. When collaboration is turned off, multiple users can work simultaneously in Chat or on the Whiteboard.

Control the Access database, Access project, or data access page as the host

  • To turn on collaboration, click Allow others to edit [image] on the Online Meeting toolbar.

  • To take back control of the Access database, Access project, or data access page when collaboration is turned on, click anywhere in the Access data file.

  • To turn off collaboration, click Allow others to edit again if you have control, or press ESC if you don't have control.

Control the Access database, Access project, or data access page as a participant

To take control of a shared Access database, Access project, or data access page the first time, double-click anywhere in the Access data file. Thereafter, you can gain control by clicking anywhere in the Access data file.

Only the host of the meeting can use the Online Meeting toolbar. If you want more control of Microsoft NetMeeting features during an online meeting you must use the NetMeeting program directly by clicking Microsoft NetMeeting on the taskbar.

Note The initials of the person in control appear next to the pointer.


View a list of participants in an online meeting

  • Click the participant list on the Online Meeting toolbar. The list is updated as participants join and leave an online meeting.


 Send typed messages in an online meeting

Send typed messages in an online meeting

Only the host of the online meeting can open the Chat window from within Office. If participants want to open the Chat window, they must use the Microsoft NetMeeting program directly by clicking Microsoft NetMeeting on the taskbar.

  1. On the Online Meeting toolbar, click Display Chat Window [image] .

  2. In the Message box, type your text, and then press Enter.

Tip It is faster to correspond in the Chat window if the host turns off collaboration. To turn off collaboration, click Allow others to edit [image] on the Online Meeting toolbar (if you have control), or press ESC (if you don't have control).


 Work on the Whiteboard in an online meeting

Work on the Whiteboard in an online meeting

Only the host of the online meeting can open the Whiteboard window from within Microsoft Office. If participants want to open the Whiteboard window, they must use the Microsoft NetMeeting program directly by clicking Microsoft NetMeeting on the taskbar.

  • On the Online Meeting toolbar, click Display Whiteboard [image] .

    The Whiteboard window appears.

Note In order for participants to draw or type simultaneously on the Whiteboard, the host must turn off collaboration; if you have control of the Microsoft Access database, Microsoft Access project, or data access page, click Allow others to edit [image] on the Online Meeting toolbar. If you don't have control, press ESC.


 Remove participants from an online meeting

Remove participants from an online meeting

Note The host of the online meeting is the only person who can remove participants from an online meeting.

  1. On the Online Meeting toolbar, select the name of the person you want to remove from the participant list.

  2. Click Remove Participants [image] .


 End an online meeting

End an online meeting

  • Click End Meeting [image] on the Online Meeting toolbar.

Note The host of the online meeting is the only person who can end an online meeting for the entire group. Participants in an online meeting can disconnect at any time by clicking Microsoft NetMeeting on the taskbar, and then clicking Hang Up on the NetMeeting toolbar. When the host ends an online meeting, others in the online meeting are automatically disconnected from each other.


 Which NetMeeting directory server should I connect to?

Which NetMeeting directory server should I connect to?

The first time you start an online meeting, you'll be prompted to select a directory server to connect to. You can select any of the directory servers from the list in the Server name box under Directory. If you're a corporate user, ask your system administrator for the name of a directory server you can connect to.


 About report snapshots and Snapshot Viewer

About report snapshots and Snapshot Viewer

You can view, print, mail, and electronically distribute reports created in Microsoft Access without needing a full or run-time Microsoft Access license. This topic provides reference information about:

What is a report snapshot?

What is Snapshot Viewer?

Benefits of report snapshots and Snapshot Viewer

Using report snapshots

Using report snapshots on the World Wide Web

Sending report snapshots in e-mail

Creating and distributing report snapshots

More Information

Return to top

What is a report snapshot?

A report snapshot is a file (.snp extension) that contains a high-fidelity copy of each page of a Microsoft Access report and that preserves the two-dimensional layout, graphics, and other embedded objects of the report.

Return to top

What is Snapshot Viewer?

Snapshot Viewer is a program that you can use to view, print, and mail a snapshot, such as a report snapshot. Snapshot Viewer version 9.0 consists of a stand-alone executable program, a Snapshot Viewer control (Snapview.ocx), a help file, and other related files. By default, Snapshot Viewer is automatically installed by Microsoft Access 2000 the first time you create a report snapshot. You can also install Snapshot Viewer from the Setup program, or from a World Wide Web software download page located at the Microsoft Access Developer's Web site.

You can use the Snapshot Viewer control to view a snapshot from Microsoft Internet Explorer version 3.0 or later or from any application that supports ActiveX controls, such as Access or Microsoft Visual Basic for Applications.

Return to top

Benefits of report snapshots and Snapshot Viewer

If you print and distribute reports to users inside or outside your organization, using report snapshots can save considerable time and money. Instead of photocopying and mailing printed Microsoft Access reports, you can electronically distribute and publish them using either e-mail or a Web browser, such as Microsoft Internet Explorer. Your users can easily and quickly view the reports online and print only the report pages they need. This is especially useful when your reports contain color and images, such as charts and pictures.

Return to top

Using report snapshots

You use Microsoft Access 2000 to create a report snapshot. However, you can view, print, store, publish, distribute, and archive a report snapshot without having an Access license by using a combination of Snapshot Viewer and other programs such as Windows Explorer, an e-mail program, or a Web browser, such as Internet Explorer.

Return to top

Using report snapshots on the World Wide Web

There are two ways you can publish a report snapshot on the World Wide Web:

  • Create a link to the report snapshot by using an HTML anchor tag on a Web page. For example:
    <A HREF="http://Website/NWTraders/catalog.snp">Catalog report</A>

    If you are using Internet Explorer version 3.0 or later as your browser, when you click on the link, Internet Explorer does an in-place activation of the report snapshot and Snapshot Viewer in the Internet Explorer window. Other browsers open the report snapshot in a separate Snapshot Viewer window. In either case, Snapshot Viewer must be installed on the same computer as the browser. Therefore, it's a good idea to provide an additional link on the Web page to the software download page for Snapshot Viewer. Users who do not have Snapshot Viewer installed on their computers can then download and install Snapshot Viewer to view the report.

  • Embed the Snapshot Viewer control on the Web page by using the HTML Object tag. For example:
    <OBJECT ID="SnapshotViewer" WIDTH=640 HEIGHT=480
 CLASSID="CLSID:F0E42D60-368C-11D0-AD81-00A0C90DC8D9">
    <PARAM NAME="_ExtentX" VALUE="16722">
    <PARAM NAME="_ExtentY" VALUE="11774">
    <PARAM NAME="_Version" VALUE="65536">
    <PARAM NAME="SnapshotPath"
 VALUE="http://Website/NWTraders/catalog.snp">
    <PARAM NAME="Zoom" VALUE="0">
    <PARAM NAME="AllowContextMenu" VALUE="-1">
    <PARAM NAME="ShowNavigationButtons" VALUE="-1">
</OBJECT>

    You can embed the Snapshot Viewer control by using the Microsoft ActiveX Control Pad application and set the control parameters by using the Control Pad Object Editor.

    You can use this method only with Internet Explorer 3.0 or later. In this case, if Snapshot Viewer is not installed on the same computer as the browser, Internet Explorer automatically downloads the Snapshot Viewer ActiveX control (but not the entire Snapshot Viewer program).

Return to top

Sending report snapshots in e-mail

You can send a report snapshot in e-mail by using Snapshot Viewer or Microsoft Access. You can also embed a report snapshot as an icon or as a file in an e-mail message by using an e-mail program that supports ActiveX controls, such as Microsoft Outlook or Microsoft Exchange. When you send report snapshots in e-mail, it's a good idea to always include a link to the software download page for Snapshot Viewer.

More information about sending a report snapshot in an e-mail message

Return to top

Creating and distributing report snapshots

A typical business application creates and distributes reports not only on request, but also on a schedule according to regular business cycles, such as weekly stock quotes, monthly sales reports, or quarterly financial statements.

From Microsoft Access 2000, you can programmatically create and distribute report snapshots in several ways. For example:

  • Create a macro that uses the OutputTo action to export one or more reports in snapshot format to a Web server that you use to publish your reports.

  • Create a macro that uses the SendObject action to mail a report to a mail recipient or distribution list.

  • Create a Visual Basic for Applications program.

Return to top

More information

Create a report snapshot

Return to top


Create a report snapshot

  1. In the Database window, click the name of the report you want to export, and then on the File menu, click Export.

  2. In the Save As Type box, click Snapshot Format (*.snp).

  3. Click the arrow to the right of the Save In box, and select the drive or folder to export to.

  4. In the File Name box, enter the file name.

  5. Click Save.

    By default, the report snapshot is displayed in Snapshot Viewer. If this is the first time you are creating a report snapshot and you chose not to install Snapshot Viewer during Setup, Microsoft Access automatically installs Snapshot Viewer for you.

Notes

  • The report snapshot is based on the recordset behind the report, including any current OrderBy or Filter property settings.

  • If the report contains a parameter query, Access first prompts you for the parameter values and then outputs the results.

  • You can also use the OutputTo action in a macro to export a report to snapshot format.


 Create a report snapshot by using the OutputTo action and publish it to the Web

Create a report snapshot by using the OutputTo action and publish it to the Web

  1. Create a macro with one or more OutputTo actions, one for each report you want to output in report snapshot format. For example:

    Create Snapshot macro

    Action | Argument | Value
    OutputTo | Object Type | Report
    Object Name | Catalog
    Output Format | Snapshot Format
    Output File | \\Website\Inetpub\wwwroot\Webreports\Catalog.snp *
    Auto Start | No

    * Output directly to the folder on the World Wide Web server.

  2. On the home page of the Web site, do one of the following:
    • Create a link to each report snapshot using an HTML anchor tag. For example:
      <A HREF="http://Website/WebReports/catalog.snp">Catalog report</A>
    • Embed the Snapshot Viewer control in an HTML Object tag by using the Microsoft ActiveX Control Pad application, and set the control parameters using the Control Pad Object Editor (you can only use this method with Microsoft Internet Explorer version 3.0 or later). For example:
      <OBJECT ID="SnapshotViewer" WIDTH=640 HEIGHT=480
 CLASSID="CLSID:F0E42D60-368C-11D0-AD81-00A0C90DC8D9">
    <PARAM NAME="_ExtentX" VALUE="16722">
    <PARAM NAME="_ExtentY" VALUE="11774">
    <PARAM NAME="_Version" VALUE="65536">
    <PARAM NAME="SnapshotPath"
 VALUE="http://Website/WebReports/catalog.snp">
    <PARAM NAME="Zoom" VALUE="0">
    <PARAM NAME="AllowContextMenu" VALUE="-1">
    <PARAM NAME="ShowNavigationButtons" VALUE="-1">
</OBJECT>

Notes

  • If the report is based on a parameter query, you will need to modify the macro to run it in a batch file. You can use the SendKeys action to pass the parameter information, or you can modify the report by removing the parameter query and using specific criteria.

  • You can also create a Visual Basic for Applications program to do the same task.


 Send a report snapshot in e-mail by using the SendObject action

Send a report snapshot in e-mail by using the SendObject action

  • Create a macro with a SendObject action. For example:

Send Snapshot macro

Action | Argument | Value
SendObject | Object Type | Report
 | Object Name | Summary of Sales by Quarter
 | Output Format | Snapshot Format
 | To | All Northwind Traders; Shareholders
 | Cc |
 | Bcc |
 | Subject | Quarterly Sales report
 | Message Text | This is our best quarter in years!
 | Edit Message | No

Notes

  • Depending on how your e-mail program was set up, you might not be able to send a report snapshot programmatically if the e-mail program requires you to log on and enter information. For example, Microsoft Outlook can be installed to prompt you for a user profile when you log on. Therefore, you might need to modify your e-mail program.

  • You can also create a Visual Basic for Applications program to do the same task.


 About protecting a Microsoft Access database

About protecting a Microsoft Access database

This topic provides reference information about:

Securing a Microsoft Access database file

Securing database objects with user-level security

Securing Visual Basic for Applications (VBA) Code

Securing data access pages

Securing an application

Security in a multiuser environment

Return to top

Securing a Microsoft Access database file

The simplest method of protection is to set a password for opening a Microsoft Access database (.mdb). Once a password is set, a dialog box that requests the password will be displayed whenever the database is opened. Only users who type the correct password will be allowed to open the database. This method is secure (Microsoft Access encrypts the password so that it can't be accessed by reading the database file directly), but it only applies to opening a database. Once a database is open, all its objects are available to the user (unless other types of security have already been defined, as described later in this topic). For a database that is shared among a small group of users or on a single computer, setting a password is often all that is required.

Caution Do not use a database password if you will be replicating a database. Replicated databases can't be synchronized if database passwords are defined.

To further protect the database, you can encrypt it. Encrypting a database compacts the database file and makes it indecipherable by a utility program or word processor. Decrypting a database reverses the encryption.

Return to top

Securing database objects with user-level security

The most flexible and extensive method of securing a database is called user-level security. This form of security is similar to methods used in most network systems. The two main reasons to use user-level security are to:

  • Prevent users from inadvertently breaking an application by changing tables, queries, forms, reports, and macros on which the application depends.

  • Protect sensitive data in the database.

Under user-level security, users are required to identify themselves by an id, and then type a password when they start Microsoft Access. Within the workgroup information file, they are identified as members of a group. Microsoft Access provides two default groups: administrators (named the Admins group) and users (named the Users group), but you can define additional groups.

Although setting up user-level security on most databases can be a daunting task, the User-Level Security Wizard makes it easy to quickly secure your Access database in a one-step process. Furthermore by implementing common security schemes, the User-Level Security Wizard minimizes and even eliminates the need to use the Security command from the Tools menu.

After running the User-Level Security Wizard, you can assign or remove permissions for user and group accounts in your workgroup for a database and its existing tables, queries, forms, reports, and macros. You can also set the default permissions that Microsoft Access assigns for any new tables, queries, forms, reports, and macros that are created in a database.

Permissions are granted to groups and users to regulate how they are allowed to work with each table, query, form, report, and macro in a database. For example, members of the Users group might be allowed to view, enter, or modify data in a Customers table but not to change the design of that table. While the Users group might be allowed to only view data in a table containing order data, they might be totally denied any access to a Payroll table. Members of the Admins group have full permissions on all of a database's tables, queries, forms, reports, and macros . You can set up more fine-grained control by creating your own group accounts, assigning appropriate permissions to those groups, and then adding users to those groups.

If you only need an administrators group and users group for your security purposes, you don't need to create additional groups; you can use the default Admins and Users groups. In this case, you only need to assign the appropriate permissions to the default Users group, and add any additional administrators to the default Admins group. Any new users you add are automatically added to the Users group. Typical permissions for the Users group might include Read Data and Update Data for tables and queries, and Open/Run for forms and reports.

If you need more fine-grained control of different groups of users, you can create your own groups, assign different sets of permissions to those groups, and then add users to the appropriate groups. To simplify the management of permissions, it is recommended that you only assign permissions to groups (not users), and then add users to the appropriate groups.

Note For more information on the Microsoft Access security model, see the Microsoft Office 2000/Visual Basic Programmer's Guide.

Return to top

Securing Visual Basic for Applications (VBA) Code

You can protect Microsoft Visual Basic for Applications (VBA) code in modules and modules behind forms and reports with a password, which you enter once per session. The password prevents unauthorized users from editing, cutting, pasting, copying, exporting, and deleting VBA code.

To protect the intellectual property of your code, you can remove editable VBA code from your database, and prevent modifications to the design of forms, reports, and modules by saving it as an MDE file.

Learn about protecting VBA code.

Return to top

Securing data access pages

To protect a data access page and the data it accesses, do the following:

  • Protect the Access database containing the shortcut to the data access page and its corresponding HTML file by using the file system security of the computer where you have stored these files.

  • Protect the database connected to the data access page by securing the database against unauthorized users, controlling the level of access once a user logs in, and not saving the database password with the data access page.

  • Prevent unauthorized access from a malicious Visual Basic script by using Microsoft Internet Explorer security options and using three-tier data access.

Learn about how to protect a data access page.

Return to top

Securing an application

Finally, you can prevent curious or malicious end users from accidentally or intentionally damaging your application by hiding database objects from the database window and setting several startup options to control the applications appearance and behavior and protect menus and command bars.

Return to top

Security in a multiuser environment

In many situations, you will want to prevent users from replicating a database. Replicating a database allows a user to make a copy of a shared database and also adds fields and makes other changes to the current database. You will probably want to prevent users from setting a database password, too. If a user sets a database password for a shared database, no other user will be able open the database without providing that password. You might also want to keep users from changing startup properties that specify features such as custom menus, custom toolbars, or the startup form.

If a shared database doesn't have user-level security defined, you can't prevent a user from making any of these changes. Running the User-Level Security Wizard on a database defines user-level security, which allows you to control access to certain features and determines how database objects can be used. When user-level security is defined, a user or group must have Administer permission for the database to replicate a database, set a database password, or change its startup properties. After running the User-Level Security Wizard, only members of the Admins group of the current workgroup have Administer permission.

If user-level security is already defined and a user or group currently has Administer permission for a database, removing that permission will prevent the user or group from making any of these changes. If you need to allow a user or group to perform any of these tasks, you can assign the Administer permission to that user or group. You can't control access to these three tasks independently.

Return to top


 About protecting a data access page

About protecting a data access page

This topic provides reference information about:

Protecting a data access page shortcut and its corresponding HTML file

Protecting and controlling database access from a data access page

Preventing unauthorized access from a malicious script

Protecting a data access page shortcut and its corresponding HTML file

A data access page is the combination of a shortcut stored in the Microsoft Access database (.mdb) or Microsoft Access project (.adp) file and a corresponding Hypertext Markup Language (HTML) file located in your computer's file system. To protect a page's shortcut and its corresponding HTML file from being renamed, deleted, or changed, use the file system's security of the computer where you have stored these files. For example, on your computer, you can make the Access database or Access project file that contains the page's shortcut read-only. Or on the Web server where the page's corresponding HTML file is located (after you have published the page), make the file and the folder where the HTML file is located read-only. For more information about file and folder security, see Microsoft Windows Help.

Return to top

Protecting and controlling database access from a data access page

Consider the following when you want to ensure secure access to the Access database or Microsoft SQL Server database that the page is connected to:

Protect the database You can connect a page to either an Access database or SQL Server database. You should provide adequate security to either database as a foundation for protecting access to the database through a page. As with any application, you need to prevent unauthorized users from accessing the database, and control the level of access once a user has logged in.

  • For an Access database, if it is protected with user-level security and you want to enable user-level security through a page, you need to make sure that the connection information for a page specifies the correct workgroup information file and that this file is in a public network share accessible to all users. Modify the connection to the page in the Data Link Properties dialog box by clicking the All tab, double-clicking Jet OLEDB:System database, and then specifying the UNC path to the correct workgroup information file in the Property Value box. Learn about protecting an Access database.

    If you have set a database password on an Access database that is connected to a page, you will be prompted for the password the first time you view the page.

  • For an SQL Server database, if you want to use Windows NT integrated security to connect from a page, modify the connection to the page in the Data Link Properties dialog box by clicking Connection, and then clicking Use Windows NT Integrated security. Learn about protecting an SQL Server database.

Don't save the user name and password with the page If the username and password to the database are saved with the page, any user can log in to the database. If you want the page to prompt the user to log in to the database, modify the connection to the page in the Data Link Properties dialog box by clicking the Connection tab, and then clearing the Allow saving of password check box.

Return records based on a user name You might want to create a page that doesn't require entering a username and password through a page but can automatically detect who the user is, and display records based on that user. For example, you could create a page that allows users to change their personnel file. The general steps for doing this are:

  • Create a page in an Access project connected to an SQL Server database protected by Microsoft Windows NT integrated security.

  • Add a column to the employee table that has each employee's Windows NT log in user name.

  • Create a view that uses the suser_sname() function to detect the current user logged in, and make that view the page's record source.

For a detailed example of this, see the Microsoft Office 2000/Visual Basic Programmer's Guide.

Return to top

Preventing unauthorized access from a malicious script

A page uses the Microsoft Office Data Source Control (MSODSC) to connect to its data source. When a user opens a page, the MSODSC on the page may use the user name of the user to log on to the database. A malicious page author could exploit this by using Microsoft Visual Basic, Scripting Edition or JScript running against the MSODSC to attempt access to databases on servers accessible to the user, but not the page author. The mode of data access used by the MSODSC determines whether a page is considered inherently safe, or if cross-domain data access is possible from the page. You can configure the MSODSC to use two modes of data access: two-tier or three-tier data access.

Two-tier data access is a direct connection to a data source in a traditional client/server fashion — the client (first tier) makes a direct connection to the database server (second tier). To perform two-tier data access, the MSODSC makes a direct connection to its data source through an OLE DB provider that is registered on the user’s computer. For an Access database, two-tier data access uses the local computer’s Microsoft Jet 4.0 OLE DB provider to connect to an .mdb file located on a network share. For an SQL Server database, two-tier data access uses the local computer’s Microsoft OLE DB provider for SQL Server to connect to a database server available on your local network.

Three-tier data access refers to using a third, remote component between the client and database components. Three-tier data access is typically used to access data across the Internet. For three-tier data access that uses the MSODSC, this third component is the ActiveX Data Objects (ADO) Remote Data Service (RDS) component (also called Data Factory) running on Microsoft Internet Information Server (IIS).

Any page that uses two-tier data access is considered by Microsoft Internet Explorer to be making a cross-domain access attempt. Depending on the security settings in Internet Explorer, when a user opens a page by using two-tier data access, one of three things occurs: the page is automatically disabled, the user is asked whether to allow data access, or the page is automatically enabled.

Internet Explorer security settings also define different security zones. If a page is on a Web server in a trusted zone, the cross-domain attempt can be enabled automatically. In a controlled environment, such as a corporate intranet, your pages will perform better if you use two-tier data access, and make sure that they are published from a server located in a trusted security zone. This is the simplest way to provide security against unauthorized access from malicious scripts. For more information about security settings, see Internet Explorer Help.

A page that uses three-tier data access to connect to a database is considered to be inherently safe regardless of what Internet Explorer security zone it is published from, and will not warn the user about cross-domain data access attempts when it is opened if authentication settings have been left to their default configuration.

For information about implementing two-tier or three-tier access, see the Microsoft Office 2000/Visual Basic Programmer's Guide.

Return to top


About providing user-level security on a specific Microsoft Access database

When users join a Microsoft Access workgroup by using the Workgroup Administrator, the location of the workgroup information file is stored in the Windows Registry, which means that in many cases all Access databases on the user's machine will use user-level security based on that workgroup information file.

However, you may want to use user-level security on a specific database, and not use it on others. To do this, don't have users join a Microsoft Access workgroup by using the Workgroup Administrator. Instead, take the following steps:

  1. Create a workgroup information file and store it in a location that is accessible to all users of that specific database.

  2. Create a shortcut that starts the specific database by using the /wrkgrp command-line option to specify the location of the workgroup information file. For example:

    "C:\Program Files\Microsoft Office\Office\MSACCESS.EXE \\SalesSystem\DBFiles\SalesS.mdb /wrkgrp \\SalesSystem\DBFiles\SalesS.mdw"

    For more information on creating shortcuts, see Windows Help.


 About protecting Visual Basic for Applications code

About protecting Visual Basic for Applications code

This topic provides reference information about:

Protecting Visual Basic for Applications (VBA) code

Modules, forms, reports, and user-level security

Protecting Visual Basic for Applications (VBA) code

In a Microsoft Access project and Microsoft Access database, you can protect all modules, and modules behind forms and reports by protecting VBA code with a password that you and other users must enter to view or edit VBA code in the Visual Basic Editor. Once you set a password, you enter this password once per session. The password is required not only for viewing and editing, but also for cutting, copying, pasting, exporting, and deleting any module. Note, however, that protecting your VBA code in this manner doesn't prevent you or other users from running existing VBA code.

Return to top

Modules, forms, reports, and user-level security

In a Microsoft Access 2000 database, modules and modules behind forms and reports are no longer secured by user-level security, as they were in previous versions. However, forms and reports are still secured by user-level security. This means that modules, and forms and reports are protected by two different security mechanisms.

For example, assuming you have the appropriate permissions, you can add a control to a form, but if the VBA project is locked for viewing and protected with a password, and you don't know the password, you can't view or edit the module behind the form. Conversely, you can be restricted from designing a form or report through user-level security by not having Modify Design permission on the object, but if you know the VBA project password, you can access the module behind the form or report.

There is an exception to this. Even if you have Modify Design permission on a form or report, you cannot delete the form or report, or set the HasModule property to No, because this action deletes the module behind the form or report.

Return to top


 About MDE files

About MDE files

If your database contains Microsoft Visual Basic code, saving your Microsoft Access database as an MDE compiles all modules, removes all editable source code, and compacts the destination database. Your Visual Basic code will continue to run, but it cannot be viewed or edited, and the size of your Access database will be reduced due to the removal of the code. Additionally, memory usage is optimized, which will improve performance.

Saving your Access database as an MDE file prevents the following actions:

  • Viewing, modifying, or creating forms, reports, or modules in Design view.

  • Adding, deleting, or changing references to object libraries or databases.

  • Changing code using the properties or methods of the Microsoft Access or VBA Object models — an MDE file contains no source code.

  • Importing or exporting forms, reports, or modules. However, tables, queries, data access pages, and macros can be imported from or exported to non-MDE databases. Any tables, queries, data access pages, or macros in an MDE file can be imported into another Access database, but no forms, reports, or modules can be imported into another Access database.

Caution Be sure to save a copy of your original Access database. If you need to modify the design of forms, reports, or modules in an Access database saved as an MDE file, you must open the original Access database, modify it, and then save it as an MDE file again. Saving an Access database containing tables as an MDE file creates complications reconciling different versions of the data if you need to modify the design of the forms, reports, or modules later. For this reason, saving a Access database as an MDE file is most appropriate for the front-end database of a front-end/back-end application.

Caution You won't be able to open, convert, or run code in a Microsoft Access 2000 MDE file in future versions of Microsoft Access. The only way to convert a Microsoft Access 2000 MDE file to a future version will be to open the original Access database the MDE file was created from, convert it, and then save the converted Access database as an MDE file.

Important Some restrictions may prevent you from saving your Access database as an MDE file:

  • If your Access database is secured with user-level security, you must meet certain criteria. Learn about using other forms of security with an Access database that is saved as an MDE file.

  • You must have password access to the Visual Basic code. Learn about protecting Visual Basic code.

  • If your database is replicated, you must first remove replication system tables and properties.

  • If your Access database references another Access database, or add-in, you must save all Access databases or add-ins in the chain of references as MDE files.


 About references and MDE files

About references and MDE files

If you try to save as an MDE file a Microsoft Access database (.mdb) or an add-in (.mda) that references another Access database or add-in, Microsoft Access displays an error message, and doesn't let you complete the operation. To save an Access database that references another Access database as an MDE file, you must save all databases in the chain of references as MDE files, starting from the first database referenced. After saving the first database as an MDE file, you must then update the reference in the next database to point to the new MDE file before saving it as an MDE file, and so on.

For example, if Database1.mdb references Database2.mdb, which references Database3.mda, you would proceed as follows:

  1. Save Database3.mda as Database3.mde.

  2. Open Database 2.mdb and change its reference to point to the new Database3.mde.

  3. Save Database2.mdb as Database2.mde.

  4. Open Database1.mdb and change its reference to point to the new Database2.mde.

  5. Save Database1.mdb as Database1.mde.


 About saving a replicated Microsoft Access database as an MDE file

About saving a replicated Microsoft Access database as an MDE file

A replicated database (either a replica or Design Master) cannot be saved as an MDE file. To save a replicated database as an MDE file, you must first remove the replication system tables and properties. Learn about removing replication features.

Once a database is saved as an MDE file, it can be replicated; however, replication is only recommended in situations where no further changes need to be made to the original database. There is no way to make changes to the design of forms, reports, or code in the Design Master MDE file, and design changes made in the original database can't be synchronized with pre-existing MDE replicas. For this reason, if you need to make a design change to a replica set of MDE files, you must make that change in the original database, re-save it as an MDE file, and then create and distribute an entirely new replica set from the new MDE file.


 What is a Microsoft Access workgroup?

What is a Microsoft Access workgroup?

A Microsoft Access workgroup is a group of users in a multiuser environment who share data. If user-level security is defined, the members of a workgroup are recorded in user and group accounts that are stored in a Microsoft Access workgroup information file. Users' passwords are also stored in the workgroup information file. These security accounts can then be assigned permissions for databases and their tables, queries, forms, reports, and macros. The permissions themselves are stored in the secure database.

In Microsoft Access 2000, user preferences are stored in the Windows Registry in the \Hkey_Current_User\Software\Microsoft\Office\9.0\Access\Settings key. In versions prior to Microsoft Access 97, user preferences are defined in the Options dialog box are recorded in the workgroup information file.

Your default workgroup is defined by the workgroup information file that the Setup program automatically creates in the language folder. Unless you specify another workgroup information file using the Workgroup Administrator utility, Microsoft Access uses the default workgroup information file each time you start Microsoft Access. You can also use the Workgroup Administrator to create a new Microsoft Access workgroup information file.

Before you create security accounts, you should choose a Microsoft Access workgroup information file where those accounts will be stored. You can use the default workgroup information file, specify an existing file, or create a new file. If you need to make sure that your workgroup and its permissions can't be duplicated, don't use the default workgroup information file; you must make sure the workgroup information file you choose has been created with a unique workgroup ID (WID). If such a workgroup information file doesn't exist, you should create one using the Workgroup Administrator.


 Ways to make a secure application and workgroup available to users

Ways to make a secure application and workgroup available to users

A secure application depends on users having access to both an application database where permissions are stored, and a workgroup where user and group accounts and passwords are stored. Depending on how the application is to be used, you can make the application and workgroup available to users in a variety of ways.

Copy the application files and the workgroup information file that defines the workgroup to a network server location

Using the Workgroup Administrator, users can join the workgroup by specifying the network server path to the workgroup information file, and then run the application directly from the server location. You might want to prevent users from opening the application with exclusive access by removing Open Exclusive permissions for the database from the Users group.

Give each user a copy of the application files and the workgroup information file that defines the workgroup

Using the Workgroup Administrator, users can join the workgroup by specifying the path to the workgroup information file on their computer, and then running their copies of the application on their computers. However, if you have to update the application, its data, or the workgroup information file, you'll have to give each user copies of all updated files.

As an alternative, you might want to split the application into a data database placed on a network server and an application database containing all other database objects placed on each user's computer. Typically in this configuration, you want to keep the workgroup information file on the server as well. Then if you have to update the application, you only have to give users updated versions of the application database file. For information on how to do this, click [image] .

Give users in different Microsoft Access workgroups access to the application by creating the same group in each workgroup

You can create a group account in each workgroup with the identical name and personal ID (PID), and then add users in each workgroup to that group. For example, a user working on a network on a Microsoft Access workgroup in Honolulu can use an application created for a Microsoft Access workgroup in Melbourne if that user is a member of a group account that was created with an identical name and PID on both workgroups.

To run the application, each user must have a copy of Microsoft Access. To create a Microsoft Access application that doesn't require a copy of Microsoft Access, you must use Microsoft Office 2000 Developer (MOD).


 How to organize security accounts

How to organize security accounts

A Microsoft Access workgroup information file contains the following predefined accounts.

Account | Function
Admin | The default user account. This account is exactly the same for every copy of Microsoft Access and other applications that can use the Microsoft Jet database engine, such as Microsoft Visual Basic for Applications and Microsoft Excel.
Admins | The administrator's group account. This account is unique to each workgroup information file. By default, the Admin user is in the Admins group. There must be at least one user in the Admins group at all times.
Users | The group account comprising all user accounts. Microsoft Access automatically adds user accounts to the Users group when a member of the Admins group creates them. This account is the same for any workgroup information file, but it contains only user accounts created by members of the Admins group of that workgroup. By default, this account has full permissions on all newly-created objects. The only way to remove a user account from the Users group is for a member of the Admins group to delete that user.

In effect, security in Microsoft Access is always "on." Until you activate the logon procedure for a workgroup, Microsoft Access invisibly logs on all users at startup by using the default Admin user account with a blank password. Behind the scenes, Microsoft Access uses the Admin account as the administrator account for the workgroup, as well as the owner of any databases and tables, queries, forms, reports, and macros created.

Administrators and owners are important because they have permissions that can't be taken away:

  • Administrators (members of the Admins group) can always get full permissions for objects created in the workgroup.

  • An account that owns a table, query, form, report, or macro can always get full permissions for that object.

  • An account that owns a database can always open the database.

Because the Admin user account is exactly the same for every copy of Microsoft Access, the first steps in securing your database are to define administrator and owner user accounts (or use a single user account as both the administrator and owner account), and then to remove the Admin user account from the Admins group. Otherwise, anyone with a copy of Microsoft Access can log on to your workgroup by using the Admin account and have full permissions for the workgroup's tables, queries, forms, reports, and macros.

For example, to secure a database named Orders, you could create your own OrdersAdmin and OrdersOwner user accounts, and then add passwords to these accounts.

You can assign as many user accounts as you want to the Admins group, but only one user account can own the database itself — the user account that is active when the database is created, or when ownership is transferred by creating a new database and importing all of a database's objects into it. However, group accounts can own tables, queries, forms, reports, and macros within a database.

Important

  • The accounts that you create for users of the database must be stored in the workgroup information file that those users will join when they use the database. If you're using a different file to create the database, change the file before creating the accounts.

  • Make sure to create a unique password for your administrator and user accounts. A user who can log on by using the administrator account can always get full permissions for any tables, queries, forms, reports, and macros created in the workgroup. A user who can log on using an owner account can always get full permissions for those objects owned by that user.

Organizing users in groups makes it easier to manage a secure database. With this strategy, rather than assign permissions to each user for each table, query, form, report, and macro in your database, you assign permissions to a few groups, and then add users to the appropriate group. When users log on to Microsoft Access, they inherit the permissions from any groups they belong to. Only user accounts can log on to Microsoft Access; you can't log on by using a group account.

For example, you could secure an Orders database by creating a Managers group for managers, a Sales Reps group for sales representatives, and a Staff group for staff employees. You can assign the least restrictive set of permissions to the Managers group, a more restrictive set of permissions to the Sales Reps group, and the most restrictive set of permissions to the Staff group. When you create a user account for a new employee, you add that account to the appropriate group. The employee then has the permissions associated with that group.

After you create user and group accounts, you can view the relationships between them by clicking User And Group Accounts on the Security submenu (Tools menu), and then clicking the Print Users And Groups button. Microsoft Access prints a report of the accounts in the workgroup, showing the groups to which each user belongs and the users that belong to each group.


 How permissions work and who can assign them

How permissions work and who can assign them

There are two types of permissions: explicit and implicit. Explicit permissions are those permissions that are granted directly to a user account; no other users are affected. Implicit permissions are those permissions that are granted to a group account. Adding a user to that group grants the group's permissions to that user; removing a user from the group takes away the group's permissions from that user.

When a user attempts to perform an operation on a secured database object, that user's set of permissions are based on the intersection of that user's explicit and implicit permissions. A user's security level is always the least restrictive of that user's explicit permissions and the permissions of any and all groups to which that user belongs. For this reason, the least complicated way to administer a workgroup is to create new groups and assign permissions to the groups, rather than to individual users. Then you can change individual users' permissions by adding or removing them from groups. Also, if you need to grant new permissions, you can grant them to all members of a group in a single operation.

Permissions can be changed for a database object by:

  • Members of the Admins group of the workgroup information file in use when the database was created.

  • The owner of the object.

  • Any user who has Administer permission for the object.

Even though users might not be able to currently perform an action, they might be able to grant themselves permissions to perform the action. This is true if a user is a member of the Admins group, or if a user is the owner of an object.

The user who creates a table, query, form, report, or macro is the owner of that object. The same group of users that can change permissions can change the ownership of these objects by using the User And Group Permissions command on the Security submenu (Tools menu), or they can re-create these objects. To re-create these objects, you do not have to start from scratch. You can make a copy of the object, or import it or export it to another database. If you want to secure an entire database, this is the easiest way to transfer the ownership of all of these objects, including the database . The best way to secure an entire database is by using the User-Level Security Wizard, which creates a new database and imports all objects into it.

Note Copying, importing, or exporting doesn't change the ownership of queries that has its RunPermissions property set to Owner's. You can change ownership of a query only if its RunPermissions property is set to User's.

For information on types of permissions, click [image] .


 Types of permissions

Types of permissions

The following table summarizes the permissions that you can assign.

Permission | Permits a user to | Applies to
Open/Run | Open a database, form, or report, or run a macro. | Databases, forms, reports, and macros
Open Exclusive | Open a database with exclusive access. | Databases
Read Design | View objects in Design view | Tables, queries, forms, reports, and macros
Modify Design | View and change the design of objects, or delete them. | Tables, queries, forms, reports, and macros
Administer | For databases, set database password, replicate a database, and change startup properties. For tables, queries, forms, reports, and macros, have full access to these objects and data, including ability to assign permissions. | Databases, tables, queries, forms, reports, and macros
Read Data | View data. | Tables and queries
Update Data | View and modify but not insert or delete data. | Tables and queries
Insert Data | View and insert but not modify or delete data. | Tables and queries
Delete Data | View and delete but not modify or insert data. | Tables and queries

Note

  • Some permissions automatically imply the selection of others. For example, the Update Data permission for a table automatically implies the Read Data and Read Design permissions because you need these to modify the data in a table. Modify Design and Read Data imply Read Design. For macros, Read Design implies Open/Run.

  • To design forms, reports, macros, modules in a multiuser environment, you must open a Microsoft Access database exclusively, which means you must have Open Exclusive permission on the Access database. Learn about saving design changes to a shared Access database.

  • In general, for users to access a linked table, grant Read Data and Read Design permissions on the table in the back-end database, and Modify Design permission on the table link defined in the front-end database so that users can conveniently re-link the table. If you want to restrict all access to the back-end table but still allow users to view the data and re-link the tables, remove all permissions on the back-end table and use queries in the front-end database with their RunPermissions property set to Owner's.


 About creating and changing passwords

About creating and changing passwords

This topic provides reference information about:

Database passwords

Security account passwords

Visual Basic for Applications (VBA) passwords

Database passwords

The first kind of password is called a "database password." If you set a database password, all users must enter that password before they are allowed to open the database. Adding a database password is an easy way to prevent unwanted users from opening your database; however, once a database is open, no other security measures are provided unless user-level security has been defined as well. If you have user-level security defined for your database, you can prevent users from setting a database password.

Return to top

Security account passwords

The second kind of password is called a "security account password" and is only used when user-level security has been defined for a workgroup. A security account password is created to make sure that no other user can log on using that user name.

By default, Microsoft Access assigns a blank password to the default Admin user account and to any new user accounts that you create in your workgroup. As part of securing a database, it's important to add a password to:

  • The Admin user account (to activate the Logon dialog box).

  • The user account that owns the database and its tables, queries, forms, reports, and macros.

  • Any user accounts that you add to the Admins group.

In addition, you might want to add passwords to the accounts you create for users, or instruct users to add their own passwords.

Users can create or change their own user account passwords; however, only an administrator account can clear a password if a user forgets the password.

Return to top

Visual Basic for Applications (VBA) passwords

The third kind of password is called a Visual Basic for Applications (VBA) password. You use this password once per session to protect VBA code in modules and modules behind forms and reports. This password prevents unauthorized users from editing, cutting, pasting, copying, exporting, and deleting VBA code.

Return to top


 About using a database password and user-level security with a Microsoft Access database that is saved as an MDE file

About using a database password and user-level security with a Microsoft Access database that is saved as an MDE file

Creating an MDE file secures the forms, reports, and Microsoft Visual Basic code in your Microsoft Access database, without requiring users to log on or requiring you to create and manage the user accounts and permissions that are needed for user-level security. However, if you define a database password or user-level security before saving an Access database as an MDE file, those features will still apply to an MDE file created from that database. If your Access database has a database password or user-level security defined and you want to remove these features, you must do so before saving it as an MDE file. For information on removing a database password, click [image] . For information on removing user-level security, click [image] .

To save an Access database that was secured with user-level security as an MDE file, you must meet the following requirements before you can proceed:

  • You must join the workgroup information file that defines the user accounts used to access the database, or that were in use when the database was created.

  • Your user account must have Open/Run and Open Exclusive permissions for the database.

  • Your user account must have Modify Design or Administer permissions for any tables in the database, or you must be the owner of any tables in the database.

  • Your user account must have Read Design permissions for all objects in the database.


 About converting or enabling a secured database from a previous version of Microsoft Access

About converting or enabling a secured database from a previous version of Microsoft Access

Using a secured database from a previous version of Microsoft Access requires some additional steps and considerations.

Important To convert or enable a secured database, you must meet the following requirements or conversion will fail:

  • When you install Microsoft Access 2000, it creates a new workgroup information file and makes it the current file. Therefore, before you convert a secured database, you must join the workgroup information file that defines the user accounts that are used to access the database you wish to convert, or that were in use when the database was secured. For information on joining a workgroup information file, click [image] .

  • The user account you use to log on during conversion must have the following permissions:

    Open/Run and Open Exclusive permissions for the database itself.

    Modify Design or Administer permissions for all tables in the database, or you must be the owner of all tables in the database.

    Read Design permissions for all objects in the database.

If all users of a previous-version secured database will be upgrading to Microsoft Access 2000, you should convert the database and workgroup information file used with it. How you proceed depends on which version of Microsoft Access you are upgrading from.

If only some users of a secured database will be upgrading to Microsoft Access 2000, you can share the database and workgroup information file across all versions of Microsoft Access currently in use. There are several ways to share the secured database and workgroup information file.

Important Only convert a previous-version secured database if all users of the database are upgrading to Microsoft Access 2000. If only some users are upgrading, you can share the database in its current format.

Important Because you cannot protect Microsoft Visual Basic code in modules and code behind forms and reports with user-level security in Microsoft Access 2000, code converted from a secure database of a previous version is no longer secure. Learn about protecting Visual Basic code.


 Protect a database by adding a database password

Protect a database by adding a database password

  1. Close the database. If the database is shared on a network, make sure all other users have closed the database.

  2. Make a backup copy of the database, and store it in a secure place.

  3. On the File menu, click Open.

  4. Click the arrow to the right of the Open button, and then click Open Exclusive.

  5. On the Tools menu, point to Security, and then click Set Database Password.

  6. In the Password box, type your password. Passwords are case-sensitive.

  7. In the Verify box, confirm your password by typing the password again, and then click OK.

    The password is now set. The next time you or any other user opens the database, a dialog box will be displayed that requests a password.

Caution

  • If you lose or forget your password, it can't be recovered, and you won't be able to open your database.

  • Do not use a database password if you will be replicating a database. Replicated databases can't be synchronized if database passwords are defined.

Notes

  • A database password is stored with the database and not with the workgroup information file.

  • You can't set a database password if user-level security has been defined for your database and you don't have Administer permission for the database. Also, a database password is defined in addition to user-level security. If user-level security has been defined, any restrictions based on user-level security permissions remain in effect.

  • If a table from a password-protected database is linked, the password is cached (saved) in the database it is linked to when the link is established. This may have unforeseen consequences. For more information, click [image] .


 Remove a database password

Remove a database password

  1. On the File menu, click Open.

  2. Click the arrow to the right of the Open button, click Open Exclusive, and then open the database.

  3. In the Password Required dialog box, type the database password, and then click OK. Passwords are case-sensitive.

  4. On the Tools menu, point to Security, and then click Unset Database Password. This command is only available if a database password was set previously.

  5. In the Unset Database Password dialog box, type your current password.

  6. Click OK.


 About linking tables from a password-protected database

About linking tables from a password-protected database

To link a table from a Microsoft Access database that is password-protected, you must supply the correct password. If you supply the correct password, Microsoft Access stores the database password with the information that defines the link to the table. After the link has been defined, any user who can open the database that the table is linked to can open the linked table. When a user opens the linked table, Microsoft Access uses the stored password to open the database where the table is stored. If the password is changed for the database where the table is stored, the next time the linked table is opened, the new password must be supplied before Microsoft Access will open it.

Microsoft Access stores the database password in an unencrypted form. If this will compromise the security of the password-protected database, you should not use a database password to protect the database. Instead, you should define user-level security to control access to sensitive data in that database. For more information on user-level security, click [image] .


 Encrypt or decrypt a database

Encrypt or decrypt a database

Encrypting a database compacts the database file, and makes it indecipherable by a utility program or word processor. Decrypting a database reverses the encryption.

  1. Start Microsoft Access without opening a database.

    Important You can't encrypt or decrypt a database when it is open. In a multiuser environment, the encrypt or decrypt operation fails if another user has the database open.

  2. On the Tools menu, point to Security, and then click Encrypt/Decrypt Database.

  3. Specify the database you want to encrypt or decrypt, and then click OK.

  4. Specify a name, drive, and folder for the encrypted or decrypted database; and then click OK.

    If you use the same name, drive, and folder as the original database, and the database is encrypted or decrypted successfully, Microsoft Access automatically replaces the original file with the encrypted or decrypted version. If an error occurs, Microsoft Access doesn't delete the original file.

Notes

  • If user-level security has been defined, to encrypt or decrypt a database, you must either be the owner of the database or a member of the Admins group and have Open Exclusive permission on the database. Otherwise, the encrypt or decrypt operation fails.

  • If an object in a version 1.x database includes the backquote character (`) in its object name, you won't be able to encrypt the database. Use Microsoft Access version 1.x to rename it, and then change the references to that object in your queries, forms, reports, macros, and Access Basic code.

  • Encrypting a database doesn't restrict access to objects. For more information on other security methods, click [image] .

  • The encrypt or decrypt operation fails if you don't have enough storage space on your disk for both the original and encrypted or decrypted versions of the database.


 Hide objects in the Database window

Hide objects in the Database window

  1. In the Database window, click the object you want to hide.

  2. Click Properties [image] on the toolbar.

  3. Click Hidden, and then click OK.

Notes

  • To show all hidden objects, 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 displayed with a dimmed outline. You can then repeat the steps, but in step 3 clear Hidden, to unhide the objects.

  • In a Microsoft Access project, you cannot hide tables, views, database diagrams, or stored procedures.


 Make an MDE file

Make an MDE file

  1. Close the Microsoft Access database. If you are working in a multiuser environment, make sure that all other users have closed the Access database.

  2. On the Tools menu, click Database Utilities, and then click Make MDE File.

  3. In the Database To Save As MDE dialog box, specify the Access database you want to save as an MDE file, and click Make MDE.

  4. In the Save MDE As dialog box, specify a name, drive, and folder for the Access database.

Caution Be sure to save a copy of your original Access database. You can't modify the design of forms, reports, or modules in an Access database saved as an MDE file. If you need to change the design of these objects, you must do so in the original Access database and then re-save the Access database as an MDE file. You also won't be able to run or convert an Access database saved as an MDE file in future versions of Microsoft Access. You will only be able to open or convert the original Access database.


 Protect Visual Basic for Applications code with a password

Protect Visual Basic for Applications code with a password

To prevent someone from viewing or making undesired changes to your Visual Basic for Applications (VBA) code, you can protect VBA code by requiring a password.

  1. Open the Microsoft Access project or Microsoft Access database with the VBA code you want to protect.

  2. In the Database window, on the Tools menu, click Macro, and then click Visual Basic Editor.

    Tip You can also press ALT+F11.

  3. In the Microsoft Visual Basic Editor, on the Tools menu, click <Access database or Access project name> Project Properties.

  4. Click Protection.

  5. Select the Lock project for viewing check box.

  6. Enter a password in the Password box, and confirm the password by entering it again in the Confirm password box.

The next time you open the Access database or Access project, the VBA code will be protected by requiring you or any user to enter the password defined in step 6 to view and edit the VBA code.

Notes

  • To remove the password, clear all information in the Protection tab of the <Access database or Access project name> Project Properties dialog box.

  • If you set a password but don't select Lock project for viewing, the code can be viewed and edited by anyone, but the Project Properties dialog box is protected.

  • Don't forget the password. If you forget the password, you will not be able to view or edit the VBA code.


 Secure a database using the User-Level Security Wizard

Secure a database using the User-Level Security Wizard

By using the User-Level Security Wizard, you can apply user-level security with a commonly-used security scheme and encrypt your Microsoft Access database.

  1. Open the database that you want to secure.

  2. On the Tools menu, click Security, and then click User-Level Security Wizard.

  3. Follow the directions in the wizard dialog boxes.

Notes

  • The User-Level Security Wizard creates a back-up copy of the current Access database with the same name and a .bak extension, and then secures the selected objects in the current database.

  • If your current Access database protects Visual Basic for Applications (VBA) code with a password, the wizard prompts you for the password, which you must enter or the wizard doesn't complete successfully.

  • Any passwords that you create though the wizard are printed in the User-Level Security Wizard report when you finish using the wizard. You should keep this report in a secure location. You can also use this report to re-create your workgroup file.


 Secure a database without requiring users to log on

Secure a database without requiring users to log on

  1. Secure your database by using the User-Level Security Wizard.

    How?

  2. For each table, query, form, report, and macro you want to be available to users, grant the appropriate permissions to the Admin user account.

    How?

  3. Turn off the Logon dialog box.

    How?

When users start Microsoft Access and open a database without logging on, Microsoft Access automatically logs them on under the Admin user account. As a result, they will have only the permissions granted in step 2. This works for any workgroup, because the Admin account is the same in every workgroup information file. Only the administrator user account and any other members of the Admins group of the workgroup information file that was current when you ran the wizard in step 1 will have full permissions on your database's tables, queries, forms, reports, and macros.

To perform administrative functions, you can either reactivate the logon procedure and log on as a member of the Admins group, or you can use the /pwd and /user command-line options to specify your password and user name when starting Microsoft Access.


 Remove user-level security

Remove user-level security

This procedure requires a two-stage process. First, you log on as a workgroup administrator and give the Users group permissions on all tables, queries, forms, reports, and macros. Next you return ownership of the database and these objects to the default Admin user by exiting and logging on as Admin, creating a blank database, and then importing all of the objects from the original database into the new database.

  1. Start Microsoft Access.

  2. Open the database.

  3. Log on as a workgroup administrator (a member of the Admins group).

  4. Give the Users group full permissions on all tables, queries, forms, reports, and macros in the database.

    How?

  5. Exit and restart Microsoft Access, open a database, and then log on as Admin.

  6. Create a new blank database, and leave it open.

  7. Import all the objects from the original database into the new database.

    How?

  8. If users will be using the current workgroup information file when opening the database, you need to clear the password for Admin to turn off the Logon dialog box for the current workgroup. This is not necessary if users will be using the default workgroup information file created when installing Microsoft Access.

The new database is now completely unsecured. Anyone who can open the new database has full permissions on all the tables, queries, forms, reports, and macros in it. These permissions work for any workgroup because the Admin account is the same in every workgroup information file. The workgroup information file that was current when the new database was created in step 6 defines the Admins group for the new database.


 Create a new Microsoft Access workgroup information file

Create a new Microsoft Access workgroup information file

When you install Microsoft Access, the Setup program automatically creates a Microsoft Access workgroup information file that is identified by the name and organization information you specify. Because this information is often easy to determine, it's possible for unauthorized users to create another version of this workgroup information file and consequently assume the irrevocable permissions of an administrator account (a member of the Admins group) in the workgroup defined by that workgroup information file. To prevent this, create a new workgroup information file, and specify a workgroup ID (WID). Only someone who knows the WID will be able to create a copy of the workgroup information file.

  1. Exit Microsoft Access.

  2. To start the Workgroup Administrator, open the language folder, and then double-click Wrkgadm.exe. Alternatively, you can use the MS Access Workgroup Administrator shortcut in the \Program Files\Microsoft Office\Office folder.

  3. In the Workgroup Administrator dialog box, click Create.

  4. In the Workgroup Owner Information dialog box, type your name and organization, and then type any combination of up to 20 numbers and letters for the workgroup ID.

    Caution Be sure to write down your exact name, organization, and workgroup ID — including whether letters are uppercase or lowercase (for all three entries) — and keep them in a secure place. If you have to re-create the workgroup information file, you must supply exactly the same name, organization, and workgroup ID. If you forget or lose these entries, you can't recover them and might lose access to your databases.

  5. Type a new name for the new workgroup information file, and then click OK. (By default, the workgroup information file is saved in the language folder. To save in a different location, type a new path or click Browse to specify the new path.)

The new workgroup information file is used the next time you start Microsoft Access. Any user and group accounts or passwords that you create are saved in the new workgroup information file. To have others join the workgroup defined by your new workgroup information file, copy the file to a shared folder (if you didn't already save it in a shared folder in step 4), and then have each user run the Workgroup Administrator to join the new workgroup information file.


 Join a Microsoft Access workgroup using the Workgroup Administrator

Join a Microsoft Access workgroup using the Workgroup Administrator

  1. Exit Microsoft Access.

  2. To start the Workgroup Administrator, open the language folder, and then double-click Wrkgadm.exe. Alternatively, you can use the MS Access Workgroup Administrator shortcut in the \Program Files\Microsoft Office\Office folder.

  3. In the Workgroup Administrator dialog box, click Join.

  4. Type the path and name of the workgroup information file that defines the Microsoft Access workgroup you want to join, and then click OK, or click Browse and then use the Select Workgroup Information File dialog box to locate the workgroup information file.

    The next time you start Microsoft Access, it uses the user and group accounts and passwords stored in the workgroup information file for the workgroup you joined.

Important If you are setting up user-level security and need to make sure that your workgroup and its permissions can't be duplicated, you should make sure the workgroup information file that defines the workgroup you're joining has been created with a unique workgroup ID (WID). If such a workgroup information file doesn't exist, you should create one. For information on creating a new workgroup information file, click [image] .


 Set up more than one workgroup to use the same secure database

Set up more than one workgroup to use the same secure database

You can give users in different Microsoft Access workgroups access to a secure database and its objects by creating a group account with an identical name and personal ID (PID) in each workgroup that you want to share the secure database. You then add users in each workgroup to that group account. This is useful if you want users at remote locations to manage their own workgroup membership.

  1. Exit Microsoft Access.

  2. Use the Workgroup Administrator to join one of the workgroups.

    How?

  3. Start Microsoft Access, open a database, and then log on as a workgroup administrator (a member of the Admins group).

  4. Create a group account, making sure to write down the exact case-sensitive group name and PID.

    How?

  5. Add users to the new group.

    How?

    Note You can add users to this group or delete them at any time.

  6. Repeat steps 1 through 5 for each workgroup that will share the same secured database. In step 3, make sure to type exactly the same case-sensitive group name and PID as you did for the group account you created in the first workgroup.

  7. Open the secure database you want to share between the workgroups and assign permissions to the new group.

    How?

Note You can also have a workgroup administrator at a remote location add the same group to his or her workgroup information file by providing the administrator with the exact case-sensitive group name and PID you used to create that group in your workgroup information file.


 Log on to a Microsoft Access workgroup

Log on to a Microsoft Access workgroup

The Logon box is displayed only if the logon procedure has been activated for your Microsoft Access workgroup. Once the logon procedure has been activated, you must identify yourself at startup by entering a valid user account name. If a password has been added to a user account, you must also enter the password. Passwords are case-sensitive.

  1. If necessary, change to the workgroup that contains the user account you want to use to log on, by using the Microsoft Access Workgroup Administrator.

    How?

  2. Start Microsoft Access, and open a database. If the logon procedure has been activated, the Logon box is displayed.

  3. Type your user account name in the Name box. Your user account name isn't case-sensitive.

  4. If your password has been defined, type your password in the Password box; otherwise, leave it blank.

For information about activating the logon procedure, click [image] .

For information about adding a password to your account, click [image] .


 Require users to log on to Microsoft Access

Require users to log on to Microsoft Access

Until you activate the logon procedure for a workgroup, Microsoft Access automatically logs on all users at startup using the predefined Admin user account. You require users in a workgroup to log on by adding a password to the Admin user account.

  1. Join the workgroup with the logon procedure you want to activate.

    How?

  2. Start Microsoft Access, and then open a database.

  3. On the Tools menu, click Security, and then click User And Group Accounts.

  4. Click the Users tab, and make sure that the predefined Admin user account is highlighted in the Name box.

  5. Click the Change Logon Password tab, click the New Password box, and type the new password. Don't type anything in the Old Password box.

    To maintain the security of your password, Microsoft Access displays asterisks (*) as you type. Passwords can be from 1 to 20 characters, and can include any characters except ASCII character 0 (null). Passwords are case-sensitive.

  6. Verify the password by typing it again in the Verify box, and then click OK.

    The Logon dialog box is displayed the next time any member of the workgroup that you joined in step 1 starts Microsoft Access and opens a database. If no user accounts are currently defined for that workgroup, the Admin user is the only valid account at this point. For information on defining user accounts, click [image] .

Note When you secure a database, you create user accounts in a Microsoft Access workgroup, and then assign permissions for databases, tables, queries, forms, reports, and macros to those accounts and to any group accounts to which they belong. When users log on to Microsoft Access by using their accounts, they have only the permissions associated with those accounts. Users log on to Microsoft Access by typing a user name and password in the Logon dialog box.


 Turn off the Logon dialog box

Turn off the Logon dialog box

  1. Join the workgroup with the logon procedure that you want to deactivate.

    How?

  2. Start Microsoft Access and open a database.

  3. On the Tools menu, click Security, and then click User And Group Accounts.

  4. Click the Users tab. In the Name box, select Admin from the list, and then click Clear Password.

    The next time any member of the workgroup that you joined in step 1 starts Microsoft Access and opens a database, it will no longer display the Logon dialog box.

Note This procedure does not remove any user-level security defined for the database. For information on removing user-level security completely, click [image] .


 Rebuild a workgroup information file from user and group names and IDs

Rebuild a workgroup information file from user and group names and IDs

If a workgroup information file becomes damaged or has been deleted, and a backup copy isn't available, you can re-create the workgroup information file if you have the exact, case-sensitive information that you used to create the file and define the accounts and groups in the file originally.

  1. Create a new workgroup information file, making sure to enter the exact, case-sensitive name, company name, and workgroup ID that you used to create the original file. Failure to re-enter the exact entries used to create the original file will create an invalid Admins group.

    How?

  2. Re-create any group accounts, making sure to enter the exact, case-sensitive group name and personal ID (PID) for each group.

    How?

  3. Re-create each user account, making sure to enter the exact, case-sensitive user name and PID for each user.

    How?

  4. If you saved the new workgroup information file to a new name or location in step 1, tell other users in the workgroup to use the Workgroup Administrator to join the new workgroup information file.


 Restore a damaged or deleted Microsoft Access workgroup information file

Restore a damaged or deleted Microsoft Access workgroup information file

In rare circumstances, the Microsoft Access workgroup information file can become damaged. If you start Microsoft Access and that file can't be opened, a message will be displayed. How you solve this problem depends on whether you have a backup copy and how your workgroup information file was originally created or specified. The following table summarizes how you should address each situation.

Used Workgroup Administrator | Made backup copy | Solution
No. Used default file created when installing Microsoft Access. | No | Re-start Microsoft Access and Windows installer will re-create a default workgroup information file.
No. Used default file created when installing Microsoft Access. | Yes | Use Windows Explorer, My Computer, MS-DOS copy command, or backup software to copy the most recent copy of the file to the folder where you installed Microsoft Access.
Yes. Created a new file. | No | Run the Workgroup Administrator again, typing the same case-sensitive name, organization, and workgroup ID entries you used when you originally created it. For more information on creating a workgroup information file, click [image] .
Yes. Created a new file. | Yes | Copy or restore the backup copy to the path where you originally saved your workgroup information file.
Yes. Joined (specified) a file on a path other than the folder where Microsoft Access is installed. | Yes | Copy or restore the backup copy to the original path.
Yes. Joined (specified) a file on a path other than the folder where Microsoft Access is installed. | No | Create a new copy by using the method that was used to create the original file: re-start Microsoft Access so that installer will re-create a default workgroup information file, or use Workgroup Administrator and type the same case-sensitive name, organization, and workgroup ID entries used when it was originally created.

Important Microsoft Access stores security account information in the workgroup information file. So in all cases where you don't have a backup copy and have to re-create a workgroup information file, if you've restricted permissions to your databases, you must re-create security accounts with the same case-sensitive names and personal ID (PID) entries as before. For more information on rebuilding a workgroup information file using user and group names and IDs, click [image] .

You don't have to redefine permissions or object ownership because this information is stored in the secure databases.


 Create a security administrator account

Create a security administrator account

To complete this procedure, you must be logged on as a member of the Admins group.

  1. Start Microsoft Access by using a secure workgroup.

    Important To make sure your database is completely secure, don't use the default workgroup defined by the workgroup information file that was created when you installed Microsoft Access. You should make sure the workgroup information file that defines the workgroup you are using has been created by using a unique workgroup ID (WID) , and, if not, you should create a new file.

    For information on joining an existing workgroup, click [image] . For information on creating a new workgroup information file, click [image] .

  2. Open a database.

  3. On the Tools menu, point to Security, and then click User And Group Accounts.

  4. On the Users tab, click New.

  5. In the New User/Group dialog box, type the name of the administrator account and a personal ID (PID), and then click OK to create the new account.

    User names can range from 1 to 20 characters, and can include alphabetic characters, accented characters, numbers, spaces, and symbols, with the following exceptions:

    • The characters " \ [ ] : | < > + = ; , . ? *

    • Leading spaces

    • Control characters (ASCII 10 through ASCII 31)

    Caution Be sure to write down the exact account name and PID entries, including whether letters are uppercase or lowercase, and keep them in a secure place. If you ever have to re-create the account, you must supply the same name and PID entries. If you forget or lose these entries, you can't recover them.

  6. In the Available Groups box, click Admins, and then click Add.

    Microsoft Access adds the new administrator account to the Admins group and displays Admins in the Member Of box.

Note The PID entered in step 5 is not a password. Microsoft Access uses the PID and the user name as seeds for an encryption algorithm to generate a secure identifier for the user account. For information on creating passwords, click [image] .


 Create a security user account

Create a security user account

To complete this procedure, you must be logged on as a member of the Admins group.

  1. Start Microsoft Access by using the workgroup in which you want to use the account.

    Important The accounts you create for users must be stored in the workgroup information file that those users will use. If you're using a different workgroup to create the database, change your workgroup before creating the accounts.

    For information on joining an existing workgroup, click [image] . For information on creating a new workgroup information file, click [image] .

  2. Open a database.

  3. On the Tools menu, point to Security, and then click User And Group Accounts.

  4. On the Users tab, click New.

  5. In the New User/Group dialog box, type the name of the new account and a personal ID (PID), and then click OK to create the new account, which is automatically added to the Users group

    User names can range from 1 to 20 characters, and can include alphabetic characters, accented characters, numbers, spaces, and symbols, with the following exceptions:

    • The characters " \ [ ] : | < > + = ; , . ? *

    • Leading spaces

    • Control characters (ASCII 10 through ASCII 31)

    Caution Be sure to write down the exact account name and PID, including whether letters are uppercase or lowercase, and keep them in a secure place. If you ever have to re-create an account that has been deleted or created in a different workgroup, you must supply the same name and PID entries. If you forget or lose these entries, you can't recover them.

Notes

  • The PID entered in step 5 is not a password. Microsoft Access uses the PID and the user name as seeds for an encryption algorithm to generate a secure identifier for the user account. For information on creating passwords, click [image] .

  • It is usually easier to manage security if you organize users into groups, and then assign permissions to groups rather than to individual users.


 Create a security group account

Create a security group account

As part of securing a database, you can create group accounts in your Microsoft Access workgroup that you use to assign a common set of permissions to multiple users.

To complete this procedure, you must be logged on as a member of the Admins group.

  1. Start Microsoft Access by using the workgroup in which you want to use the account.

    Important The accounts you create for users must be stored in the workgroup information file that those users will use. If you're using a different workgroup to create the database, change your workgroup before creating the accounts. You can change workgroups by using the Workgroup Administrator.

  2. Open a database.

  3. On the Tools menu, point to Security, and then click User And Group Accounts.

  4. On the Groups tab, click New.

  5. In the New User/Group dialog box, type the name of the new account and a personal ID (PID).

    Group names can range from 1 to 20 characters, and can include alphabetic characters, accented characters, numbers, spaces, and symbols, with the following exceptions:

    • The characters " \ [ ] : | < > + = ; , . ? *

    • Leading spaces

    • Control characters (ASCII 10 through ASCII 31)

    Caution Be sure to write down the exact account name and PID, including whether letters are uppercase or lowercase, and keep them in a secure place. If you have to re-create an account that has been deleted or created in a different workgroup, you must supply the same name and PID entries. If you forget or lose these entries, you can't recover them.

  6. Click OK to create the new group account.


 Add users to security groups

Add users to security groups

To complete this procedure, you must be logged on as a member of the Admins group.

  1. Start Microsoft Access by using the workgroup that contains the user and group accounts.

    You can find out which workgroup is current or change workgroups by using the Workgroup Administrator.

  2. Open a database.

  3. On the Tools menu, point to Security, and then click User And Group Accounts.

  4. On the Users tab, enter in the Name box the user you want to add to a group.

  5. In the Available Groups box, click the group you want to add the user to, and then click Add.

    The selected group is displayed in the Member Of list.

  6. Repeat step 5 if you want to add this user to any other groups. Repeat steps 4 and 5 to add other users to groups. Click OK when you have finished.


 Print information about security users and groups

Print information about security users and groups

  1. Start Microsoft Access by using the workgroup information file whose security information you want to print.

    You can find out which workgroup information file is current, or change workgroups by using the Workgroup Administrator.

  2. Open a database.

  3. On the Tools menu, point to Security, and then click User And Group Accounts.

  4. On the Users tab, click Print Users And Groups.

  5. In the Print Security dialog box, click Only Users to print a report showing all users defined for the current workgroup, or Only Groups to print a report showing all groups defined for the current workgroup. Click Both Users And Groups to print both user and group account information.

  6. Click OK.

Note If you are using a workgroup information file created with Microsoft Access version 2.0, you must be logged on as a member of the Admins group to print user and group information. If the workgroup information file was created with Microsoft Access version 7.0 or later, all users in the workgroup can print user and group information.


 Remove users from security groups

Remove users from security groups

To complete this procedure, you must be logged on as a member of the Admins group.

  1. Start Microsoft Access by using the workgroup containing the user and group accounts.

    You can find out which workgroup is current or change workgroups by using the Workgroup Administrator.

  2. Open a database.

  3. On the Tools menu, point to Security, and then click User And Group Accounts.

  4. On the Users tab, enter the user you want to remove in the Name box.

  5. In the Member Of box, click the group you want to remove the user from, and then click Remove.

  6. Repeat step 5 if you want to remove this user from any other groups. Repeat steps 4 and 5 to remove other users from groups. Click OK when you are finished.

Notes

  • You can't remove users from the default Users group. Microsoft Access automatically adds all users to the Users group. To remove any user account from the Users group, you must delete the account. For information on deleting a user account, click [image] .

  • There must be at least one user in the predefined Admins group at all times.


 Delete a security user account

Delete a security user account

To complete this procedure, you must be logged on as a member of the Admins group.

  1. Open a database.

  2. On the Tools menu, point to Security, and then click User And Group Accounts.

  3. On the Users tab, enter a user in the Name box, and then click Delete.

  4. Click Yes to delete the user account.

  5. Repeat steps 3 and 4 if you want to delete additional user accounts, and then click OK when you have finished.

Note The Admin user account can't be deleted.


 Delete a security group account

Delete a security group account

To complete this procedure, you must be logged on as a member of the Admins group.

  1. Start Microsoft Access by using the workgroup that contains the account you want to delete.

    You can find out which workgroup is current or change workgroups by using the Workgroup Administrator.

  2. Open a database.

  3. On the Tools menu, point to Security, and then click User And Group Accounts.

  4. On the Groups tab, enter the group you want to delete in the Name box, and then click Delete.

  5. Click Yes to delete the group account.

  6. Repeat steps 4 and 5 if you want to delete additional group accounts, and then click OK when you have finished.

Note The Admins and Users group accounts can't be deleted.


 Create or change a security account password

Create or change a security account password

A security account password is created to make sure that no other user can log on using that user name. By default, Microsoft Access assigns a blank password to the Admin user account, and to any new user accounts you create in your workgroup.

  1. Start Microsoft Access by using the workgroup the user account is stored in, and log on using the name of the account for which you want to create or change the password.

    You can find out which workgroup is current or change workgroups by using the Workgroup Administrator.

  2. Open a database.

  3. On the Tools menu, point to Security, and then click User And Group Accounts.

  4. On the Change Logon Password tab, leave the Old Password box blank if a password hasn't been defined previously for this account. Otherwise, type the current password in the Old Password box.

  5. Type the new password in the New Password box.

    A password can range from 1 to 20 characters, and can include any characters except ASCII character 0 (null). Passwords are case-sensitive.

  6. Retype the password in the Verify box, and then click OK.

Caution You can't recover your password if you forget it, so be sure to store it in a safe place. If you forget your password, a user logged on with an administrator account (a member of the Admins group in the workgroup in which the account and password were created) must clear the password before you can log on.


 Clear a security account password

Clear a security account password

To complete this procedure, you must be logged on as a member of the Admins group.

  1. Start Microsoft Access by using the workgroup information file in which the user account (and its password) is stored.

    You can find out which workgroup information file is current or change workgroups by using the Workgroup Administrator.

  2. Open a database.

  3. On the Tools menu, point to Security, and then click User And Group Accounts.

  4. On the Users tab, enter the user account name in the Name box.

  5. Click Clear Password.

  6. Repeat steps 4 and 5 to clear any additional passwords, and then click OK when you have finished.


 View or transfer ownership of individual tables, queries, forms, reports, and macros in a secure database

View or transfer ownership of individual tables, queries, forms, reports, and macros in a secure database

If you have Administer permission for a table, query form, report, or macro, you can change the ownership of the object to another user or group.

  1. Open the database.

  2. On the Tools menu, click Security, and then click User And Group Permissions.

    On the Change Owner tab, Microsoft Access displays a list of the tables, queries, forms, reports, and macros that are currently displayed in the Database window, and the current owner of those objects.

  3. Click an object type in the Object Type box, or use the existing object type.

  4. From the Object list, click one or more objects with ownership that you want to change. To select more than one object, either hold down CTRL and click the objects, or drag through the ones you want to select.

  5. In the New Owner box, click the user or group account that you want to be the new owner of the object or objects.

  6. Click the Change Owner button.

Note If you change ownership of an table, query, form, report, or macro to a group account, all users who belong to the group automatically receive the permissions associated with ownership of the object.


 Transfer ownership of an entire database to another administrator

Transfer ownership of an entire database to another administrator

  1. Start Microsoft Access by using a secure workgroup that contains the user account that you want to own the database and its objects.

  2. Log on by using that account.

  3. Create a new blank database.

  4. Import all of the objects from the database that has the ownership you want to change into the new database.

    How?

Note To import a database, you must have Open/Run permission for the database, and Read Design permission for its objects. To import tables, you must also have Read Data permission. If you have permissions for some tables, queries, forms, reports, and macros but not others, Microsoft Access imports only those objects for which you have permissions.


 Assign default permissions for new tables, queries, forms, reports, and macros

Assign default permissions for new tables, queries, forms, reports, and macros

  1. Open the database that contains the tables, queries, forms, reports, and macros.

  2. On the Tools menu, click Security, and then click User And Group Permissions.

  3. On the Permissions tab, click Users or Groups, and then click the user or group that has the permissions you want to assign in the User/Group Name box.

  4. Click the type of object in the Object Type box, and click <New object> in the Object Name list.

    The <New object> selection varies depending on the type of object you've selected — <New Tables/Queries>, <New Forms>, <New Reports>, or <New Macros>.

  5. Select the default permissions that you want to assign for that object type, and then click Apply. Repeat steps 4 and 5 to assign default permissions for additional object types for the current user or group.

    For information on all the permissions you can assign, click [image] .

  6. Repeat steps 3 through 5 for any additional users or groups, and then click OK when you have finished.

Notes

  • Default permissions can be assigned only by an administrator account (a member of the Admins group in the workgroup in which the database that contains the object was created) or by the owner of the database.

  • Some permissions automatically imply the selection of others. For example, the Modify Data permission for a table automatically implies the Read Data and Read Design permissions because you need these to modify the data in a table. Modify Design and Read Data imply Read Design. For macros, Read Design implies Open/Run.

  • Organizing user accounts into groups makes it easier to manage security. For example, rather than assigning permissions to each user for each object in your database, you can assign permissions to a few groups, and then add users to the appropriate group. When users log on to Microsoft Access, they inherit the permissions of any groups to which they belong.


 Assign or remove permissions for a database and existing tables, queries, forms, reports, and macros

Assign or remove permissions for a database and existing tables, queries, forms, reports, and macros

  1. Open the database that contains the tables, queries, forms, reports, and macros that you want to secure.

    The workgroup information file in use when you log on must contain the user or group accounts that you want to assign permissions for at this time; however, you can assign permissions to groups and add users to those groups later.

  2. On the Tools menu, click Security, and then click User And Group Permissions.

  3. On the Permissions tab, click Users or Groups, and then click the user or group that has the permissions you want to assign in the User/Group Name box.

  4. Click the type of object in the Object Type box, and then click the name of the object to assign permissions for in the Object Name box.

    Tip You can select multiple objects in the Object Name box by dragging through the objects you want to select, or by holding down CTRL and clicking the objects you want.

  5. Under Permissions, select the permissions you want to assign, or clear the permissions you want to remove for the group or user, and then click Apply. Repeat steps 4 and 5 to assign or remove permissions for additional objects for the current user or group.

    For information on all the permissions you can assign, click [image] .

  6. Repeat steps 3 through 5 for any additional users or groups, and then click OK when you have finished.

Notes

  • For information on who can assign and remove permissions, click [image] .

  • Some permissions automatically imply the selection of others. For example, the Modify Data permission for a table automatically implies the Read Data and Read Design permissions because you need these to modify the data in a table. Modify Design and Read Data imply Read Design. For macros, Read Design implies Open/Run.

  • When you edit an object and save it, it retains its assigned permissions. However, if an object is saved with a new name by using the Save As command on the File menu, or by cutting and pasting, importing, or exporting the object, the associated permissions are lost, and you have to reassign them. This is because you are creating a new object that is assigned the default permissions defined for that object type.

  • Hidden objects aren't displayed in the Object Name box unless you select Hidden objects on the View tab of the Options dialog box (Tools menu).


 RunPermissions Property

RunPermissions Property

You can use the RunPermissions property in a multiuser environment with a secure workgroup to override the existing user permissions. This allows you to view a query or run an append, delete, make-table, or update query that you otherwise 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 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.

Setting | Description
Owner's | All users are allowed the owner's permissions to view or run the query.
User's | (Default) Users have only their own permissions to view or run the query.

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


Convert a Microsoft Access version 2.0 secured database

  1. Convert the secured database.

    How?

  2. Convert the workgroup information file (typically named system.mda) that is used with the secured database.

    How

  3. Tell users to join the converted workgroup information file before opening the secured database.

    How


 Convert a Microsoft Access 95 or 97 secured database

Convert a Microsoft Access 95 or 97 secured database

When upgrading from Microsoft Access 95 or 97, you need to convert your secured database, but you don't need to convert the workgroup information file to use it with Microsoft Access 2000. However, you should compact the workgroup information file before using it.

  1. Convert the secured database.

    How

  2. Compact the secured database.

    How

  3. Exit Microsoft Access.

  4. Before compacting the workgroup information file (typically named system.mdw) that was used with the secured database, temporarily join another workgroup information file.

    How?

  5. Start Microsoft Access without opening a database.

  6. Compact the workgroup information file that was used with the secured database.

  7. Tell users to join the compacted workgroup information file before opening the secured database.


 Convert a workgroup information file from a previous version of Microsoft Access

Convert a workgroup information file from a previous version of Microsoft Access

To take advantage of security and performance improvements, you should re-create the workgroup information file as described below.

  1. Create a new workgroup information file, making sure to enter the exact, case-sensitive name, company name, and workgroup ID that was used to create the original file. Failure to re-enter the exact entries that were used to create the original file will create an invalid Admins group.

    How?

  2. Re-create any group accounts, making sure to enter the exact, case-sensitive group name and personal ID (PID) for each group.

    How?

  3. Re-create each user account, making sure to enter the exact, case-sensitive user name and PID for each user.

    How?

  4. Tell other Microsoft Access 2000 users in the workgroup to use the Workgroup Administrator to join the new workgroup information file.


 Share a previous-version secured database across several versions of Microsoft Access

Share a previous-version secured database across several versions of Microsoft Access

With one exception, the issues involved when sharing a secured database across more than one version of Microsoft Access are the same as the issues for sharing an unsecured database across more than one version. For more information on the general issues of sharing a database across more than one version of Microsoft Access, click [image] .

The one exception concerns how to handle the workgroup information files that is used with the secured database. You have two choices:

  • Tell users who will be upgrading to Microsoft Access 2000 to join the appropriate workgroup information file with the oldest version of Microsoft Access that will be sharing the secured database. Microsoft Access 2000 can use workgroup information files that have been created with previous versions, but previous versions can only use workgroup information files that have been created with Microsoft Access 2000 or a previous version. For more information on joining a workgroup information file, click [image] .

    Important If users will be sharing a secured database from Microsoft Access 95 or 97, you should compact the current workgroup information file with Microsoft Access 2000 before using it. Compacting the file by using Microsoft Access 2000 does not change the file format, so the file can continue to be used by any Microsoft Access 95 or 97 users who are not upgrading. For more information on compacting a database, click [image] .

  • If the shared database is Microsoft Access version 2.0, convert the workgroup information file that will be used with the secured database, and then tell only users who are upgrading to Microsoft Access 2000 to join the converted workgroup information file. All users who are not upgrading from version 2.0, must continue to use the workgroup information file produced with that version. For more information on converting a workgroup information file, click [image] .


 About replication in a Microsoft Access project

About replication in a Microsoft Access project

A Microsoft Access project contains several wizards to help you create a publication and subscription. Access projects support push, pull, and bi-directional synchronization.

In a project, you replicate the data, not the forms, reports, and other objects that are contained in the project. And a project can not contain an Access database replica.

For more information about replication with an Access project, learn about the Microsoft SQL Server documentation.

More information

About synchronizing data in your replica set


 Create Partial Replicas

Create Partial Replicas

What Are Partial Replicas?

Partial replicas are replicas that contain only a subset of records in a full replica. To create a partial replica, you specify a filter that restricts the data that's synchronized to a subset of the full database. By using partial replicas, you can synchronize a replica with only the data that you need, rather than with an entire database.

For example, a business might store its entire sales database at the headquarters office but replicate only regional data to its regional offices across the country. You can create a separate replica for each regional office that contains only the data relating to that region. The database at the headquarters office would be a full replica, with which each partial replica would be synchronized.

Advantages of Using Partial Replicas

Partial replicas can make your database effectively smaller, since you need only replicate the portions that you work with frequently. Synchronizing a partial replica takes less time, and the replica itself requires less disk space.

Partial replicas can help restrict access to data. In the case of a sales database, partial replicas can help ensure that people in a regional sales office won't view sales data for other regional offices. Although you can use partial replicas to restrict access to records, they aren't a substitute for a security system.

Partial replicas also have benefits for replicating data over local area networks (LANs) and wide area networks (WANs). By restricting which data is replicated, partial replicas can reduce the amount of data transferred over a LAN or a long-distance carrier. This can reduce network traffic and lower telecommunications costs.

Creating a Partial Replica with ActiveX Data Objects (ADO)

To create a partial replica, follow these steps:

  1. Use the CreateReplica method on a Replica object, specifying the jrRepTypePartial constant in the replicatype argument. This creates the partial replica.

  2. Use the Filters property to set the desired filters and relationships that determine which data to replicate from the full replica.

  3. Use the PopulatePartial method to transfer all records from the full replica that meet the new replica filter criteria.

When you change data or the filter criteria in the partial replica, you should use the Synchronize and PopulatePartial methods together to ensure that all data is propagated to the full replica and that the partial replica is repopulated based on the current filter criteria.

Note Once you create a partial replica, you can't convert it to a full replica. If you remove all of the replica filters and replica relations within the partial replica, it will contain all the records of a full replica, but it will still have the same limitations and restrictions of a partial replica.

Creating a Partial Replica with Data Access Objects (DAO)

To create a partial replica, follow these steps:

  1. Use the MakeReplica method on a Database object, specifying the dbRepMakePartial constant in the options argument. This creates the partial replica.

  2. Use the ReplicaFilter and PartialReplica properties to set the desired filters and relationships that determine which data to replicate from the full replica.

  3. Use the PopulatePartial method to transfer all records from the full replica that meet the new replica filter criteria.

When you change data or the filter criteria in the partial replica, you should use the Synchronize and PopulatePartial methods together to ensure that all data is propagated to the full replica and that the partial replica is repopulated based on the current filter criteria.

Note Once you create a partial replica, you can't convert it to a full replica. If you remove all of the replica filters and replica relations within the partial replica, it will contain all the records of a full replica, but it will still have the same limitations and restrictions of a partial replica.

Partial Replicas and Referential Integrity

In a replica that has relationships that enforce referential integrity, many of the tables in the database may be related to the table on which your filter is based. When you create a partial replica, you need to make certain that you include any tables that are related to the table containing the data you want.

For example, if you're using the Northwind sample database, you might place a filter on an Employees table, such as [EmployeeID]=1, that synchronizes only one employee's records. Because the Employees table is in a relationship with the Orders and Order Details tables, you must also include those tables so that your partial replica includes the corresponding records for that employee in the Orders and Order Details tables.

You may need to include other tables that are only indirectly related to your filter. For example, you may want your partial replica to include a list of all products so that new orders can include any products that are available. In this case, you must include the Products table in your partial replica.

You should also be aware of tables in your database that have no enforced relationships, such as lookup tables, or tables with relationships where referential integrity isn't enforced. For example, a table that populates a combo box might not take part in any relationships. If you choose to include such a table, all records will be retrieved; otherwise no records will be retrieved.

For more information about partial replicas and tools to create them, see Chapter 16, "Multiuser Database Applications" in the Microsoft Office 2000/Visual Basic Programmer's Guide. For information about how to obtain the Microsoft Office 2000/Visual Basic Programmer's Guide, click [image] .


 Specify the initial keyboard language in a text box or combo box

Specify the initial keyboard language in a text box or combo box

Language-specific information

You can select the type of keyboard language you want in a text box or combo box.

  1. Open a form or report in Design view.

  2. Make sure the control is selected, and then click Properties [image] on the toolbar.

  3. On the All tab, in the KeyboardLanguage box, do one of the following:

    To make the keyboard language follow the most recent keyboard language you used, click System.

    To make the keyboard language a particular language, click one of the languages shown in the list.

Notes

  • The languages that appear in the KeyboardLanguage property box are determined by the keyboard languages you have installed by double-clicking Keyboard in Windows Control Panel.

  • Learn about right-to-left properties.


Work with the euro

What do you want to do?

Learn about euro support in Microsoft Windows 95 and Windows NT 4.0

Work with the euro symbol ( [image])

Display the euro symbol in a field on a data access page

Use the Format property

Use the EuroConvert function


 About Correct Keyboard Setting

About Correct Keyboard Setting

Language-specific information

Correct Keyboard Setting is a feature that automatically corrects words entered in English mode that were meant to be entered in hangul mode, and vice versa. For example, if you enter eogksalsrnr in English mode, it will be changed to tae han min kuk; and if you enter yo u ya p d gya nya syo in hangul mode, it will be changed to university. Also, IME mode is changed automatically.

Correct Keyboard Setting also automatically corrects English words that have a hangul ending entered in English mode, and vice versa. For example, if you enter optiondmf in English mode, it is automatically changed to option ul.

Correct Keyboard Setting works even when hangul and English are mixed. For example, if you enter rntjddnjs ppyo mi ya syo, it is automatically changed to ku song won quality.


 Set the encoding for a Web page

Set the encoding for a Web page

When you are authoring a data access page in Design view, you can specify the encoding that a Web browser will use to display the page.

  1. Open the data access page in Design view.

  2. On the Tools menu, click Options.

  3. Click the General tab, and then click Web Options.

  4. In the Web Options dialog box, click the Encoding tab.

  5. Click the language you want in the Save this document as list.

Note To have Access always save your pages using a default language encoding, select the Always save Web pages in the default encoding check box. This setting affects the current page and future pages that you save. This setting is useful if you reuse pages from other sources and want to store every page in one encoding.


Turn on Correct Keyboard Setting

Language-specific information

  1. On the Tools menu, click AutoCorrect.

  2. On the AutoCorrect tab, select the Correct Keyboard Setting check box.


 About bidirectional fonts

About bidirectional fonts

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

Any version of Access 2000 with left-to-right support is designed to display and print both right-to-left and left-to-right text. To do this, the program should use a font that contains both right-to-left and left-to-right language characters. Most fonts available with bidirectional Windows operating systems contain both right-to-left and left-to-right characters. If you choose a font that does not contain both right-to-left and left-to-right characters, existing text in one or both languages might be displayed incorrectly by using the default secondary font, Tahoma. To correct this problem, choose a different font.

More information

Set defaults for the appearance of Datasheet view

Change font, or font style, size, and color in Datasheet view

Change the font of text in a text box or other control


 About bidirectional properties of the user interface

About bidirectional properties of the user interface

Language-specific information

The options that appear in dialog boxes and other elements of the Microsoft Access 2000 user interface do not have properties that can be set. Although you cannot change their property settings, they do have bidirectional characteristics. Access 2000 assigns the following values:

Property | Value
KeyboardLanguage | System
TextAlign | General
ReadingOrder | Context
ScrollBarAlign | System
NumeralShapes | System

If the option contains no text, reading order is determined by the keyboard language when the control is entered: Right-to-left if the keyboard language is a right-to-left language, and left-to-right if otherwise. Initial alignment and insertion point position are determined by the General alignment setting.

Note CTRL+LEFT SHIFT and CTRL+RIGHT SHIFT keyboard sequences used to change keyboard language, reading order, and alignment in other bidirectional applications will temporarily change reading order and alignment.


 About checking the spelling of bidirectional text

About checking the spelling of bidirectional text

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

You can check the spelling of both your English and right-to-left text in the Memo, Text, and Hyperlink fields. Just choose a dictionary that corresponds to the text that will be used.

Note You must be using a right-to-left version of Microsoft Office 2000 to be able to check spelling in right-to-left text.

When right-to-left text is checked, English words are ignored and not flagged as misspelled. However, when English text is checked, right-to-left words aren't ignored.

What do you want to do?

Check the spelling of data

Choose a custom dictionary for checking spelling


 About right-to-left feature compatibility

About right-to-left feature compatibility

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

Access 2000 provides full forward compatibility for database files saved in all previous versions of Microsoft Access and Microsoft Access with right-to-left support; however, databases saved in Access 2000 file format are not compatible with any previous versions of Microsoft Access.


 About right-to-left properties

About right-to-left properties

Language-specific information

Microsoft Access 2000 has specific right-to-left properties to support bidirectional data entry and display.

This topic provides reference information about the following properties:

  • ReadingOrder

  • KeyboardLanguage

  • TextAlign

  • ScrollBarAlign

  • NumeralShapes (Arabic only)

The settings for these properties are initially determined when the control is placed on the grid in form Design view or report Design view.

Note The settings associated with these properties are available for forms and reports. Control behavior for tables and queries is a fixed, bidirectional-capable configuration: ScrollBarAlign = System, NumeralShapes = System, KeyboardLanguage = System, TextAlign = General, ReadingOrder = Context, and initial insertion point position = data dependent. If the control contains no text, then alignment, reading order, and initial insertion point position are determined by the keyboard language when the control is entered: Right-to-Left if the keyboard language is a right-to-left language, and Left-to-Right if otherwise.

ReadingOrder property

Determines the reading order of the control. You can specify right-to-left or left-to-right reading order or choose to have the reading order determined by the keyboard language of text first entered. See how to set the ReadingOrder property for a control.

Return to top

KeyboardLanguage property

The KeyboardLanguage property overrides the keyboard language that is currently in use (including changing the active keyboard language icon on the taskbar). This property specifies the initial keyboard language when the control receives focus. This feature is useful for volume data entry programs because it reduces the need to make keyboard language changes when moving from one field to the next. You can subsequently choose a new keyboard language.

In Form view or Datasheet view, Microsoft Access 2000 will activate the designated keyboard language. If the operation fails (most likely because the requested keyboard language is not available on the developer/user system), the active keyboard language is not changed. For more sophisticated error handling, refer to the discussion of the Visual Basic for Applications KeyboardLanguage property. See how to set the KeyboardLanguage property for a control.

Return to top

TextAlign property

This property determines the placement of text within a control. In addition to the standard left, right, and center character alignments, right-to-left features in Access 2000 use the General alignment setting to specify how text is aligned. See how to set the TextAlign property for a control.

Return to top

ScrollBarAlign property

This property allows you to place the control's vertical scroll bars and buttons in the applicable right-to-left or left-to-right direction. The System setting orients the vertical scroll bar according to the user-interface language in effect. If the user-interface language is a right-to-left language, the vertical scroll bar will be on the left; if the user interface language is a left-to-right language, the vertical scroll bar will be on the right. See how to set the ScrollBarAlign property for a control.

Return to top

NumeralShapes property (Arabic only)

Two different representations of digit shapes are used in Middle Eastern countries: Arabic and Hindi. You can choose to have text in controls be specifically Arabic or Hindi, you can let the Microsoft Windows operating system determine the numerals, or you choose the numeral shape depending on the context of adjacent text. See how to set the NumeralShapes property for a control.

Return to top


 About the hierarchy of setting right-to-left features

About the hierarchy of setting right-to-left features

Language-specific information

The appearance of an object and the behavior of its right-to-left features are determined by a hierarchy of settings. The following progression illustrates this point:

  • The Default Direction setting on the Right-to-Left tab in the Options dialog box sets the direction for new forms or reports to right-to-left (unless the default was manually changed to left-to-right).

  • In the property sheet for a form or report, you can change the direction for a specific form or report by setting the Orientation property. This change will determine the default value of related left-to-right and right-to-left direction properties for each new control on that form or report.

  • Each control has a default set of right-to-left properties that can be changed for that individual control.

  • After controls are placed on the design grid, you can move them and change their right-to-left properties to change their appearance and behavior.


 Change the default for a right-to-left feature

Change the default for a right-to-left feature

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

You can set the default behavior for several right-to-left features.

What do you want to do?

Set the direction for new tables, queries, forms, reports, and pages

Set insertion point behavior

Specify alignment behavior for General alignment

Switch between Gregorian and Hijri calendars for the current database


 Specify alignment behavior for General alignment

Specify alignment behavior for General alignment

Language-specific information

  1. Click Options on the Tools menu, and then click the Right-to-Left tab.

  2. Do one of the following in the General Alignment option group:

    Click Interface Mode to align text and numbers in text fields according to the user interface language in effect.

    Click Text Mode to align text and numbers in text fields according to the keyboard language of the text first entered.


 About creating macros in right-to-left applications

About creating macros in right-to-left applications

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

You can create custom menus bars in a right-to-left or left-to-right direction. The following are some considerations to keep in mind:

  • The TransferText action allows you to choose code page format when importing, exporting, and linking files.

  • Menu bars you create can be displayed with a left-to-right or right-to-left direction. For example, if oriented right-to-left, the menu bar will display with menu items starting on the right side of the menu bar and continuing to the left in a right-to-left reading order.

  • The display direction of global and form menu bars is determined by the user-interface language.

  • You can name menu items in right-to-left, left-to-right, or bidirectional text. An ampersand (&) can be added to a menu item name to designate a menu item access key. The ampersand applies to the next character in the name and causes the character to be underlined when the menu item is displayed. In right-to-left text, this is the character to the left of the ampersand; in left-to-right text, it's the character to the right of the ampersand.

  • Macro names can be in right-to-left, left-to-right, or bidirectional text.

  • The Macro window has a left-to-right layout regardless of the user-interface language.


 About creating modules in right-to-left applications

About creating modules in right-to-left applications

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

Access 2000 supports these right-to-left characteristics in modules:

  • Statements are displayed left-aligned and in left-to-right reading order. However, you can view and edit Visual Basic for Applications statements containing right-to-left or bidirectional text.

  • You can use right-to-left, left-to-right, or bidirectional text in module names.

Visual Basic for Applications

All Visual Basic for Applications procedures and properties that provide right-to-left functionality to Microsoft Access 2000 are listed alphabetically in the following table.

Procedures and properties | Type
Calendar | Property
DataType | Property
Date, Date$ | Function
DateAdd | Function
DateDiff | Function
DatePart | Function
DateSerial | Function
DateValue | Function
Day | Function
Format, Format$ | Function
Format | Property
GetOption, SetOption | Methods
KeyboardLanguage | Property
LabelAlign, TextAlign | Properties
LabelX, LabelY | Properties
Month | Function
NumeralShapes | Property
Orientation | Property
ReadingOrder | Property
ScrollBarAlign | Property
TransferText | Action/Method
Weekday | Function
Year | Function

For development of sophisticated right-to-left applications, you might want to take advantage of the numerous Microsoft Windows operating system application programming interfaces (APIs) that have right-to-left settings. For more information, see your local Microsoft dealer.


 Set the direction for new tables, queries, forms, reports, and pages

Set the direction for new tables, queries, forms, reports, and pages

Language-specific information

  1. Click Options on the Tools menu, and then click the Right-to-Left tab.

  2. Do one of the following in the Default Direction option group:

    Click Left-To-Right to have new objects displayed in a direction familiar to left-to-right users.

    Click Right-To-Left to have new objects displayed in a direction familiar to right-to-left users.


 Change table direction

Change table direction

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

What do you want to do?

Learn about right-to-left behavior in tables

Change individual table direction

Change the default direction for new tables


 Change individual table direction

Change individual table direction

Language-specific information

  1. Open a table in Design view.

  2. Click the Properties button [image] on the toolbar.

  3. Click the Orientation property.

  4. Do one of the following:

    For a right-to-left direction, click Right-to-Left.

    For a left-to-right direction, click Left-to-Right.

Note Table direction is configurable only for tables in a Microsoft Access database (.mdb). Table direction in a Microsoft Access project (.adp) is always left to right.


 About right-to-left behavior in tables

About right-to-left behavior in tables

Language-specific information

Right-to-left characteristics for tables are summarized as follows:

New table direction The direction for new tables is determined by the Default direction setting on the Right-to-Left tab in the Options dialog box (Tools menu).

Note Table direction is configurable only for tables in a Microsoft Access database (.mdb). Table direction in a Microsoft Access project (.adp) is always left-to-right.

Existing table direction The direction of an existing tables can be "flipped" from right to left, or the reverse, by changing the table's Orientation property.

User interface direction The direction and layout of several features that support tables, such as the Design view window, the Index window, frozen columns, and key visual characteristics such as Field Properties descriptions and tabs, the current record indicator, and grid column order are determined by the user interface you are currently using.

Field properties Text and Memo fields are assigned General alignment and Context reading order. Visual layout is automatically adjusted based on the language of the first character entered in a field when General alignment is set to Text mode in the Right-to-Left tab in the Options dialog box (Tools menu). Alignment can be then overridden by creating a custom format by using the format control character, the exclamation point (!), in the Format property. Reading order, however, cannot be changed.

Note You can create tables with more sophisticated right-to-left field properties and data entry features if you create a form that uses your table as a record source, and then view the form in Datasheet view.


 Import, export, and link right-to-left tables in text formats

Import, export, and link right-to-left tables in text formats

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

Microsoft Access 2000 provides code page conversion of tables and worksheets with right-to-left characteristics for text files stored in logical text layout, with one of the following right-to-left code pages:

Language | Code page
Arabic | UTF-8 (default)
 | ISO 8859-6
 | DOS-720
 | ASMO-708
Hebrew | UTF-8 (default)
 | ISO 8859-8
 | DOS-862

To import, export, or link text files that are not recognized by Microsoft Access 2000, use ConvText, a stand-alone text-file conversion utility that provides both logical and visual text layout options and an expanded list of supported bidirectional code pages.

Note A table/worksheet in Lotus, dBASE, Microsoft FoxPro, Paradox, or ODBC database format that requires code page and/or text layout conversion can still be imported into Access 2000 by saving the table/worksheet in text file format prior to importing it. The ability to save a table/worksheet in text file format is a standard feature of most database/spreadsheet products. When Access 2000 imports the text file, all field names and records from the original table/worksheet will be fully recreated in a new Access table.

What do you want to do?

Convert bidirectional text files to ANSI

Convert bidirectional text files from ANSI


 Change query direction

Change query direction

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

What do you want to do?

Learn about right-to-left behavior in queries

Change individual query direction

Change the default direction for new queries


 About right-to-left behavior in queries

About right-to-left behavior in queries

Language-specific information

Right-to-left characteristics for queries are summarized as follows:

  • Query Design view displays the query in a layout consistent with the current user interface language.

  • The Orientation property allows you to change the overall right-to-left or left-to-right direction of the query in Datasheet view, regardless of the Default direction setting on the Right-to-Left tab in the Options dialog box (Tools menu).

Note Direction in queries is configurable only for queries in a Microsoft Access database (.mdb). Direction in queries in a Microsoft Access project (.adp) is always left-to-right.

Query Design view

All Text and Memo fields are assigned General alignment and Context reading order. Visual layout adjusts automatically based on the language of the first character entered in a field. Alignment can be overridden by creating a custom format by using the format control character, the exclamation point (!) in the Format property in the query's property sheet. Reading order, however, is fixed.

Microsoft Access 2000 provides right-to-left support to many of the other query features available in Design view. For example, if you choose to design a crosstab query, you have the same ability to use the query's property sheet to change the view direction of the crosstab query you're creating.

Query Datasheet view

The direction of the data, description fields, and other window components will be right-to-left or left-to-right depending on the query orientation you chose in Design view.

Other query design considerations

You can use right-to-left or mixed right-to-left and left-to-right text to name many of the objects you create. You can:

  • Provide bidirectional text in names given to tables you create with a make-table query.

  • Select tables with right-to-left or bidirectional text names when you add data to a table by using an append query.

  • Name query parameters with right-to-left or bidirectional text in a parameter query.

SQL

The editor displays SQL statements in an overall left-to-right direction regardless of the user interface language or chosen query view direction.

Important Dates in SQL statements are always displayed as Gregorian calendar values, regardless of database calendar chosen. If you change a date in a SQL statement, the new value MUST be a Gregorian date.


 About using bidirectional text in expressions

About using bidirectional text in expressions

Language-specific information

Microsoft Access 2000 preserves expressions with left alignment and left-to-right reading order. Expression terms are preserved in left-to-right order to ensure the visual readability of expression statements that contain mixed text. As each statement character is entered, the expression display is dynamically updated.

The following table provides examples of bidirectional text that is used in expressions:

Bidirectional text used in expressions

There are a few other considerations when using expressions with right-to-left languages:

  • Access 2000 displays Structured Query Language (SQL) statements by using the same rules it uses for displaying expressions.

  • Bidirectional control characters entered in expressions are removed prior to evaluating the expression to avoid possible conflicts.

Note Bidirectional text used in the Expression Builder will "swap" certain neutral character pairs such as "( )" and "{ }" when the keyboard language is a right-to-left language. To resolve this, change the keyboard language to a left-to-right language or type the correct character.


 Change individual query direction

Change individual query direction

Language-specific information

  1. Open a query in Design view.

  2. Select a field, field list, or query.

    To select a field, click the cell in the Field row.

    To select a field list, click anywhere in the list.

    To select the whole query, click anywhere in query Design view outside the design grid and the field lists.

  3. Click the Properties button [image] on the toolbar.

  4. In the Orientation property box, do one of the following:

    For a right-to-left direction, click Right-to-Left.

    For a left-to-right direction, click English.

Note Direction in queries is configurable only for queries in a Microsoft Access database (.mdb). Direction in queries in a Microsoft Access project (.adp) is always left-to-right.


 Use right-to-left features in forms and reports

Use right-to-left features in forms and reports

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

What do you want to do?

Learn about right-to-left behavior in forms and reports

Learn about right-to-left features hierarchy

Learn how labels are attached to controls

See examples of printing orders

Set right-to-left properties in controls


 About right-to-left behavior in forms and reports

About right-to-left behavior in forms and reports

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

Right-to-left characteristics for forms and reports are summarized as follows:

Default direction

The default direction that was set on the Right-To-Left tab in the Options dialog box (Tools menu) determines whether your form has a left-to-right or right-to-left layout. If you have not changed the default, new controls added to the form are displayed with a right-to-left direction.

Ruler and grid

Whether a form or report is in a right-to-left or left-to-right direction, the ruler retains its origin in the upper-left corner of the design window. The same concept applies to the grid. This provision does not cause any problems when creating a right-to-left-oriented form. By dragging the right grid boundary to the right, controls on the grid move to the right in proportion to the distance the boundary is moved and the grid is extended from the left boundary.

Set control defaults

The Set Control Defaults command on the Format menu recognizes all right-to-left properties in Microsoft Access 2000. When you select this command, Access applies all right-to-left properties.

Change To

When you change a control's type (for example, from a text box to a list box) by using the Change To command, Access transfers any relevant right-to-left properties from the original control to the new one.

Snap To Grid and Align To Grid

These Format menu commands behave according to the direction of the current form or report.

Snap To Grid When you place a new control on a left-to-right form or report, the upper-left corner of the control is aligned to the nearest point on the grid. When you place a new control on a right-to-left form or report, the upper-right corner aligns to the nearest point.

Align To Grid In a left-to-right form or report, the upper-left corners of selected controls align to the nearest point in the grid. In a right-to-left form or report, upper-right corners of selected controls align to the nearest grid point.

Form Datasheet view

Datasheet view in forms is the way to present tables with the most sophisticated right-to-left behavior. In addition to displaying the underlying data in the column and row layout generally associated with tables, each field in Datasheet view has the right-to-left properties of the associated Form view control.

For example, if you set the KeyboardLanguage property to Arabic for a text box control bound to a Text field named Company, then the keyboard language will automatically switch to Arabic whenever you click in the Company field in Datasheet view. This feature is useful for volume data-entry applications because it reduces the need to make keyboard language changes when moving from one field to the next.

Form and report Design view

A hierarchy of control governs the orientation, overall appearance, and basic parameters of forms and reports.

Print Preview and Layout Preview in reports

Microsoft Access 2000 displays the report in the direction in which it was designed, left-to-right or right-to-left.


 Examples of printing orders

Examples of printing orders

Language-specific information

You can view and print your data in the direction, right-to-left or left-to-right, that you assigned to the object.

Objects that are longer or wider than can be printed on a single sheet of paper are printed on multiple sheets in an order that is determined by the view direction of the object. The following example shows the page numbering and printing order for a report that is three pages wide and requires six pages to print.

Object direction | Multiple page printing order
Left-to-Right | Left to right printing order
Right-to-Left | Right to left printing order

Note Reports and labels can be printed on a page in a multiple-column format. The layout of the columns will be determined by the direction of the report.

More information

Select printing options


 Use right-to-left features in data access pages

Use right-to-left features in data access pages

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

What do you want to do?

Learn about right-to-left features in data access pages

Set the direction for new tables, queries, forms, reports, and data access pages

Specify the direction of a data access page

Specify the direction of a control on a data access page


 About right-to-left features in data access pages

About right-to-left features in data access pages

Language-specific information

Right-to-left features in data access pages are set according to a two-level hierarchy: page level and control level.

Page level

Initially, a new data access page will be displayed in the direction, either left-to-right or right-to-left, that is selected under Default direction on the Right-to-Left tab in the Options dialog box (Tools menu). That direction appears as a setting of the Dir property of the data access page.

Note Data access page direction is included in the underlying HTML code of the data access page through use of the standard HTML Direction (DIR) attribute. For example, the code <HTML DIR=RTL> placed at the beginning of the <HTML> element identifies a right-to-left data access page.

Controls placed on a data access page inherit the directionality of the data access page itself, depending on whether the control has right-to-left features. Controls without right-to-left features are displayed in a left-to-right direction.

Control level

Controls with right-to-left features initially appear on a data access page according to the direction of the data access page. After you place a control on a data access page, you might be able to change the control display direction to give it right-to-left appearance and functionality. The property name that controls display direction varies with control type. The properties in the following table control directionality for data access page controls:

Control type | Description
Office Web Component controls | The Office Web Component controls are the spreadsheet, the chart, and the PivotTable list. The direction setting property is RightToLeft. Note Office Web Component controls each have a property toolbox that can be used both while designing the control and in the browser; however the right-to-left setting can't be changed in the browser.
Intrinsic browser controls | Examples of intrinsic browser controls include Table, Label, TextBox, ComboBox, ListBox, OptionGroup, and ScrollingText. The direction setting property is typically Dir.
ActiveX controls | These are other controls that are available with Microsoft Office 2000 programs or Microsoft Visual Basic. The direction setting property is typically RightToLeft.


 Specify the direction of a data access page

Specify the direction of a data access page

Language-specific information

  • Do one of the following:

    Before creating a new data access page, set the direction, either left-to-right or right-to-left, under Default direction on the Right-to-Left tab in the Options dialog box (Tools menu). That direction will appear as the setting of the Dir property of the new data access page.

    For an existing data access page:

    1. From the Database window, open the data access page in Design view.

    2. Select the page by clicking the page title bar.

    3. Click Properties [image] on the toolbar, click the All tab, and change the Dir property setting to the page direction you want: Right-to-left or Left-to-right.

    Tip To edit directly in HTML, click HTML Source from the View menu and modify the <HTML> element to <HTML DIR=RTL> for a right-to-left page direction or <HTML DIR=LTR> for a left-to-right page direction.


 About code page and text layout support for right-to-left HTML files

About code page and text layout support for right-to-left HTML files

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

Right-to-left enabled Access 2000 supports several code pages used in importing, saving, and exporting HTML Web pages.

Code page conversion of tables/worksheets with right-to-left characteristics is provided for HTML files stored in logical text layout and one of the following right-to-left code pages:

Language | Code page
Arabic | UTF-8 (default)
 | ISO 8859-6
 | DOS-720
 | ASMO-708
Hebrew | UTF-8 (default)
 | ISO 8859-8
 | DOS-862

Note Microsoft Access 2000 supports editing and saving of HTML files in logical text layout. HTML files stored in visual text layout can be viewed but not edited or saved in logical text layout.

More information

Import HTML tables and lists

Export a table, query, form, or report to HTML format


 About the Arabic code page

About the Arabic code page

Language-specific information

Each code page is identified by a unique code page number. The code page (CP) for Arabic is CP 1256.

Note Microsoft Access 2000 sorts right-to-left databases by using values from Unicode, not those from the right-to-left code page as in earlier versions. Opened or imported databases that use the Arabic code page and Arabic sort order will be converted to Unicode and General sort order.

Arabic code page


 About the Hebrew code page

About the Hebrew code page

Language-specific information

Each code page is identified by a unique code page number. The code page (CP) for Hebrew is CP 1255.

Note Microsoft Access 2000 sorts right-to-left databases using values from Unicode, not those from the right-to-left code page as in earlier versions. Opened or imported databases that use the Hebrew code page and Hebrew sort order will be converted to Unicode and General sort order.

Hebrew code page


 Specify text alignment in a text box or other control

Specify text alignment in a text box or other control

Language-specific information

You can select the type of text alignment you want in a label, text box, combo box, or list box.

  1. Open a form or report in Design view.

  2. Make sure the control is selected, and then click Properties [image] on the toolbar.

  3. On the All tab, in the TextAlign box, click one of the following:

    To have text alignment follow the language of the text first entered or the user interface language, click General.

    To have alignment fixed, click one of the other choices.

Notes

  • CTRL+LEFT SHIFT and CTRL+RIGHT SHIFT shortcut keys used to dynamically change reading order and alignment in other bidirectional programs will temporarily change reading order only (alignment is excluded because changing alignment might negatively affect appearance). When the focus leaves the control, the display format reverts to the chosen control reading order.

  • Learn about right-to-left properties.


 Summary of right-to-left properties for controls

Summary of right-to-left properties for controls

Language-specific information

Most intrinsic Microsoft Access 2000 controls can be configured to present right-to-left appearance and behavior. In some cases, this can be done by using standard Microsoft Access control properties (for example, the TextAlign property) and repositioning of controls to achieve a right-to-left appearance.

However, in some cases right-to-left properties are needed to achieve proper right-to-left appearance and behavior. The following tables lists those controls for which new right-to-left properties are added:

 | Label | Text box | Toggle button | Combo box | List box | Command button
TextAlign | X | X |  | X | X |
ReadingOrder | X | X | X | X | X | X
KeyboardLanguage |  | X |  | X |  |
ScrollBarAlign |  | X |  | X | X |
NumeralShapes | X | X |  | X | X |


 Set right-to-left properties in controls

Set right-to-left properties in controls

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

What do you want to do?

Learn about right-to-left properties

Specify text reading order for a text box or other control

Specify the initial keyboard language in a text box or combo box

Specify text alignment in a text box or other control

Specify where you want scroll bars in a text box or other control

Specify the appearance of numbers (Arabic only) in a text box or other control

See a summary of right-to-left properties for controls

Learn about bidirectional properties of the user interface


 How labels are attached to controls

How labels are attached to controls

Language-specific information

Labels are automatically created and attached to most controls. Label placement is determined by the Orientation property setting for the parent form at the time you create the label. If the Orientation property is set to right-to-left, the label is placed to the right of the control. If the Orientation property is set to left-to-right, the label is placed to the left of the control.

Properties for a label attached to a control, except TextAlign, are inherited from default label control properties. TextAlign for an attached label is inherited from the LabelAlign property in the parent control (for example, text box, option group, toggle button, option button, check box, combo box, list box, subform/subreport, bound object frame, or command button). LabelAlign, which specifies the alignment of text within a label, exists only as a parent property until the control is created. Thereafter, it is available as TextAlign in the label control attached to the parent control.


 Set insertion point behavior

Set insertion point behavior

Language-specific information

  1. Click Options on the Tools menu, and then click the Right-to-Left tab.

  2. Do one of the following in the Cursor option group:

    Click Logical to have insertion point movement according to the logical order of mixed text.

    Click Visual to have insertion point movement that ignores text language and moves contiguously to the right or left.


 Specify text reading order for a text box or other control

Specify text reading order for a text box or other control

Language-specific information

You can select the type of reading order you want in a label, text box, toggle button, combo box, list box, or command button. Learn about the ReadingOrder property.

  1. Open a form or report in Design view.

  2. Make sure the control is selected, and then click Properties [image] on the toolbar.

  3. On the All tab, in the ReadingOrder box, do one of the following:

    To have the reading order follow the language of the text first entered, click Context.

    To force the reading order in one direction, click Right-To-Left or Left-To-Right.

Note CTRL+LEFT SHIFT and CTRL+RIGHT SHIFT shortcut keys used to dynamically change reading order and alignment in other bidirectional programs will temporarily change reading order only (alignment is excluded because changing alignment might negatively affect appearance). When the focus is moved outside the control, the display format reverts to the chosen control reading order.


 Specify the appearance of numbers (Arabic only) in a text box or other control

Specify the appearance of numbers (Arabic only) in a text box or other control

Language-specific information

You can select the appearance of numbers in a label, text box, combo box, or list box.

  1. Open a form or report in Design view.

  2. Make sure the control is selected, and then click Properties [image] on the toolbar.

  3. On the All tab, in the NumeralShapes box, do one of the following:

    For numerals formatted according to Unicode rules for adjacent text, click Context. In general, this means numeral shapes are Hindi if surrounding text is Arabic.

    For numerals formatted according to the Numeral Shapes option (set by double-clicking Regional Settings in Windows Control Panel), click System.

    For numerals in Arabic, click Arabic.

    For numerals in Hindi, click Hindi.

Note Learn about right-to-left properties.


 Specify the direction of a control on a data access page

Specify the direction of a control on a data access page

Language-specific information

  1. From the Database window, open the data access page in Design view.

  2. Make sure the control is selected, and then click Properties [image] on the toolbar.

  3. On the All tab, find the right-to-left property associated with the control (such as Dir).

  4. Do one of the following:

    Click Right-to-left (or the equivalent setting) to display the control with a right-to-left direction.

    Click Left-to-right (or the equivalent setting) to display the control with a left-to-right direction.


Specify where you want scroll bars in a text box or other control

Language-specific information

You can select the position of scroll bars you want in a text box, combo box, or list box.

  1. Open a form or report in Design view.

  2. Make sure the control is selected, and then click Properties [image] on the toolbar.

  3. On the All tab, in the ScrollBarAlign box, do one of the following:

    To have the scroll bar follow the setting of the Orientation property for the form or report that contains the control, click System. (A vertical scroll bar is placed on the left if the form or report Orientation property setting is Right-to-left; and on the right if the form or report Orientation property setting is Left-to-right.)

    To have a scroll bar on the right side of the control, click Right.

    To have a scroll bar on the left side of the control, click Left.

Note Learn about right-to-left properties.


 Use database calendars

Use database calendars

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

Any version of Access 2000 that supports right-to-left text (except Hebrew) also supports the use of the Gregorian (default) and Hijri calendar for date entry and display.

What do you want to do?

Learn about using different calendars

Switch between Gregorian and Hijri calendars


 About using different calendars

About using different calendars

Language-specific information

If you open an existing database with date references and you have selected the wrong calendar setting, the program might report a variety of errors or other unexpected behaviors. For example, if you have checked the Hijri Calendar setting, Microsoft Access 2000 will display a syntax error message if a report makes reference to Gregorian dates that are invalid as Hijri dates (for example, the date 12/31/99 will produce a syntax error because no Hijri month has 31 days).

To avoid problems of this sort, all date references in a database must be based on the same calendar.

Important It is recommended that you choose the database calendar when you first create your database, and then never change it.

Other considerations when the database calendar is set to Hijri

  • To ensure Hijri dates strings are evaluated correctly in expressions and Visual Basic for Applications statements, use the CDate function to evaluate the strings instead of declaring the strings as constants.

    For example, type CDate("1/25/20") instead of #1/25/20#.

    The CDate function will always return a value based on the active database calendar, whereas date constants are always evaluated by using the Gregorian calendar.

  • For reliable behavior, enter and display dates in an unambiguous format. For example, dates in short date format might be misinterpreted in queries if the year or the day of the month are 12 or less (for example, 3/11/10). Dates in medium date format display only the first few characters of the month name, which can create ambiguity or an undesirable appearance. Use long date format whenever possible. You can alter the way a date is displayed in long format (for example, excluding the day of the month) by using Regional Settings in Windows Control Panel.

  • Dates entered in the ValidationRule property of a Date/Time field in a table (in table Design view) must be Hijri. However, to have the ValidationRule date appear as a Hijri date in validation messages, the validation rule must use the CDate function (for example, 'CDate ("1/25/1420")'.

  • Sample Access 2000 applications, such as the Northwind database, are not localized and expect the database calendar to be Gregorian. Because the sample applications contain hard-coded date constants that are not valid Hijri dates, running the sample applications with the database calendar set to Hijri is not recommended.

  • All Hijri years will be displayed as four-digit year values (for example, 1420) unless the Format() function is explicitly used.

  • The Visual Basic Date function, used to set the system date for your computer, will not accept Hijri dates. If the database calendar is set to Hijri, set the calendar to Gregorian before setting system date with the Date function.

  • Dates in tables exported as text files are always stored as Gregorian values. If the database calendar is set to Hijri, automatic Hijri to Gregorian conversion is performed during the export process. Similarly, dates in tables imported from text files are assumed to be Gregorian dates and will be converted to Hijri values during the import process if the database calendar setting is Hijri.

  • You can't set the database calendar programmatically by using Visual Basic for Applications.

More information

Import, export, and link right-to-left tables in text formats


Switch between Gregorian and Hijri calendars

Language-specific information

  1. On the Tools menu, click Startup.

  2. Click Advanced.

  3. Select the Hijri Calendar check box.

The setting is saved with the database and used for all date references in the database.


 Use right-to-left sort orders

Use right-to-left sort orders

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

The default Microsoft Access 2000 sort order, General, handles sorting of right-to-left characters; that is, there are no separate sort orders for right-to-left languages. General sort order now includes right-to-left characters because characters are stored as Unicode values. The behavior of General sort order for right-to-left characters stored as Unicode values is identical to the behavior of right-to-left characters previously stored as Arabic or Hebrew code page values and sorted by using Arabic sort order and Hebrew sort order, respectively.

Right-to-left text is sorted along the following guidelines:

  • Left-to-right text is always sorted ahead of right-to-left text.

  • Sort ignores kashidas and bidirectional control characters.

  • Characters with diacritics are clustered after other occurrences of the base character.

Note When opened or imported, previous-version databases that use a right-to-left sort order are saved with the Access 2000 General sort order.

What do you want to do?

Learn about Arabic sort order

Learn about Arabic code page

Learn about Hebrew sort order

Learn about Hebrew code page


 About Arabic sort order

About Arabic sort order

Language-specific information

Arabic sort order is described here by using the Arabic code page, not Unicode, because the former is more familiar to most users. The Arabic sort order table arranges the characters of the Arabic code page into a sort order. The sort order controls how data is sequentially ordered in Microsoft Access databases that use the Arabic code page.

Note Microsoft Access 2000 sorts right-to-left databases by using values from Unicode, not those from the right-to-left code page as in earlier versions. Opened or imported databases that use the Arabic code page and Arabic sort order will be converted to Unicode and General sort order.

The 256 characters of the Arabic code page can be organized into several categories that determine how characters are sorted.

  • Kashida and bidirectional control characters (hexadecimal code points 9D, 9E, DC, FD, and FE):

    Sort ignores these characters.

  • Arabic diacritics (hexadecimal code points F0 through F3, F5, F6, F8, and FA):

    Sort ignores Arabic diacritics except when the strings being compared are otherwise identical. In this case, unmarked characters (without diacritics) sort ahead of marked characters (with diacritics); diacritics with lower code point values sort ahead of others.

  • General control characters (hexadecimal code points 00 through 1F and 7F), reserved characters (hexadecimal code points 80, 81, 8D, 8E, 8F, and 90), and punctuation:

    These three categories sort ahead of alphanumeric characters in category order (that is, General control characters first) and in ascending code point order within each category (for example, 00 sorts ahead of 01).

  • Arabic and left-to-right alphanumeric characters (shown in the Arabic sort order table that follows):

    Left-to-right text is always sorted ahead of Arabic text.

    Left-to-right text sorting is not case sensitive. For example, although uppercase "A" is listed before lowercase "a" in the sort table, Access 2000 treats these characters equally and does not provide any sorting preference to either character.

    Unmarked left-to-right text (without diacritics) is sorted before marked left-to-right text.

The following table lists the alphanumeric characters of the Arabic code page along with their respective hexadecimal code points. Characters (Char) are arranged in columns according to their sort order, starting in the upper-left corner.

Arabic sort order


 About Hebrew sort order

About Hebrew sort order

Language-specific information

Hebrew sort order is described here by using the Hebrew code page, not Unicode, because the former is more familiar to most users. The Hebrew sort order table arranges the characters of the Hebrew code page into a sort order. The sort order controls how data is sequentially ordered in Microsoft Access databases that use the Hebrew code page.

Note Microsoft Access 2000 sorts right-to-left databases by using values from Unicode, not those from the right-to-left code page as in earlier versions. Opened or imported databases that use the Hebrew code page and Hebrew sort order will be converted to Unicode and General sort order.

The 256 characters of the Hebrew code page can be organized into several categories that determine how characters are sorted.

  • Bidirectional control characters (hexadecimal code points FD and FE):

    Sort ignores these characters.

  • Hebrew diacritics (hexadecimal code points C0 through CD, D1, and D2):

    Sort ignores Hebrew diacritics except when the strings being compared are otherwise identical. In this case, unmarked characters (without diacritics) sort ahead of marked characters (with diacritics); diacritics with lower code point values sort ahead of others.

  • General control characters (hexadecimal code points 00 through 1F and 7F), reserved characters (hexadecimal code points 80, 81, 8A, 8C through 90, 9A, 9C through 9F, CE through D0, D3 through DF, FB, FC, and FF), and punctuation:

    These three categories sort ahead of alphanumeric characters in category order (that is, General control characters first) and in ascending code point order within each category (for example, 00 sorts ahead of 01).

  • Hebrew and left-to-right alphanumeric characters (shown in the Hebrew sort order table that follows):

    Left-to-right text is always sorted ahead of Hebrew text.

    Left-to-right text sorting is not case sensitive. For example, although uppercase "A" is listed before lowercase "a" in the table on the following page, Hebrew Access treats these characters equally and does not provide any sorting preference to either character.

    Unmarked left-to-right text (without diacritics) is sorted before marked left-to-right text.

The following table lists the alphanumeric characters of the Hebrew code page along with their respective hexadecimal code points. Characters (Char) are arranged in columns according to their sort order, starting in the upper-left corner.

Hebrew sort order


 Convert bidirectional text files from ANSI

Convert bidirectional text files from ANSI

Language-specific information

The ConvText utility provides more support (additional code pages and visual text layout options) than is found in the Microsoft Access 2000 Import Text Wizard to convert bidirectional files from ANSI characters. ConvText is installed as part of Microsoft Access 2000.

  1. Export the Access object you want to convert to a non-ANSI code page.

  2. In the Program Files\Microsoft Office\Office folder, double-click the ConvText.exe icon.

  3. Click Convert From Windows ANSI Code Page.

  4. Type file names in the Source and Target boxes, or click Browse.

  5. Select the code page, text layout, file type, and file type parameters that match the target text file you are converting to.

  6. Click Load. You can also click Save to retain the conversion specifications.

  7. Click Convert.


 Convert bidirectional text files to ANSI

Convert bidirectional text files to ANSI

Language-specific information

The ConvText utility provides more support (additional code pages and visual text layout options) than is found in the Microsoft Access 2000 Import Text Wizard to convert bidirectional files to ANSI characters. ConvText is installed as part of Access 2000.

  1. In the Program Files\Microsoft Office\Office folder, double-click the ConvText.exe icon.

  2. Click Convert To Windows ANSI Code Page.

  3. Type file names in the Source and Target boxes, or click Browse.

  4. Select the code page, text layout, file type, and file type parameters that match the source text file you are converting.

  5. Click Load. You can also click Save to retain the conversion specifications.

  6. Click Convert.

  7. Import the converted text file into Access.

All field names and records from the original table/worksheet will be fully recreated in a new table.


 Convert reports saved as text files to ANSI characters

Convert reports saved as text files to ANSI characters

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

Reports exported as text files using the Save as/Export command (File menu) are saved as simple text files with fields in logical, not visual, order. You can use the resulting file with a number of different programs, but the file can be hard to read when it contains bidirectional text. Depending on the report complexity, a viewable version of the report can frequently be obtained by opening the file in Notepad and switching document reading order by using CTRL+LEFT SHIFT and CTRL+RIGHT SHIFT.

What do you want to do?

Convert bidirectional text files to ANSI characters

Convert bidirectional text files from ANSI characters


About Japanese sort order

Language-specific information

Japanese characters are sorted in the following order:

  • Hiragana and Katakana are sorted in the order of the kana syllabary.

  • English letters will be sorted alphabetically. No distinction is made between uppercase and lowercase letters.

  • Numbers are sorted in descending order.

  • No distinction is made between half-pitch and full-pitch English characters and symbols.

  • Other kanji, symbols, and so on, are sorted in the order of their Shift-JIS codes.

The order of the kana syllabary is as follows:

  • Long vowel sounds ( [image]) are treated as the vowel of the previous syllable. For example, " [image] [image] [image] [image] [image] [image] " is treated as " [image] [image] [image] [image] [image] [image] ".

  • Repetition marks (" [image] ") are treated as the same character as the character preceding the mark. For example, " [image] [image] [image] " is treated as " [image] [image] [image] ".

  • Voiced and unvoiced sounds are sorted in the following order: unvoiced sound, voiced-sound, semi-voiced sound.

  • No distinction is made between hiragana, full-pitch katakana, and half-pitch katakana.


 About a Microsoft Access project

About a Microsoft Access project

This topic provides reference information about:

What is a Microsoft Access Project?

Supported Microsoft SQL Server databases

Working with an Access project

Other questions

What is a Microsoft Access Project?

A Microsoft Access project (.adp) is a new type of Access file that provides efficient, native-mode access to a Microsoft SQL Server database through the OLE DB component architecture. Using an Access project, you can create a client/server application as easily as a file server application. This client/server application can be a traditional solution based on forms and reports, or a Web-based solution by using data access pages, or a combination of both.

a Microsoft Access project interacts with a Microsoft SQL Server database

An Access project is called a project because it contains only code-based or HTML-based database objects: forms, reports, data access pages, macros, and modules. These are the database objects that you use to create an application. Unlike a Microsoft Access database, an Access project does not contain any data or data definition based objects: tables, views, database diagrams, or stored procedures (which can also contain application code). Instead, these database objects are stored in the SQL Server database.

To create your application and access the data, you connect the Access project to the SQL Server database by using the New command on the File menu or by using the Database Wizard. Learn about creating an Access project.

Return to top

Supported Microsoft SQL Server databases

You can connect to one of the following SQL Server databases:

  • Microsoft SQL Server 7.0 on Microsoft Windows NT 4.0 or later (with Microsoft Windows NT Service Pack 4 or later) and Microsoft Windows 95 or later)

  • Microsoft Data Engine (MSDE) on Windows NT 4.0 or later and Windows 95 or later

  • SQL Server 6.5 on Windows NT 4.0 or later (with SQL Server Service Pack 5 or later)

Return to top

Working with an Access project

Working with an Access project is very similar to working with an Access database. The process of creating forms, reports, data access pages, macros, and modules is virtually the same as that used to create an Access database.

Once you connect to an SQL Server database, you can view, create, modify, and delete tables, views, stored procedures, and database diagrams by using the Microsoft SQL Server Design Tools, the same design tools that are used in Microsoft Visual Interdev and Microsoft Visual Basic. Although the user interface for working with these database objects is different from the equivalent database objects in Access database, it is just as user-friendly. An Access project also contains many of the same wizards as an Access database, such as the Form Wizard, the Report Wizard, and the Page Wizard, which you can use to quickly create a prototype or simple application.

Return to top

Other questions

About OLE DB and Data Links

About Microsoft Data Engine (MSDE)

Use the Upsizing Wizard

Optimize Microsoft Access project performance

Learn about Microsoft SQL Server documentation

Return to top


 About OLE DB and Data Links

About OLE DB and Data Links

Microsoft Access 2000 provides a native OLE DB user and programming interface that you can use to access a Microsoft Access database, a Microsoft SQL Server database, and other data sources. This topic provides reference information about:

Microsoft Access and the OLE DB architecture

Defining connection information

Creating and accessing Microsoft Data Link files

OLE DB provider installation

Programming OLE DB

Return to top

Microsoft Access and the OLE DB architecture

OLE DB is a component database architecture that implements efficient network and internet access to many types of data sources, including relational data, mail files, flat files, and spreadsheets. In the OLE DB architecture, the application that accesses the data is called a data consumer (for example, Microsoft Access 2000 or a Microsoft Visual Basic 6.0 program), and the program that enables native access to the data is called a database provider (for example, Microsoft OLE DB Provider for SQL Server or Microsoft Jet 4.0 OLE DB Provider).

Return to top

Defining connection information

A data link is the connection information that a data consumer uses to access a data source through the OLE DB provider of that data source. In the Microsoft Access user interface, you use the Data Link Properties dialog box to define a data link for an OLE DB provider in the following ways:

  • To connect to a Microsoft SQL Server database when you create a Microsoft Access project by using the New command on the File menu or by using the Database Wizard. Learn about creating an Access project.

  • To redefine the connection information for an Access project by using the Connection command on the File menu. You might do this to easily switch from a test to a production database or from a primary to a secondary server. Learn about modifying the connection to an Access project.

  • To redefine the connection information of an existing data access page in Page Design view by right-clicking on the field list and clicking Connection. When you first create a data access page, Microsoft Access automatically defines the connection information for you by connecting to the currently open Access database or project. Learn about modifying the connection to a page.

  • To connect a Web page that you opened from the Open dialog box (File menu, Open) from a null database window.

  • To create a PivotTable list or modify the connection to a PivotTable list.

Each OLE DB provider defines specific connection information. For example, Microsoft OLE DB Provider for SQL Server requires a server name, server location, and a user name, and you may want to define additional information, such as a password or whether or not you want to use Microsoft Windows NT integrated security.

In general, to define connection information in the Data Link Properties dialog box:

  • Click the Provider tab, select the OLE DB provider, and then click Next to display the Connection tab to enter specific connection information for that OLE DB provider. Note that depending on how you get to the Data Link Properties dialog box, the Provider tab may not be available. Access automatically defines the provider as the currently open Access database or SQL Server database connected to the open Access project.

  • Click the Advanced tab to provide additional information, such as network settings and access permissions.

  • Click the All tab to define initialization properties for that OLE DB provider.

The Data Link Properties dialog box Help file (msdasc.hlp) provides additional information on using the dialog box and defining connection information for each OLE DB provider.

Return to top

Creating and accessing Microsoft Data Link files

Although you typically connect to an OLE DB provider through Microsoft Access using the Data Link Properties dialog box, you may want to define connection information for an OLE DB provider in a Microsoft Data Link file (.udl) to use in a Visual Basic program and to organize and manage connection information on your computer.

To create connection information in this manner, open Microsoft Windows Explorer, choose Microsoft Data Link from the New menu, create a Microsoft Data Link file, select the file name, right-click on the file name, and then choose Properties.

Return to top

OLE DB provider installation

Microsoft Jet 4.0 OLE DB Provider and Microsoft OLE DB Provider for SQL Server are installed automatically when you install Microsoft Office 2000 or Microsoft Access 2000 standalone. Additional OLE DB providers are also installed, including OLE DB Provider for ODBC Drivers and OLE DB Provider for Oracle. To see a complete list of OLE DB providers installed on your computer, display the Data Link Properties dialog box from a Data Link file, and then click the Provider tab.

When you or other users display a page from Microsoft Internet Explorer 5 or later and you have a Microsoft Office 2000 license on your computer, if necessary, the page automatically downloads the necessary OLE DB providers and other related files by installing Microsoft Office Web Components.

Return to top

Programming OLE DB

You can also programmatically access data through an OLE DB provider in Visual Basic for Applications in Microsoft ActiveX Data Objects (ADO) by defining a connection string in the ConnectionString property of the Open method of the Connection object to pass the connection information to the OLE DB provider. For more information, see the The Microsoft Office 2000/Visual Basic Programmer's Guide.

Return to top


 About Microsoft Data Engine (MSDE)

About Microsoft Data Engine (MSDE)

This topic provides reference information about Microsoft Data Engine (MSDE):

What is MSDE?

When to use MSDE

Installing MSDE

More information

What is MSDE?

MSDE is a new technology that provides local data storage that is compatible with Microsoft SQL Server 7.0. You can also use MSDE as a remote data storage solution. Think of MSDE as a client/server data engine alternative to the file server Microsoft Jet database engine. MSDE runs under Microsoft Windows NT 4.0 or later and Windows 95 or later. It is designed and optimized for use on smaller computer systems, such as a single user computer or small workgroup server.

Because MSDE is based on the same data engine as SQL Server, most Microsoft Access projects or client/server applications run on either version unchanged. However unlike SQL Server 7.0, MSDE has a 2 gigabyte database size limit, doesn't support Symmetrical Multiprocessing (SMP) on Windows 95 or later, and when using Transactional replication, can't be a replication publisher (although it can act as a replication subscriber).

Return to top

When to use MSDE

Consider using MSDE as a desktop database alternative to a Microsoft Access database in the following ways:

  • As a small workgroup server database. You develop your applications by using an Access project connected to MSDE. You anticipate that your workgroup and its business requirements may grow over time until they eventually need the full functionality of SQL Server 7.0 running on a larger network server.

  • As a replication subscriber in an SQL Server replicated database environment. For example, you may have mobile users working remotely from the main office who access and update MSDE on laptops or disconnected computers, but then periodically connect to the Master SQL Server database to reconcile changes.

  • To easily develop and test an Access project or client/server application on a personal computer or workstation, and then modify the Access project connection information to connect to an SQL Server database on a remote server for final testing and production.

Return to top

Installing MSDE

Although MSDE is not part of Microsoft Office 2000 or Microsoft Access 2000 standalone Setup, you can install MSDE from the CD-ROM by running Setupsql.exe located in the \Sql\x86\Setup folder.

The Microsoft Office 2000 version of MSDE also contains additional help files that are located in the \Windows\Help folder, the SQL Server Enterprise Manager Help (entmgr.chm) and the Replication Wizard Help (replwiz.chm), that you can use with the SQL Server database utilities available from the Access Tools menu.

Once you install MSDE on your computer, on Microsoft Windows 95 or later, you may need to start the SQL Server Service Manager (double-click the MSSQLServer icon on the task bar and click Start/Continue). MSDE starts automatically on Windows NT 4.0 or later; you might want to automatically start MSDE on Windows 95 or later by selecting the Auto-Start service when OS starts check box on the SQL Server Service Manager window.

Return to top

More information

Create an Access project using the Database Wizard

Connect an Access project to an SQL Server database

Learn about replication in a Microsoft Access project

Learn about using Microsoft SQL Server database utilities from Microsoft Access

Learn about Microsoft SQL Server documentation

Return to top


 Optimize Microsoft Access project performance

Optimize Microsoft Access project performance

In a client/server application, the general rules of thumb for reducing network traffic and optimizing application performance are: Do your data processing work on the server, minimize roundtrips to the server to access the data, and limit the data you retrieve from the server. This topic provides reference information about:

Understanding OLE DB and the client/server environment

Processing data on the server

Limiting data retrieved from the server

Optimizing the Microsoft SQL Server database

Optimizing forms

Optimizing reports

More information

Understanding OLE DB and the client/server environment

A Microsoft Access project uses OLE DB to connect and communicate with an SQL Server database. Microsoft designed the OLE DB architecture to work efficiently in a client/server environment.

When you access data through a form or datasheet, OLE DB retrieves an updateable snapshot recordset from the SQL server database (up to the maximum record limit) and caches the data on the client — making one roundtrip to the server. Access retrieves the data asynchronously, which means that you can continue to interact with Access while the data is being loaded. When you work with the data on the form or datasheet, whether browsing, filtering, sorting, finding and updating data, you are working with the data that is cached on the client.

Return to top

Processing data on the server

To process data on the server, you can use stored procedures and triggers, and you can sort data on the server before retrieving it.

Stored procedures are a precompiled collection of one or more SQL statements and optional control-of-flow statements that can accept parameters and that are processed as a single unit by Microsoft SQL Server. A stored procedure resides in the SQL Server database. Because a stored procedure is compiled on the server when it is created, it executes faster than individual SQL statements. And because a stored procedure runs on the server, it takes advantage of the extra processing power of the server. Learn about working with stored procedures.

Triggers are a special kind of stored procedure that automatically execute when you update, insert, or delete data. Use triggers to enforce business rules and restrictions that are more complex than those defined with check constraints. Unlike check constraints, triggers can reference columns in other tables. For example, a trigger can roll back updates that attempt to apply a discount (stored in a discounts table) to books (stored in a titles table) with a price of less than $10. Learn about working with triggers.

Sort records on the server by using a stored procedure, or SQL statement stored in the RecordSource property of a form or report (which executes on the server). Sorting records on the server is another way to take advantage of the extra processing power of the server. Learn about ways to sort.

Return to top

Limiting data retrieved from the server

As much as possible, limit the amount of data your application retrieves from the SQL Server database. Use views, stored procedures, server filters, and SQL statement WHERE clauses to limit the data you or your users see in a form or datasheet to only what is needed. In general, avoid designing application scenarios where users browse the database in unrestricted fashion.

It's usually a good idea to use the maximum record limit button or the MaxRecords property to limit the data you or a user can see in a form or datasheet.

You can also use server filters to limit records before they are retrieved from the database on the server, and filters to further limit records on the client. Learn about creating filters. You can define a filter in the ServerFilter property of a form or report. You can also optimize the performance of lists of values in Server Filter by Form and Filter by Form windows by modifying the FilterLookup property to control the number of values displayed if the values are retrieved from either the server or client. Learn about optimizing filter performance.

Return to top

Optimizing the SQL Server database

The following are general guidelines for optimizing SQL Server database performance. For detailed information on improving SQL Server database performance, see the SQL Server documentation.

  • Design tables without redundant data. A well-designed database is a prerequisite for fast data retrieval and updates.

  • Enforce referential integrity, which preserves the defined relationships between tables when you add, update, or delete the rows in those tables by defining primary key and foreign key constraints in the related tables.

  • Choose an appropriate data type for fields. You can save space in your database and improve join operations. When defining a field, choose the smallest data type or field size that's appropriate for the data in the field.

  • Create indexes for fields that you sort, join, or set criteria for. You can make dramatic improvements in the speed of a query by indexing fields that are on both sides of joins, and fields that are used to set criteria for the query. Indexes, however, can slow down the speed of record insertions, updates, and deletes.

  • Add a timestamp field to your tables to improve performance of record deletions and updates, especially if your table contains many fields. SQL Server uses a timestamp field to indicate that a record was changed (not when it was changed) by creating a unique value field, and then updating this field whenever a record is updated. SQL Server uses the value in timestamp fields to determine whether a record has been changed before updating it. In general, a timestamp field provides the best performance and reliability, especially in a multiuser environment. Without a timestamp field, SQL Server must check all the fields in the record to determine if the record has changed, and this check can slow performance.

  • Periodically compact your SQL Server database to save disk space and reorganize indexes and data for faster access.

Return to top

Optimizing forms

In general when you design a form, determine the data and functionality needed, and delay asking the server for this data and functionality until the information is requested by the user. For example, create a form so that it doesn't require data to be retrieved from the server during the form-opening process. For example, you can add a command button to the form to load data on the form.

Display fields that take a long time to retrieve data from the server, such as text and image fields, only when requested. You can use the following techniques:

  • Place text and image fields on a subform that uses the same record source. Access only fetches the text or image values for the current record.

  • Display the most important fields on a main form, and provide a button labeled "More Information" that opens another form containing other fields. Base the second form on a query that is parameterized by the primary key field on the main form.

  • If your application is data-entry intensive, such as an order entry system, create a specific form for adding records that has the DataEntry property set to Yes. When you open the form to enter new data, Access doesn't display any existing records. This saves time because Access doesn't have to retrieve all the records from the server.

  • If a form or report is based on a parameterized stored procedure, use the Input Parameters property to supply the parameter values.

Use SQL UPDATE and DELETE statements with the appropriate WHERE clause to update or delete multiple records that meet the same criteria. This is more efficient than opening a recordset and performing the updates or deletions one record at a time.

Return to top

Optimizing reports

Instead of printing a long report, break up reports into smaller subsets of data, by using views, stored procedures, and SQL statements as your record source, or by using filters.

Use layout preview instead of print preview when you design your reports. You can take a quick look at the layout, which includes just a sample of the data in layout preview. When you are done working on the layout of the report, verify the data by opening the report in print preview.

You typically create and distribute reports on a schedule according to regular business cycles, such as weekly stock-level reminders, monthly sales reports, or quarterly financial statements. Create and distribute these reports as report snapshots in a batch file. Users can use the Snapshot Viewer to view and print the reports. When your users need up-to-the-minute reporting, use grouped data access pages.

Return to top

More information

Tips on optimizing performance in a data access page

Optimizing Visual Basic code performance

Return to top


 About Microsoft SQL Server documentation

About Microsoft SQL Server documentation

Microsoft Access documents in its Help and in The Microsoft Office 2000/Visual Basic Programmer's Guide how to use and program a Microsoft Access project that is connected to a Microsoft SQL Server database. You may need information about SQL Server to answer specific product questions you might have. The SQL Server documentation contains the following:

Item | Description
Books Online | Comprehensive documentation for SQL Server 7.0, including programming reference and Transact-SQL reference documentation, conceptual information about SQL Server, and general instructions for using SQL Server.
Transact-SQL Reference Help | Reference information about Transact-SQL syntax. Note This help information is also available from the Access Help Contents window.
SQL Server Error messages | Reference information about SQL Server error messages, numbers, and recovery actions. Note This help information is also available from the Access Help Contents window.
Enterprise Manager Help | Help information about administering an SQL Server database.
Replication wizard | Help information about configuring and managing replication.
Client Configuration Utility Help | Help information about managing SQL Server network connectivity options.
ODBC Driver Help | Help information about creating SQL Server ODBC data source definitions.
Profiler Help | Help information about capturing SQL Server events in a trace file for analysis and replay.
Query Analyzer Help | Help information about a graphical user interface that is used to interactively design and test Transact-SQL statements, batches, and scripts.
Data Transformation Services (DTS) Designer Help | Help information about importing, exporting, and transforming a variety of data sources.
SQL-DMO | Context-sensitive help information that is available from the development environment for SQL-DMO objects, properties and methods.
The Pubs Sample Database | The traditional SQL Server sample database.
The Northwind SQL Sample Database | A new sample database that contains the same Access Northwind sample database tables with specific SQL Server examples.


 About using a Microsoft Access project in a multiuser environment

About using a Microsoft Access project in a multiuser environment

There are several ways to share data in a Microsoft Access project (.adp) and several considerations to keep in mind when working in a multiuser environment. This topic provides reference information about:

Using Access projects in a multiuser environment

Handling concurrent updates

Sharing a Microsoft SQL database on the Internet

Replicating an SQL Server database

Using Access projects in a multiuser environment

In a multiuser environment, each user needs their own copy of the Access project file that is connected to the same Microsoft SQL Server database. You cannot share the same Access project file among two or more users.

When you open an Access project, it's always opened in exclusive mode. If another user has opened an Access project first, and you try to open the same Access project while that user still has it open, Access alerts you that the file is opened exclusively and gives you the option of opening a read-only copy.

In practice, when you are running a shared application, you simply provide a copy of the Access project file to each user of the application. In this case, each user has their own copy of forms, reports, data access pages, macros, and modules. But they are in fact sharing one SQL Server database and the tables, views, stored procedures, and database diagrams that reside in that database. Therefore, it's important in a multiuser environment to also provide adequate security on these shared database objects so their integrity is not compromised. Learn about protecting an Access project.

Return to top

Handling concurrent updates

In a multiuser environment, more than one person might be working with the same record at the same time. Because other people can change or even delete the same data that you're trying to edit, you might occasionally conflict with others as they work. An Access project uses a technique called optimistic record locking to handle record contention.

If you modify a record, and someone updates that record before you save it, Access displays a message box and warns you that if you save the record, you will overwrite the changes that the other user has made. You can do one of the following:

  • Press Save Record to save the record and overwrite the other user's changes.

  • Press Copy to Clipboard to first examine what the other user has entered as changes so that you can reconcile them with your current edits.

  • Press Drop Changes to ignore your changes and accept the other user's changes.

Because other users may add, modify, or delete records that you are accessing, you should periodically refresh the display of data in Datasheet or Form view by using the Refresh command (Records menu) to re-query and see up-to-date data.

Return to top

Sharing a Microsoft SQL database on the internet

You can create data access pages, or output one or more database objects to server-generated HTML or static HTML, display these Web pages in a browser, such as Microsoft Internet Explorer, and access data though these Web pages. Learn about the three types of Web pages Access creates.

Return to top

Replicating an SQL Server database

If you use two computers, such as an office computer and a portable computer, you can make replicas of your SQL Server database and keep those replicas synchronized. Many users at different locations can work on their own database copies of a Master database at the same time and then synchronize them over the network, either through a dial-up connection or the Internet. Learn about replication in an Access Project.

Return to top


 About updating data in a Microsoft Access project or data access page

About updating data in a Microsoft Access project or data access page

The way Microsoft Access updates data in a Microsoft Access project or data access page is different from the way they update data in a Microsoft Access database. Both users and programmers need to be aware of these differences. This topic provides reference information about:

General rules for updating data

Working with updatable snapshots

When updated field values are displayed

Recommended ways to update related data

General rules for updating data

The following rules apply when you are updating data from an Access project or page connected to either an Access database or Microsoft SQL Server database:

  • To update any field (including the primary key field) in a single table or base table of a join, you must have a unique field or combination of fields defined as a primary key constraint, a unique constraint, or any unique index on that table.

  • You can update data based on a one-to-many join in a form and page, but only for fields from the "many" side of the join. When you open a view or run a stored procedure that contains a join in Datasheet view, it is read-only, by default. However, you can update data from a form or page, even if it has a view or stored procedure as a record source, if you set the form or page's UniqueTable property (see discussion below).

  • To update a view or stored procedure, you must have UPDATE, INSERT and DELETE permission on the base table(s) referenced in the view or procedure, as well as SELECT permission on the view or EXECUTE permission on the procedure.

  • You cannot update data in a grouped page, only a non-grouped page.

  • You cannot update data derived from a self-join (such as all employees and the managers they report to) under any circumstances.

  • As is the case with an Access database:
    • You cannot update a form, datasheet, or page where the underlying SQL Statement of the record source contains a GROUP BY or COMPUTE clause.

    • You cannot update fields based on expressions (such as "price * quantity AS extended_price")

    • You cannot update a form, datasheet, or page based on a many-to-many join.

Return to top

Working with updatable snapshots

Access 2000 supports only inserting, deleting, and updating data in the row of a unique table (the "many" side of a join) in an updatable snapshot that has been created by a one-to-many join operation in a view, row-returning stored procedure, or SQL statement. Access 2000 doesn't allow you to update fields on the one side of the join.

A Form or page that is based on a one-to-many join must define the UniqueTable property in order for the recordset to be updatable. The unique table (also called the "most-many" table) is the "many" side of a one-to-many relationship. It is called a unique table because one record from the unique table corresponds to, at most, one record in the view, row-returning stored procedure, or SQL statement. For example, in a view that joins the Customers and Orders tables, Orders is the unique table because one record from the Orders table corresponds to, at most, one unique record in the view. By contrast, one record in the Customers table, can correspond to multiple records in the view.

Additionally, for a record source that is a stored procedure or SQL statement containing parameter markers, if you want to display the current values of a record after it is updated, you must also set the ResyncCommand property. Note that if you don't set the ResyncCommand property in these cases, the only consequence is that you won't see current values in a record after an update or insert. The update or insert will still happen correctly. For other types of record sources, Access displays current values even if the ResyncCommand property is not set.

In an updatable snapshot, you see only current values in an edited or newly inserted record after it has been successfully saved (See discussion below). For example, the Orders table contains an identity column as its primary key. When you insert into this table, the new OrderID value appears after you save the record or move to another record (which implicitly saves the record). Similarly, in a form based on a view joining Customers and Orders, if you update the OrderID field to a different CustomerID, the Address field will not show the address of the new customer until after the record has been saved.

Finally, all key fields or the UniqueTable must be in the SQL statement select list (although not necessarily visible). You must also select all NOT NULL columns that do not have server defaults defined, and supply values for these columns in the recordset except for fields with the Identity property set.

Return to top

When updated field values are displayed

In general, when you are updating fields in a form, datasheet, or page, Access can automatically insert a value for you, such as a default value, a calculated field, a timestamp value, an identity/AutoNumber field, or action performed by a trigger. However, unlike an Access database, the display of the value or effect of the operation occurs after you commit the record. This occurs because Access must update or perform the operation at the server first and then refresh the current display on the client.

Return to top

Recommended ways to update related data

The following are recommended ways to update related data:

  • AutoForm is a handy way to create a form that allows updating of a view or stored procedure based on a join. Use AutoForm to quickly create the form, then switch to design view to set the UniqueTable property. You can also set the DefaultView property if you prefer a Datasheet view to a single Form view.

  • To update all data in a one-to-many relationship, you can create a form/subform combination. For example, instead of displaying data on a single form that joins orders and customers (in this case, the customer fields would be read-only), you can create a form with customers and a subform with orders. Because a form/subform uses two different recordsets, you can update all fields. Additionally, you can display this form/subform combination as a datasheet with a subdatasheet.

  • In a page, you can simulate a form/subform combination by linking two pages using a hyperlink field, and then use Microsoft FrontPage to create two frames, one for each page.

Return to top


 Comparison of database objects between a Microsoft Access database and a Microsoft Access project

Comparison of database objects between a Microsoft Access database and a Microsoft Access project

The following table compares database objects between a Microsoft Access database and a Microsoft Access project.

Access database | Access project
Table | Table
Select Query | View
Action Query Parameterized Query | Stored procedure
Relationship | Database diagram
Form | Form
Report | Report
Data access page | Data access page
Macro | Macro
Module | Module

Note Tables, views, stored procedures, and database diagrams are physically stored in the Microsoft SQL database connected to the Access project. Learn about Access projects.


 Comparison of data types between a Microsoft Access database and a Microsoft Access project

Comparison of data types between a Microsoft Access database and a Microsoft Access project

The following table compares data types between a Microsoft Access database and a Microsoft Access project.

Learn about Access data types.

Learn about SQL Server data types.

Microsoft Access data type | SQL Server data type
Yes/No | bit
Number (Byte) | tinyint
Number (Integer) | smallint
Number (Long Integer) | int
Number (Single) | real
Number (Double) | float
Currency | money smallmoney
Decimal/numeric | decimal numeric
Date/Time | datetime smalldatetime
AutoNumber (Increment) | int (with Identity property defined)
Text (n) | varchar(n) nvarchar(n)
Memo | text
OLE Object | image
Replication ID (also called globally unique identifier (GUID)) | uniqueidentifier (SQL Server 7.0 only)
Hyperlink | ntext (but Hyperlink is not active)
(no equivalent) | nchar
(no equivalent) | varbinary
(no equivalent) | user-defined
(no equivalent) | smallint
(no equivalent) | timestamp
(no equivalent) | char nchar

Notes

  • In an Access project, the "n" prefix stands for "national" and means that the data type is unicode-enabled. In an Access database, all text columns are unicode-enabled by default.

  • The equivalent to an Access database AutoNumber data type in an Access project is the int data type defined with an Identity property. This data type contains system-generated sequential values that uniquely identify each row within a table (for example, employee identification numbers). When inserting values into a table with an Identity column, Access automatically generates the next field value based on the last used Identity value (set in the Identity Seed property) and the increment value (set in the Identity Increment property) that is specified when you create a column. To make this data type behave like the Autonumber data type, set the Identity Seed and Identity Increment properties to a value of 1.

  • Microsoft Access stores either a zero (0) or a minus one (-1) in the Access database Yes/No data type. An Access database interprets 0 as a 0, No, or False value, and interprets anything else as a –1, Yes, or True value. By contrast, SQL Server stores either a zero (0) or a plus one (+1) in the bit data type. An Access project interprets 0 as a False value, and interprets plus one (+1) as a True value.

  • Although the ntext data type does not store active hyperlinks, you can make a hyperlink active on a form in an Access project by binding a control to any text field and setting the IsHyperlink property to True.


 Comparison of delimiters, operators, constants, and wildcard characters between a Microsoft Access database and a Microsoft Access project

Comparison of delimiters, operators, constants, and wildcard characters between a Microsoft Access database and a Microsoft Access project

This table compares delimiters, operators, constants, and wildcard characters between a Microsoft Access database and a Microsoft Access project.

Description | Access database | Access project
Date delimiter | pound sign (#) | Single quotation mark (')
String delimiter | Matching single quotation marks (') or matching double quotation marks (") | Matching single quotation marks (')
Mod operator | mod | percent sign (%)
Concatenation operator | ampersand (&) | plus sign (+)
Wildcard character (Matches a single character.) | question mark (?) | Underscore (_)
Wildcard character (Matches zero or more characters.) | Asterisk (*) | Percent sign (%)
Constant | Yes | 1
Constant | On | 1
Constant | True | 1
Constant | No | 0
Constant | Off | 0
Constant | False | 0


 Comparison of Microsoft Access and SQL Server SQL syntax

Comparison of Microsoft Access and SQL Server SQL syntax

The following table summarizes important differences between the SQL syntax of Microsoft Access and Microsoft SQL Server, and illustrates how the Upsizing Wizard handles these differences. You can also use this reference information when you manually convert SQL syntax from a Microsoft Access database application to a Microsoft Access project application.

SQL syntax element Microsoft
Access 		Microsoft SQL
Server 		Upsizing Wizard
Identifiers Limit of 64 characters.

Allows keywords and special characters.

Can start with any character.

 SQL Server 6.5:
  • Limit of 30 characters.

  • Disallows keywords and special characters.

  • Must start with alphabetic character.

SQL Server 7.0 is fully compatible with Access identifiers.

 Converts as necessary to SQL Server names.
Output Fields | Allows multiple output fields with the same name. | Multiple output field names not supported in views. | Adds an alias for duplicate column names.
Date Delimiter | Pound sign (#) | Apostrophe (') | Converts delimiter.
Boolean Constants | True, False; On, Off; Yes, No | Integers: 1 (true), 0 (false) | Converts constant.
String Concatenation Ampersand (&) Plus sign (+) Converts character.

Note On SQL Server, ampersand (&) is used for bit-wise logical AND operations.
Wildcards Asterisk (*) matches zero or more characters.

Question mark (?) matches a single character.

Exclamation point (!) means not in list

Pound sign (#) means single digit.

 Percent sign (%) matches zero or more characters.

Underscore (_) matches a single character.

Up caret (^) means not in list.

No equivalent to the pound sign (#).

 Converts characters.

Converts pound sign (#) to [0-9] to match a single digit.
TOP Automatically includes ties, if there is an ORDER BY clause. SQL Server 6.5 does not support.

SQL Server 7.0 requires an explicit WITH TIES clause.

 For SQL Server 6.5, ignores all TOP queries.

For SQL Server 7.0, adds a WITH TIES clause to the end of all TOP queries that contain an ORDER BY clause.

CREATE INDEX Allows ascending and descending indexes.

Allows declaring primary, no nulls, and ignore nulls.

 Converts index.
DROP INDEX Syntax is:

Drop Index <index name> ON <table name>

 Syntax is:

Drop Index <table name>, <index name>

 Doesn't convert.
DISTINCTROW | Supported (allows selection of unique records). | Not supported. | Doesn't convert.
OWNERACCESS | Supported (controls permissions during execution). | Not supported. | Removes from SQL statement.
Table in UNION Supported (allows tables to be specified by using the syntax:

TABLE <tablename>

Not supported. Doesn't convert.
ORDER BY in Unions | Supported. Allows multiple order by clauses in union queries. | Supported Allows only one order by clause at the end of the statement. | Doesn't convert.
TRANSFORM | Supported. Used for cross tab queries | Not supported | Doesn't convert.
PARAMETERS | Supported (Recorded in SQL). | Not supported. | Removes explicit parameters from SQL string.


Comparison of functions between Visual Basic for Applications and Microsoft SQL Server Transact-SQL

The following table compares functions between Microsoft Visual Basic for Applications (VBA) and Microsoft SQL Server Transact-SQL. Note that the Upsizing Wizard converts the following VBA functions (which can occur in table validation rules, field validation, and defaults) to Transact-SQL functions. This topic provides reference information about:

String functions

Conversion functions

Date functions

Math functions

String functions

Visual Basic functions | Transact-SQL functions
asc(x) | ascii(x)
chr$(x) | char(x)
lcase$(x) | lower(x)
len(x) | datalength(x)
ltrim$( x) | ltrim(x)
mid$(x,y,z) | substring(x,y,z)
right$(x,y) | right(x,y)
rtrim$(x) | rtrim(x)
space$( x) | space(x)
str$(x) | str(x)
ucase$( x) | upper(x)

Return to top

Conversion functions

Visual Basic functions | Transact-SQL functions
ccur(x) | convert(money,x)
cdbl(x) | convert(float,x)
cint(x) | convert(smallint,x)
clng(x) | convert(int,x)
csng(x) | convert(real,x)
cstr(x) | convert(varchar,x)
cvdate(x) | convert(datetime,x)

Return to top

Date functions

Visual Basic functions | Transact-SQL functions
date(x ) | convert(datetime,convert(varchar,getdate(x)))
dateadd("<Access datepart>", x, y) | dateadd(<SQL Server datepart>, x, y)
datediff("<Access datepart>", x, y) | datediff(<SQL Server datepart>, x, y)
datepart("<Access datepart>", x) | datepart(<SQL Server datepart>, x)
day(x) | datepart(dd,x)
hour(x) | datepart(hh,x)
minute(x) | datepart(mi,x)
month(x) | datepart(mm,x)
now(x) | getdate(x)
second(x) | datepart(ss,x)
weekday(x) | datepart(dw,x)
year(x) | datepart(yy,x)

Return to top

Math functions

Visual Basic functions | Transact-SQL functions
int(x) | floor(x)
sgn(x) | sign(x)

Return to top


 When to upsize a Microsoft Access database to Microsoft SQL Server

When to upsize a Microsoft Access database to Microsoft SQL Server

Over time, most database applications grow, become more complex, and need to support more users. At some point in the life of your Microsoft Access database application, consider upsizing to Microsoft SQL Server to optimize database and application performance, scalability, security, reliability, recoverability, and availability. This topic provides reference information about the main reasons to upsize to an SQL Server database.

High performance and scalability

Increased availability

Improved security

Immediate recoverability

Reliable distributed data and transactions

Server-based processing

High performance and scalability

In many situations, Microsoft SQL Server offers better performance than an Access database. SQL Server also provides support for very large databases, up to one terabyte, which is much larger than the current limit for an Access database of two gigabytes. Finally, SQL Server works very efficiently on Microsoft Windows NT by processing queries in parallel (using multiple native threads within a single process to handle user requests) and minimizing additional memory requirements when more users are added.

Return to top

Increased availability

Using Microsoft SQL Server, you can do a dynamic backup, either incremental or complete, of the database while it's in use. Consequently, you do not have to force users to exit the database to back up data. This means your database can be running up to 24 hours a day, seven days a week.

Return to top

Improved security

Microsoft SQL Server can integrate with the Windows NT operating system security to provide a single log on to the network and the database. This makes it much easier for you to administer complex security schemes. An SQL Server database on a server is also better protected because unauthorized users can't get to the database file directly but must access the server first.

Return to top

Immediate recoverability

In case of system failure (such as an operating system crash or power outage), Microsoft SQL Server has an automatic recovery mechanism that recovers a database to the last state of consistency in a matter of minutes, with no database administrator intervention. Critical applications can be up and running again right away.

Return to top

Reliable distributed data and transactions

Transaction processing is a vital requirement for a system that is designed to support critical applications, such as banking and online order entry. Microsoft SQL Server supports atomic transactions with transaction logging, which guarantees that all changes performed within a transaction are either committed or rolled back.

Consistency and recoverability of a database transaction are guaranteed even in the case of system failure and in the middle of complex updates by more than one user. SQL Server treats all database changes inside a transaction as a single unit of work. By definition, either an entire transaction is completed safely and all resulting changes are reflected in the database, or the transaction is rolled back—and all changes to the database are undone.

Using a two-phase commit protocol, SQL Server can even support synchronized transactions that span more than one server—ensuring that all servers on the network are maintained in a consistent state.

Return to top

Server-based processing

Microsoft designed Microsoft SQL Server from the beginning as a client/server database. Data and indexes reside on a single server computer that is often accessed over the network by many client computers. SQL Server reduces network traffic by processing database queries on the server before sending results to the client. Thus, your client/server application can do processing where it's done best - on the server.

Your application can also use stored procedures and triggers to centralize and share application logic, business rules and policies, complex queries, and data validation and referential integrity code on the server, rather than on the client.

Return to top


 About upsizing a Microsoft Access database

About upsizing a Microsoft Access database

Upsizing is the process of migrating some or all database objects from a Microsoft Access database (.mdb) to a new or existing Microsoft SQL Server database or new Microsoft Access project (.adp). This topic provides reference information about:

Ways to upsize

The Upsizing Wizard report

Converting application code

Other questions

Ways to upsize

The Upsizing Wizard upsizes an Access database to a new or existing Microsoft SQL Server 6.5 and 7.0 database or new Access project by upsizing the data and data definitions, and migrating database objects. There are three ways to use the Upsizing Wizard:

  • Upsize only data or data definitions from an Access database to an SQL Server database.

  • Create an Access database front-end to an SQL Server database back-end so that you can create a front-end/back-end application.

  • Upsize all database objects from an Access database to an Access project so that you can create a client/server application.

Return to top

The Upsizing Wizard report

The Upsizing Wizard creates a report that provides a detailed description of all objects created, and reports any errors encountered during the process. The Upsizing Wizard automatically creates this report as a report snapshot with the same name as the Access database (for example, Northwind.snp), and stores it in the same folder.

The Upsizing Wizard report contains information about the following:

  • Database details, including database size, and transaction log and device names and sizes for an SQL Server 6.5 database.

  • Upsizing parameters, including what table attributes you chose to upsize and how you upsized.

  • Table information, including a comparison of Access and SQL Server values for names, data types, indexes, validation rules, defaults, triggers, and whether or not time stamps were added.

  • Any errors encountered, including database or transaction log full, inadequate permissions, device or database not created, table, default, or validation rule skipped, relationship not enforced, query skipped (because it cannot be translated to SQL Server syntax), and control and record source conversion errors in forms and reports.

Return to top

Converting application code

Designing and building an optimized client/server application is different from designing and building an optimized file server application. Therefore, you probably need to retrofit your application to take full advantage of SQL Server and an Access project. After you upsize, you need to manually convert code from Data Access Objects (DAO) to ActiveX Data Objects (ADO) in your modules, and convert queries that did not upsize (such as those that were nested too deeply). For more information on developing optimized client/server applications, see the Microsoft Office 2000/Visual Basic Programmer's Guide

Return to top

More information

Before you upsize a Microsoft Access database

Upsize your Microsoft Access database

Optimize Microsoft Access project performance

Return to top


 Before you upsize a Microsoft Access database

Before you upsize a Microsoft Access database

Before you upsize your Microsoft Access database to a Microsoft SQL Server database or Microsoft Access project, consider doing the following:

Backup your database Although the Upsizing Wizard doesn't remove any data or database objects from your Access database, it's a good idea to create a backup copy of your Access database before you upsize it.

Ensure you have adequate disk space You must have adequate disk space on the device that will contain the upsized SQL Server database. The Upsizing Wizard works best when there is plenty of disk space available.

If you have ample disk space on your server, multiply the size of your Access database by two and reserve that space on your disk. This ensures that the Upsizing Wizard has enough space to upsize your database and also leave it some room to grow. If you expect to add a lot of data to the database, make the multiple larger.

Caution If the Upsizing Wizard runs out of disk space on the server, the wizard halts, leaving a partial database and any devices it created on the server. If this happens, you can drop (delete) devices, databases, and tables using Microsoft SQL Server Enterprise Manager.

If desired, create multiple disk devices If you are upsizing to an SQL Server 6.5 database, you may want to create devices before running the Upsizing Wizard. The Upsizing Wizard creates all new devices on the same physical disk where the Master database device resides. If your server has multiple disks, you can place your database on one disk and the transaction log on a different disk. In the event of a disk failure, you can recover your database. Make sure that you have devices that are big enough on both disks. Create new devices if necessary.

SQL Server also allows databases and transaction logs to span several devices. However, the Upsizing Wizard only allows you to specify one device for your database and one device for the transaction log. To specify multiple devices for a database or transaction log, make those devices (and no other devices) the default devices. Then run the Upsizing Wizard, and select the default database or transaction log device.

Note If the size of the new SQL Server database or the size of the transaction log doesn't require using all the devices set as default, SQL Server uses only the devices necessary to accommodate the database or transaction log.

Set a default printer You must set a default printer to use the Upsizing Wizard because it automatically creates a report snapshot of the Upsizing Wizard report.

Assign yourself appropriate permissions on the Access database You need read/design permission on all database objects to upsize them.

Assign yourself appropriate permissions on the SQL Server database

  • To upsize to an existing database, you need CREATE TABLE and CREATE DEFAULT permissions.

  • To build a new database, you need CREATE DATABASE permission, and SELECT permissions on the system tables in the Master database.

  • To create new devices, you must be a system administrator.

Adhere to SQL Server 6.5 naming rules from the beginning If you upsize to an SQL Server 6.5 database, the Upsizing Wizard converts illegal names for you by converting spaces and illegal characters to underscores (_). However, it's a good idea to adhere to SQL Server 6.5 naming rules from the beginning, if possible. SQL Server 6.5 names must be 30 characters or less. The first character must be a letter or the at sign (@). The remaining characters may be numbers, letters, the dollar sign ($), the number sign (#), or the underscore (_). No spaces are allowed.

Note SQL Server 7.0 database names are fully compatible with Access database names.


 Upsize your Microsoft Access database

Upsize your Microsoft Access database

  1. Open the Microsoft Access database you want to upsize.

  2. On the Tools menu, point to Database Utilities, and then click Upsizing Wizard.

  3. Follow the directions in the Upsizing Wizard dialog boxes, and then click Finish when you are done.

  4. If you need more information to decide what to do in each dialog box, click Help.

The Upsizing Wizard will run to completion after you click Finish; there are no additional prompts. Any messages are written to the Upsizing Wizard report. This is especially useful if you want to upsize a large database unattended. If you need to cancel the upsizing process, click Cancel on the status box that the Upsizing Wizard displays after you click Finish.


 Enter database and transaction log devices and sizes

Enter database and transaction log devices and sizes

If you choose to create a new Microsoft SQL Server 6.5 database, the Upsizing Wizard asks you to enter devices and sizes for your database and transaction log. It also asks you to enter a pre-allocated size for the database and transactions. This topic provides reference information about how to:

Enter a database device and size

Enter a transaction log device and size

Enter a database and transaction log size

Return to top

Enter a database device and size

All SQL Server databases and transaction logs are placed on devices. A device is both a logical location for databases and transaction logs and a physical file. When you create a device, SQL Server creates a file and reserves a set amount of disk space for its own use.

If you are a system administrator, the Upsizing Wizard displays the amount of free space available on the existing devices. Select a device that has at least enough free space for your estimated database size.

If no existing devices have enough free space, you can create a new device using the Upsizing Wizard. New devices should be at least as big as your estimated database size. If possible, make the device larger than your database size, so you can expand your database later, or place other databases or transaction logs on the same device.

Return to top

Enter a transaction log device and size

The transaction log is a chronological record of all activity that occurs on the server that SQL Server uses for database backup and recovery.

The transaction log device you select must have at least one megabyte of space available. Ideally, a database and its corresponding transaction log should be placed on devices that are on separate physical disks. These devices must be created before starting the Upsizing Wizard, because the Upsizing Wizard creates all new devices on the same physical disk where the Master database device resides.

If you have only one physical disk, you should place the database and its transaction log on separate devices, so you can recover the database.

The Upsizing Wizard creates the transaction log using the size you specify. The size of your transaction log should be at least as large as the size of all of the upsized tables in your database. The size you specify can't exceed the space available on the transaction log device you selected.

Note For new databases, the Upsizing Wizard truncates the transaction log file on checkpoint if it fills up before the upsizing is complete. However, it's possible for the transaction log to overflow on a single table. If this happens, Microsoft Access doesn't upsize the table and writes the error to the Upsizing Wizard report.

Return to top

Enter a database and transaction log size

When Microsoft SQL Server 6.5 creates a database, it sets aside a fixed amount of space for that database on one or more devices. Not all of this space is necessarily used by the database right away. The database size is the maximum size a database can become before it runs out of space.

To estimate the space needed for your database, look at the size of your Microsoft Access database and estimate the rate at which your new SQL Server database will grow. In general, every megabyte of Microsoft Access data requires at least 1.3 to 1.5 megabytes on SQL Server. Note that the size of a Microsoft Access database (.mdb) file includes all Microsoft Access database objects, not just data.

If you have ample disk space on your server, multiply the size of your Access database by two. This ensures that the Upsizing Wizard has enough space to upsize your database and also leave it some room to grow. If you expect to add a lot of data to the database, make the multiple larger.

The transaction log size should be about 25% of the database size.

Return to top


 Choose which tables to upsize

Choose which tables to upsize

You can select the Microsoft Access database tables you want to upsize to a Microsoft SQL Server database. This topic provides reference information about:

Linked tables

Aliasing queries

The effect of Declarative Referential Integrity (DRI)

Linked tables

The Available Tables list box includes all linked tables except for Microsoft SQL Server tables already in an SQL Server database. Linked tables that point to an SQL Server database that has been selected for upsizing, automatically appear in the Export to SQL Server list box and can't be removed. Any table that has a name ending in "_local" is excluded from the list of available tables to prevent upsizing tables that have already been upsized. If you do want to upsize these tables again, rename them before you run the Upsizing Wizard by removing the suffix "_local". Tables that are not currently visible in the database window are also excluded, including hidden tables and system tables.

Return to top

Aliasing queries

If you choose to link Microsoft SQL Server tables to your Access database, the Upsizing Wizard may create an aliasing query to handle name differences between Microsoft Access and Microsoft SQL Server 6.5, which doesn't allow spaces or special characters in field names other than pound sign (#), dollar sign ($), and underscore (_) characters. The Upsizing Wizard automatically replaces spaces and illegal characters with the "_" character. If field names are changed when a table is upsized, the Upsizing Wizard names the linked table with the suffix "_remote" (for example, Employees_remote) and renames the original table by adding the suffix "_local" (for example, Employees_local). The Upsizing Wizard then creates an aliasing query called Employees so that forms, reports, and queries continue to work properly on the new linked SQL Server table.

Return to top

The effect of Declarative Referential Integrity (DRI)

If you are upsizing to SQL Server version 6.5, and you selected Declarative Referential Integrity (DRI) to upsize tables previously, DRI prevents you from overwriting related tables that were previously upsized. You can drop (delete) an entire upsized SQL Server database by using SQL Server's Enterprise Manager, and then upsizing the Access database again. If you want to re-upsize only some tables, you must drop those tables and any other tables they are related to starting with the "many" table in a one-to-many relationship (a table that has no references to its primary key from another table) first, and then upsize the entire set of tables again. The Upsizing Wizard can only establish DRI relationships between related tables that are upsized at the same time, but it can't establish relationships between those tables and pre-existing tables on the server.

Return to top


 Choose which table attributes to upsize

Choose which table attributes to upsize

You can select which table attributes to upsize to your Microsoft SQL Server database. At a minimum, the Upsizing Wizard converts Access field names to legal SQL Server field names, and converts Access data types to the equivalent SQL Server data types. By default, all attributes are selected for upsizing. This topic provides reference information about what happens when you decide to:

Upsize indexes

Upsize validation rules

Upsize defaults

Upsize table relationships

Add timestamp fields to tables

Choose not to upsize data

Upsize indexes

If you select the Indexes check box, the Upsizing Wizard upsizes all indexes.

The Upsizing Wizard converts Microsoft Access primary keys to Microsoft SQL Server non-clustered, unique indexes and marks them as SQL Server primary keys. If you choose to link the upsized SQL Server table to your Access database, the Upsizing Wizard also adds the prefix "aaaaa." Microsoft Access chooses the index that is first alphabetically in the list of available indexes as the primary key and the "aaaaa" prefix ensures that the right index is chosen.

All other indexes retain their names, except where illegal characters are replaced with the "_" character. Unique and non-unique Microsoft Access indexes become unique and non-unique SQL Server indexes. Note that SQL Server doesn't support ascending or descending indexes.

A linked table must have a unique index to be updateable in Microsoft Access. The Upsizing Wizard can upsize an existing unique index, but can't create one where none exists. If you want to be able to update your tables, make sure you add a unique index to each Access table before upsizing.

Return to top

Upsize validation rules

If you select the Validation rules check box, the Upsizing Wizard upsizes all table, record, and field validation rules, and field Required properties as update and insert triggers.

A trigger is a series of Transact-SQL statements associated with an SQL Server table. A table can have three triggers, one for each of the commands that can modify data in a table: the UPDATE, INSERT, and DELETE commands. The trigger is automatically executed when the command is carried out. The Upsizing Wizard uses triggers rather than SQL Server rules to enforce field level validation because SQL Server rules do not allow you to display custom error messages.

Each validation rule doesn't necessarily have a one-to-one correspondence with a trigger. Each validation rule may become part of several triggers or each trigger may contain code to emulate the functionality of several validation rules.

When you set the Required property of a Microsoft Access field to true, a user cannot insert a record and leave the required field null (if there is no default bound to the field) or make the field null when updating a record. Required fields are upsized to fields that don't allow Null values on SQL Server. The Upsizing Wizard also creates a fragment of Transact-SQL code that presents a message similar to the one Microsoft Access displays if the field is null when a record is added or updated.

Return to top

Upsize defaults

If you select the Defaults check box, the Upsizing Wizard will upsize all default values as American National Standards Institute (ANSI) defaults, not as default objects bound to the appropriate SQL Server field. Microsoft SQL Server defaults, unlike Microsoft Access defaults, are independent of any particular field or table. Once you create a default, you can bind it to any number of different fields.

Return to top

Upsize table relationships

You can decide how to upsize table relationships and referential integrity by using either update, insert, or delete triggers, or Declared Referential Integrity (DRI).

DRI works the same way as Microsoft Access referential integrity by defining primary key constraints for base tables (the "one" side of a one-to-many relationship) and foreign key constraints for foreign tables (typically the "many" side of a one-to-many relationship). However, SQL Server DRI doesn't have the Microsoft Access cascading update or delete features.

  • Use triggers If your Microsoft Access table relationships have cascading updates or deletes defined, and you want to preserve this behavior in upsized tables, select the Table relationships and Use triggers check boxes, to upsize any cascading updates or deletes as triggers to enforce referential integrity.

    A table relation doesn't necessarily have a one-to-one correspondence with a trigger. Each relation may become part of several triggers or each trigger may contain code to emulate the functionality of several referential integrity rules. Insert triggers are used on child tables and delete triggers on parent tables.

    Note The Microsoft SQL Server Design Tool requires Declared Referential Integrity (DRI) to read the database diagram of an SQL Server database. To allow the SQL Server Design Tools to read the database diagram, while enforcing referential integrity through triggers, the Upsizing Wizard places DRI on the relationships but turns off checking of foreign key constraints.

  • Use DRI If your database doesn't have cascading updates or deletes defined. or you don't care if you lose these features in the upsized database, select the Table relationships and Use DRI check boxes, to use DRI to enforce referential integrity. In this case, the Upsizing Wizard warns you that you will lose the cascading update and delete functionality.

Return to top

Add timestamp fields to tables

Microsoft SQL Server uses a timestamp field to indicate that a record was changed (not when it was changed) by creating a unique value field, and then updating this field whenever a record is updated. For a linked table, Access uses the value in timestamp fields to determine whether a record has been changed before updating it. In general, a timestamp field provides the best performance and reliability. Without a timestamp field, SQL Server must check all the fields in the record to determine if the record has changed, which slows performance.

  • If you select the default value, Yes, let wizard decide, the Upsizing Wizard creates new fields with the timestamp data type in SQL Server tables that have been upsized from Microsoft Access tables that contain floating-point (Single or Double), Memo, or OLE object fields.

  • You can also choose to have the Upsizing Wizard create a timestamp field for all upsized tables regardless of what field types they contain by selecting Yes, always. This improves the performance of upsized Access tables that may not contain Memo, OLE Object, or floating-point fields, but have fields of other types.

Note In linked SQL Server tables, Microsoft Access doesn't check to determine if Memo or OLE object fields have changed because these fields could be many megabytes in size and the comparison could be too network-intensive and time-consuming. Therefore, if only a text or image field has changed and there is no timestamp field, Microsoft Access overwrites the change. Also, the value of a floating-point field may appear to have changed when it hasn't, so in the absence of a timestamp field, Microsoft Access may determine that the record has been changed when it has not.

Return to top

Choose not to upsize data

The Upsizing Wizard upsizes all data to SQL Server by default. If you select the Only create table structure, don't upsize any data check box, only the data structure is upsized.

Return to top


 Choose how to upsize your application

Choose how to upsize your application

You can select different ways to upsize your Microsoft Access database application. This topic provides reference information about each application changes option:

No application changes

Link SQL Server tables to existing application

Create new Access client/server application

Save password and user ID

No application changes

Select No application changes if you only want to upsize your data and not make any other changes to your existing Access database application.

Return to top

Link SQL Server tables to existing application

If you select Link SQL Server tables to existing application, the Upsizing Wizard can modify your Access database so that your queries, forms, reports, and data access pages use the data in the new Microsoft SQL Server database rather than the data in your Microsoft Access database.

The Upsizing Wizard renames the Microsoft Access tables you upsize with the suffix "_local." For example, if you upsize a table named Employees, the table is renamed Employees_local in your Access database. Then, the Upsizing wizard creates a linked SQL Server table named Employees.

Queries, forms, reports, and data access pages based on the original Employees tables will now use the linked SQL Server Employees table. Many of the properties of the fields in the original local table are inherited by the new local table including, Description, Caption, Format, InputMask, and DecimalPlaces. Learn about linked table properties.

Return to top

Create new Access client/server application

If you select Create new Access client/server application, the Upsizing Wizard creates a new Microsoft Access project. The Upsizing Wizard prompts you for a name, which defaults to the current Access database name, adds a "CS" suffix, and then stores it in the same location as the existing Access database.

The Upsizing Wizard creates the Access project file, displays the Data Link Properties dialog box so that you can connect to an SQL Server database, and then upsizes all the database objects from the Access database to the Access project:

  • Queries The Upsizing Wizard changes queries by converting them to either views or stored procedures and upsizing Access SQL syntax to use SQL Server SQL syntax. Select queries are converted to views. Sorted queries are converted to a combination of views and stored procedures to allow for nesting and sorting (Views can be nested but can't contain ORDER BY clauses; stored procedures can contain ORDER BY clauses but can't be nested). Parameterized queries, queries that depend on a parameterized query, and action queries are converted to stored procedures. You may need to manually convert queries that did not upsize (such as those that were nested too deeply). SQL Passthrough queries, data definition queries, and union queries are not upsized.

  • Forms, reports, and controls The Upsizing wizard modifies RecordSource, ControlsSource and RowSource properties by changing table, query, SQL statement, or field names to the equivalent SQL Server table, view, stored procedure, or field names.

  • Data access pages The Upsizing Wizard changes the OLE DB connection and the data binding information in the Microsoft Office data source control to work with the new SQL Server database, and copies the page's corresponding HTML file to the same location as the Access project, renaming the HTML file with a "_CS" suffix. The new pages in the Access project retain the original name, so that hyperlinks between the SQL Server Pages continue to work.

  • Macros and modules The Upsizing Wizard doesn't make any changes to these database objects. After you upsize, you need to manually convert code that uses recordsets from Data Access Objects (DAO) to ActiveX Data Objects (ADO) in your modules, and revise any table and query design code (The Upsizing Wizard does not upsize an SQL Data Definition Language). For more information on developing optimized client/server applications, see the Microsoft Office 2000/Visual Basic Programmer's Guide

Return to top

Save password and user ID

By default, the wizard creates linked tables in the existing application or creates an Access project without saving the username and password. This means that users are prompted for a username and password each time they log on to an SQL Server database.

If you select Save password and user ID, users can access an SQL Server database without logging in. If you select Create new Access client/server application, the Access project stores the username password in the OLE DB connection string.

Note This option is disabled for the No application changes option if a linked SQL Server table is configured with an MSysConf table to deny saving passwords.

Return to top


What's New for Microsoft Access 2000 Developers

Extensive changes have been made to the Microsoft Access 2000 Visual Basic object model to support new and improved features in the application. Many objects, properties, and methods have been replaced. To provide backward compatibility, most of the replaced components have been hidden rather than removed. This means that they don't show up in the Object Browser by default, but old code that uses the hidden components will still work correctly without modification. When you write new code, however, you should use the new objects, properties, and methods.

New Feature Areas

The following topics provide conceptual information about features that are new in Microsoft Access 2000.

Database window

Database Design

Data Access Pages

Forms and Reports

Internet Support

Macros

Microsoft Access Projects

Security

Visual Basic Editor

Viewing and editing Web Script

New Language Elements

The following topics provide lists of language elements that are new in Microsoft Access 2000.

New Objects

New Properties (Alphabetic List)

New Properties (by Object)

New Methods (Alphabetic List)

New Methods (by Object)

New Events

Language-Specific Properties and Methods

Hidden Language Elements

The following topics provide lists of language elements that have been hidden in Microsoft Access 2000.

Hidden Properties

New Features in Microsoft Access 97

The following topics provide information about developer features and language elements that were new in Microsoft Access 97.

New Properties

New Methods


 Events: Making your database objects work together

Events: Making your database objects work together

What is an event?

An event is a specific action that occurs on or with a certain object. Microsoft Access can respond to a variety of events: mouse clicks, changes in data, forms opening or closing, and many others. Events are usually the result of user action.

By using either an event procedure or a macro, you can add your own custom response to an event that occurs on a form, report, or control.

Suppose you want a Product Details form to open when you click a Product Details command button on an Orders form. The following examples show how to do this either by using an event procedure or by using a macro.

Responding to a Click event by using an event procedure

When you create an event procedure for an object, Access adds an event procedure template named for the event and the object to the form or report module. All you need to do is add code that responds in the way you want when the event occurs for the form or report.

Create a command button event

Place methods in event procedures to carry out actions

Responding to a Click event by using a macro

To have a macro run in response to an event, open the property sheet for the form, report, or control. Find the property that corresponds to the event, and set it to the macro you want to run.

Create a macro linked to an event

For a complete list of events, click [image] .

For information on running a macro or an event procedure from an event on a form, report, or control, click [image] .


 Save a database object by using a macro or event procedure

Save a database object by using a macro or event procedure

You can automate saving a database object by carrying out the Save action in a macro or an event procedure.

What do you want to do?

Save a database object by using a macro

Save a database object by using an event procedure


 Run a macro or event procedure for an event on a form, report, or control

Run a macro or event procedure for an event on a form, report, or control

Microsoft Access responds to many types of events on forms, reports, and controls, including mouse clicks, changes in data, and forms or reports being opened or closed.

  1. Open the form or report in Design view.

  2. Create a macro or an event procedure. For example, you can create a macro or event procedure that displays a message when you click a command button.

  3. Set the appropriate event property of the form, report, or control to the name of the macro, or to [Event Procedure] if you're using an event procedure.

    For example, to use a macro to display a message when you click a command button, set the command button's OnClick property to the name of a macro that displays the message. To use an event procedure, create a Click event procedure for the command button, and then set its OnClick property to [Event Procedure].

Notes

  • For information on creating a macro, click

  • For information on creating an event procedure, click [image] .

  • For information on when events occur, click [image] .


 Find out when events occur

Find out when events occur

A single action, such as moving from one control to another, can trigger several different events, which occur in a particular sequence. Knowing when events occur and in what order they occur is important because it can affect how and when your macros or event procedures run. For example, if you have two event procedures that are to be run in a certain order, you want to make sure that the events they're associated with occur in that order.

What do you want to do?

See the order of events for controls on forms

See the order of events for records on forms

See the order of events for forms and subforms

See the order of events for keystrokes and mouse clicks

See the order of events for reports and report sections

Note You can see the order in which events occur on a form by opening the ShowEvents form in the Orders sample application. When events occur on the ShowEvents form — for example, when you open the form or move to a new record — the EventHistory form lists the events in the order in which they occur. For information on opening Orders, click [image] .


 Events used for data validation

Events used for data validation

You typically use the following events to determine when Microsoft Access runs a validation macro or event procedure from a form.

Form event | Use for validation
BeforeUpdate | Before saving new or changed data in a record
OnDelete | Before deleting a record

Control event | Use for validation
BeforeUpdate | Before saving new or changed data in a control
OnExit | Before leaving a control


 Order of validation for controls and fields

Order of validation for controls and fields

Validation rules for controls and fields are evaluated in the following order:

  1. Macro or event procedure validation (for example, a macro or an event procedure that responds to the BeforeUpdate event of the control or the form containing the control)

  2. The control's ValidationRule property

  3. The underlying table's validation rules for the field (as set in the field's ValidationRule, Required, and AllowZeroLength properties)

  4. The underlying table's ValidationRule property (this property performs validation on records)


 Navigate between controls, records, and form pages

Navigate between controls, records, and form pages

You can automatically move to a control, record, or form page in response to an event that happens on a form by carrying out the GoToControl, GoToPage, or GoToRecord actions in a macro or an event procedure.

What do you want to do?

Navigate between controls, records, and form pages by using a macro

Navigate between controls, records, and form pages by using Visual Basic for Applications


 Find a record by selecting a value from a list

Find a record by selecting a value from a list

On a form, you can create a list box or a combo box that finds a record when you select a value from the list.

  1. Open the form in Design view.

  2. Click Control Wizards [image] in the toolbox if it's not already pressed in.

  3. In the toolbox, click List Box List Box control or click Combo Box .

  4. On the form, click where you want to place the list box or combo box.

  5. In the first wizard dialog box, click the option to find a record based on the value you selected in the list box or combo box.

  6. Follow the directions in the wizard dialog boxes. In the last dialog box, click Finish to display the list box or combo box in Design view.

If you want to see the event procedure that makes the list box or combo box work, open the box's property sheet, and then click the Build button [image] next to the AfterUpdate property box.


 Automatically view the latest records for a form

Automatically view the latest records for a form

You can automatically view the most current data for a form by refreshing and requerying the records.

If you're using a database that's shared on a network, you can view the latest version of existing records by creating a command button that updates form data.

To display the latest set of records in a form, including new records, you can requery the records by adding the Requery action to a macro or by adding the Requery method to a Visual Basic procedure.

What do you want to do?

Create a command button that updates form data

Automatically view the latest records for a form by using a macro

Automatically view the latest records for a form by using Visual Basic for Applications


 Display related records on a form when moving between records on another form

Display related records on a form when moving between records on another form

When you move between records on a form, you can display related records on a second form by running a macro or an event procedure in response to the first form's Current event.

What do you want to do?

Use a macro to display related records when you move between records on a form

Use Visual Basic for Applications to display related records when you move between records on a form


Example of using Visual Basic to display related records when you move between records

When you move between supplier records on a Suppliers form, you might want to see the products each supplier carries in a Products form. In the Form_Current event procedure of the Suppliers form, set the FilterOn and Filter properties of the Products form:

Private Sub Form_Current()

    ' Declare and set a variable to store the WHERE
    ' clause that describes the records you want to
    ' display.
    Dim strCond As String
    strCond = "SupplierID = Forms!Suppliers!SupplierID"

    ' Use the IsLoaded function from the Northwind
    ' sample database to check whether the Products
    ' form is open, then set the properties.
    If IsLoaded("Products") Then
        Forms![Products].FilterOn = True
        Forms![Products].Filter = strCond
    End If

End Sub


Synchronize records between two forms

You might often want to look at related records on two forms at the same time. For example, while looking at a customer record on a Customers form, you might want to open an Orders form that shows the customer's orders.

When you move between records on a form, you might also want to automatically view related records on a second form. For example, as you move between supplier records on a Suppliers form, you might want to see the products each supplier carries in a Products form.

You can synchronize records between two forms by creating a command button that opens and synchronizes a second form, or by using the Current event to display related records on the second form when you move between records on the first form.

Tip You can also use the Form Wizard to create two related forms from scratch. In the first screen of the wizard, select fields from two different tables. In the second screen, click Linked Forms. The wizard creates the two related forms; each form contains fields from one of the tables. One of the forms also has a command button that opens the other form and synchronizes the records between the forms.

What do you want to do?

Create a command button that opens and synchronizes a form

Display related records in one form when you move between records on another form


 Print a report from a form

Print a report from a form

You can automate how a user prints a report by carrying out the OpenReport and PrintOut actions in a macro or an event procedure. For example, you can make it possible for a user to print a report by clicking a button on a form, choosing a command from a custom menu, or pressing a key combination.

Use the OpenReport action if you want to restrict the records to be printed or if you want to open a report in Print Preview. When you use the OpenReport action to print a report, Microsoft Access prints the report by using the default settings in the Print dialog box.

Use the PrintOut action to set printing options before printing your report. The PrintOut action includes arguments for every option in the Print dialog box.

What do you want to do?

Create a command button that prints a report

Add the OpenReport or PrintOut action to a macro

Carry out the OpenReport or PrintOut action in a Visual Basic procedure

Read about the OpenReport action

Read about the PrintOut action


 Create a command button that prints the current record

Create a command button that prints the current record

  1. Open the form in Design view.

  2. Click Control Wizards [image] in the toolbox if it's not already pressed in.

  3. In the toolbox, click Command Button Command Button control .

  4. On the form, click where you want to place the command button.

  5. In the first wizard dialog box, click Record Operations in the Categories box, and then click Print Record in the Actions box.

  6. Follow the directions in the wizard dialog boxes. In the last dialog box, click Finish to display the command button in Design view.

If you want to see the event procedure that makes the button work, open the button's property sheet, and then click the Build button [image] next to the OnClick property box.

Tip You can print a form's current record in a report by carrying out the OpenReport action in the Click event procedure for a command button. For example, adding the following Visual Basic for Applications code to the Click event procedure for a command button on an Orders form prints the current record in the Invoice report:

Dim strDocName As String
Dim strFilter As String
strDocName = "Invoice"
strFilter = "OrderID = Forms!Orders!OrderID"
DoCmd.OpenReport DocName, acViewNormal, , strFilter


 About setting the value of a control or property in response to an event

About setting the value of a control or property in response to an event

By assigning new values to controls and properties in response to events that occur on a form or report, you can make the objects you've created work together so that they're easier to use.

Here are some common situations that call for setting values with a macro or an event procedure:

Setting the value of a control on one form equal to the value of a control on another form

For example, you can put a command button on a Customers form that opens an Orders form and automatically fills in billing information from the Customers form.

Open another form from a command button

Updating the value of a control that's dependent on the value of another control

For example, you might have a PaymentDate control whose default value is the ship date (the value of the ShipDate control). You can use a macro or an event procedure to automatically reset the value of the PaymentDate control whenever the value in the ShipDate control changes.

For more information about setting the value of a control based on the value of another control, click [image] .

Setting a form or control property in response to a selection or other event

You can use a macro or an event procedure to set a form or control property in order to:

  • Hide or display a control based on the value of another control. For example, you might want the DateDue control on an Orders form to be hidden if the order is already paid for (if the Paid control's value is Yes) or visible if payment is still due.

  • Disable or lock a control based on the value of another control. For example, you can disable a DriversLicense control if the value of an Age control is below the minimum age for a driver's license.

  • Display different sets of records depending on a selection. For example, you can control what records are displayed in a Customers form, depending on which option is selected in a Customer Type option group. To do this, set the RecordSource property of the form to one of several different queries, each of which contains the records for a different set of customers.

For more information about setting the value of a property in response to an event, click [image] .


 Set the value of a control based on the value of another control

Set the value of a control based on the value of another control

You can assign the value of a control based on the value of another control by adding a SetValue action to a macro or by using an assignment statement in a Visual Basic procedure.

What do you want to do?

Set the value of a control based on the value of another control by using a macro

Set the value of a control based on the value of another control by using Visual Basic for Applications


 Set the value of a property in response to an event

Set the value of a property in response to an event

You can assign the value of a property in response to an event, such as a click on a command button, by adding a SetValue action to a macro or by using an assignment statement in a Visual Basic procedure.

What do you want to do?

Set the value of a property in response to an event by using a macro

Set the value of a property in response to an event by using Visual Basic for Applications


 Example of setting the value of a property in response to an event

Example of setting the value of a property in response to an event

You can set the value of a property based on a value in the current record by running a macro or an event procedure in response to the form's Current event. For example, you might want the DateDue control on an Orders form to be hidden if the order is already paid for (if the value of the Paid control is Yes or True).

To run a macro, set the form's OnCurrent event property to the name of a macro that sets the DateDue control's Visible property to No if the value of the Paid control is Yes.

Set a value based on an event

To use an event procedure, add the following Visual Basic code to the Form_Current event procedure:

If Me![Paid] = True Then
    Me![DateDue].Visible = False
Else
    Me![DateDue].Visible = True
End If


 Display a message box

Display a message box

When you want to display a brief message, such as a warning, you can use a predefined dialog box called a message box. You can display a message box by adding the MsgBox action to a macro or by adding the MsgBox function to a Visual Basic procedure.

What do you want to do?

Display a message box by using a macro

Display a message box by using Visual Basic for Applications


 Show or hide warning messages

Show or hide warning messages

You can temporarily disable the modal warning messages displayed by Microsoft Access while a macro or Visual Basic procedure is running, or enable them again by carrying out the SetWarnings action in the macro or procedure.

What do you want to do?

Show or hide warning messages by using a macro

Show or hide warning messages by using Visual Basic for Applications


 Validate data by using a macro or event procedure

Validate data by using a macro or event procedure

You can use a macro or an event procedure to validate data being entered in a form either by creating a macro that responds to an event on the form or by creating event procedures.

What do you want to do?

Validate data by using a macro

Validate data by using an event procedure

Learn more about using a macro or an event procedure for data validation


 Why use a macro or an event procedure for data validation?

Why use a macro or an event procedure for data validation?

In most cases, you can verify that data is entered correctly into a control on a form by setting the ValidationRule property for the control, or by setting record or field validation rules in the underlying table to which the control is bound. Macros and event procedures provide additional power and flexibility for more complex validation.

Use a macro or an event procedure for data validation if:

  • Your validation rule involves conditions for more than one value on the form. For example, you might want to verify that any two of three fields are filled in before saving a record.

  • You want to display different error messages for different types of errors in the field. For example, if the value entered is greater than the acceptable range, you can display one message, and if it's less than the acceptable range, you can display a different message.

  • You want the user to be able to override your validation rule. In this case, you can display a warning message asking the user to confirm the data.

  • The validation involves references to controls on other forms or contains a function.

  • You have a validation rule that you can use for more than one form, and you want the convenience of defining the rule once and then referring to it in each form.

For more information about creating a macro, click [image] .

For more information about customizing an event procedure, click [image] .


 Example of validating data by using an event procedure

Example of validating data by using an event procedure

In some circumstances, you might want to use validation rules that depend on complex conditions, and then take different actions depending on those conditions. For example, because different countries have different rules for their postal codes, a database that stores postal codes can't rely on a simple validation rule to ensure that a postal code is entered correctly.

You can, however, create an event procedure that checks which country is entered in the Country control and then checks that the value entered in the PostalCode control has the right characteristics for that country.

First, open the form that contains the controls in Design view. Then, add the following Visual Basic code to the form's BeforeUpdate event procedure to display different messages, depending on the value of the Country control and the length of the entry in the PostalCode control.

Private Sub Form_BeforeUpdate(Cancel As Integer)
    Select Case Me![Country]
        Case "France", "Italy", "Spain"
            If Len(Me![PostalCode]) <> 5 Then
                MsgBox "PostalCode must be 5 characters."
                Cancel = True
            End If
        Case "Australia", "Singapore"
            If Len(Me![PostalCode]) <> 4 Then
                MsgBox "PostalCode must be 4 characters."
                Cancel = True
            End If
    End Select
End Sub

Note You add Visual Basic code to the BeforeUpdate event procedure for the form, not the control, because the validation involves two different controls on the form.

Now when you use the form to add a new supplier, Microsoft Access runs the validation procedure after you finish entering the new record, but before it saves the record in the Suppliers table. If either condition in the procedure is met, Access displays the appropriate message and doesn't save the record in the Suppliers table.


 What's new with macros?

What's new with macros?

Microsoft Access 2000 provides new actions you can use to open data access pages and the new database objects, diagrams, stored procedures, and views, in a Microsoft Access project (.adp).

  • Open data access pages You can use the OpenDataAccessPage action to open a data access page in the current database in either Design view or Page view.

  • Open Access project diagrams You can open a diagram in the current Access project by using the OpenDiagram action.

  • Open Access project stored procedures You can open a stored procedure in the current Access project by using the OpenStoredProcedure diagram. You can open the stored procedure in Datasheet view, Design view, or Print Preview.

  • Open Access project views You can open a view in the current Access project by using the OpenView action.


 Macros: What they are and how they work

Macros: What they are and how they work

What is a macro?

A macro is a set of one or more actions that each perform a particular operation, such as opening a form or printing a report. Macros can help you to automate common tasks. For example, you can run a macro that prints a report when a user clicks a command button.

Macros contain actions and arguments

A macro can be one macro composed of a sequence of actions, or it can be a macro group. You can also use a conditional expression to determine whether in some cases an action will be carried out when a macro runs.

A sequence of actions

The following macro is composed of a series of actions. Microsoft Access carries out these actions each time the macro runs. To run this macro, you refer to the macro name Review Products.

A macro containing several actions

A macro group

If you have numerous macros, grouping related macros in macro groups can help you to manage your database more easily. To display the names of macros for a macro group, click Macro Names on the View menu in the Macro window.

For example, the following macro group, named Buttons, is made up of three related macros: Employees, Products, and Reps. Each macro carries out the OpenForm action, and the Products macro also carries out the MoveSize action.

Example of a macro group

The name in the Macro Name column identifies each macro. When you run a macro in a macro group, Access carries out the action in the action column and any actions that immediately follow whose Macro Name column is blank.

To run a macro in a macro group, you use the macro group name followed by a period and then the macro name. In the preceding example, to refer to the Employees macro in the Buttons macro group, you would type Buttons.Employees.

Conditional actions

To display the Condition column, you click Conditions on the View menu in the Macro window. The following macro runs the MsgBox and the StopMacro actions only when the expression in the Condition column is true (when there is a Null value in the SupplierID field).

Example of a conditional action in a macro

For information on creating a macro, click [image] . For information on running a macro, click [image] .


 Should I use a macro or Visual Basic?

Should I use a macro or Visual Basic?

In Microsoft Access, you can accomplish many tasks by using macros or through the user interface. In many other database programs, the same tasks require programming. Whether to use a macro or Visual Basic for Applications often depends on what you want to do.

When should I use a macro?

Macros are an easy way to take care of simple details such as opening and closing forms, showing and hiding toolbars, and running reports. You can quickly and easily tie together the database objects you've created because there's little syntax to remember; the arguments for each action are displayed in the lower part of the Macro window.

In addition to the ease of use macros provide, you must use macros to:

  • Make global key assignments.

  • Carry out an action or series of actions when a database first opens. However, you can use the Startup dialog box to cause certain things to occur when a database opens, such as opening a form.

When should I use Visual Basic?

You should use Visual Basic instead of macros if you want to:

  • Make your database easier to maintain. Because macros are separate objects from the forms and reports that use them, a database containing many macros that respond to events on forms and reports can be difficult to maintain. In contrast, Visual Basic event procedures are built into the form's or report's definition. If you move a form or report from one database to another, the event procedures built into the form or report move with it.

  • Create your own functions. Access includes many built-in functions, such as the IPmt function, which calculates an interest payment. You can use these functions to perform calculations without having to create complicated expressions. By using Visual Basic, you can also create your own functions either to perform calculations that exceed the capability of an expression or to replace complex expressions. In addition, you can use the functions you create in expressions to apply a common operation to more than one object.

  • Mask error messages. When something unexpected happens while a user is working with your database, and Access displays an error message, the message can be quite mysterious to the user, especially if the user isn't familiar with Access. By using Visual Basic, you can detect the error when it occurs and either display your own message or take some action.

  • Create or manipulate objects. In most cases, you'll find that it's easiest to create and modify an object in that object's Design view. In some situations, however, you might want to manipulate the definition of an object in code. By using Visual Basic, you can manipulate all the objects in a database, as well as the database itself.

  • Perform system-level actions. You can carry out the RunApp action in a macro to run another Microsoft Windows-based or Microsoft MS-DOS–based application from your application, but you can't use a macro to do much else outside Access. By using Visual Basic, you can check to see whether a file exists on the system, use Automation or dynamic data exchange (DDE) to communicate with other Windows-based applications such as Microsoft Excel, and call functions in Windows dynamic-link libraries (DLLs).

  • Manipulate records one at a time. You can use Visual Basic to step through a set of records one record at a time and perform an operation on each record. In contrast, macros work with entire sets of records at one time.

  • Pass arguments to your Visual Basic procedures. You can set arguments for macro actions in the lower part of the Macro window when you create the macro, but you can't change them when the macro is running. By using Visual Basic, however, you can pass arguments to your code at the time it is run or you can use variables for arguments — something you can't do in macros. This gives you a great deal of flexibility in how your Visual Basic procedures run.


 Open a macro

Open a macro

  1. In the Database window, click Macros [image] under Objects.

  2. Click the name of the macro you want to open.

  3. Click the Design button on the Database window toolbar.

  4. Make the changes you want to make. For example:
    • To add an action, click [image] .

    • To move or copy an action, click [image] .

    • To add a condition, click [image] .


 Open the Macro or the Visual Basic Editor Code window from a form or report

Open the Macro or the Visual Basic Editor Code window from a form or report

  1. In form or report Design view, do one of the following:
    • Double-click the form selector or report selector to open the property sheet for the form or report.

    • Double-click the section selector to open the property sheet for the section.

    • Make sure a control is selected, and then click Properties [image] on the toolbar.
  2. Click the Build button [image] next to the appropriate event property. For example, if you want to create a macro or event procedure that will run when you click a command button, click the Build button next to the command button's OnClick event property.

  3. Click Macro Builder to open the Macro window, or click Code Builder to open the Visual Basic Editor Code window.

Note If you want to be able to view all the code behind a form or report, click Code on the View menu.


Create macros

What do you want to do?

Create a macro

Create a macro group

Add an action to a macro

Move an action in a macro

Enter an expression in a macro action argument

Learn why you use conditions in a macro

Show and hide macro names and conditions in the Macro Window


 Create a macro group

Create a macro group

If you want to group several related macros in one place rather than keeping track of them separately, you can organize them as a macro group.

  1. In the Database window, click Macros [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. Click Macro Names [image] on the toolbar, if it isn't already pressed in.

  4. In the Macro Name column, type a name for the first macro in the macro group.

  5. Add the actions you want the macro to carry out.

    How?

  6. Repeat steps 4 and 5 for any other macros you want to include in the macro group.

Note When you save the macro group, the name you specify is the name of the group of macros. This name is displayed in the list of macros and macro groups in the Database window. Whenever you refer to a macro in a macro group, use this syntax:

macrogroupname.macroname

For example, Buttons.Products refers to the Products macro in the Buttons macro group. In a list of macros, such as the Macro Name argument list for the RunMacro action, Microsoft Access displays the Products macro as Buttons.Products.


 Carry out an action when my database first opens

Carry out an action when my database first opens

You can use a special macro named AutoExec to carry out an action or series of actions when your database first opens. When you open a database, Microsoft Access looks for a macro with this name and, if it finds one, runs it automatically.

  1. Create a macro containing the actions you want to run when you open the database.

    How?

  2. Save the macro with the name AutoExec.

The next time you open the database, Access runs this macro automatically.

Notes

  • If you don't want to run the AutoExec macro when you open the database, hold down the SHIFT key when the database opens.

  • You can also control how a database or application starts by setting options in the Startup dialog box (Tools menu). For more information, click [image] .


 Tips on setting action arguments in a macro

Tips on setting action arguments in a macro

After you add an action to a macro, you set the arguments for the action in the lower portion of the Macro window. These arguments give Microsoft Access additional information on how to carry out the action.

Here are some tips on setting action arguments:

  • You can type a value in an argument box, or in many cases you can select a setting from a list.

  • In general, it's a good idea to set action arguments in the order they're listed, because choices for one argument may determine those for arguments that follow.

  • If you add an action to your macro by dragging a database object from the Database window, Microsoft Access automatically sets appropriate arguments for that action.

  • If an action has an argument that calls for the name of a database object, you can set the argument and the corresponding object type argument automatically by dragging the object from the Database window to the argument box.

  • You can use an expression preceded by an equal sign (=) to set many action arguments.

  • For more information on setting a specific action argument, click the action argument and press F1.


 Enter an expression in a macro action argument

Enter an expression in a macro action argument

  • Type an equal sign (=) followed by the expression. For example, the following expression sets the action argument to the value of the CompanyPickList control:

    =[CompanyPickList]

There are two exceptions: the Expression argument of the SetValue action, and the Repeat Expression argument of the RunMacro action. If you precede an expression in these arguments with an equal sign, Microsoft Access evaluates the expression twice, which can cause unexpected results.

Tip In a Microsoft Access database (.mdb), click the Build button [image] to use the Expression Builder. The Expression Builder is not available from a Microsoft Access project.

For more information on setting action arguments in a macro, click [image] .


 Why use conditions in a macro?

Why use conditions in a macro?

In some cases, you may want to carry out an action or series of actions in a macro only if a particular condition is true. For example, if you're using a macro to validate data in a form, you might want to display one message in response to one set of values entered in a record and another message in response to a different set of values. In cases like these, you can use conditions to control the flow of the macro.

For example, the following macro carries out the StopMacro action when there is no value in the Country field (when the value is Null). It carries out one of several pairs of MsgBox and CancelEvent actions if the length or form of the PostalCode value isn't appropriate for the country in the Country field.

Conditional macro performs different actions depending on values in the Country and PostalCode fields

A condition is a logical expression. The macro follows different paths depending on whether the condition is true or false. To see examples of macro conditions, click [image] .

You enter conditions in the Condition column in the Macro window. If a condition is true, Microsoft Access carries out the action in that row. You can have Microsoft Access carry out a series of actions if the condition is true by typing an ellipsis (...) in the Condition column of the actions that immediately follow the condition.

For information on how to make a macro run under specific conditions, click [image] .


 Make a macro run under specific conditions

Make a macro run under specific conditions

  1. In the Macro window, click Conditions [image] on the toolbar.

  2. In the Condition column, type a conditional expression in the row where you want to set the condition.

    Notes

    • In a Microsoft Access database (.mdb), click the Build button [image] to use the Expression Builder. The Expression Builder is not available from a Microsoft Access project.

    • You can't use an SQL expression in a macro Condition column.
  3. In the Action column, enter the action you want Microsoft Access to perform when the condition is true.

When you run the macro, Microsoft Access evaluates the first conditional expression. If the condition is true, Microsoft Access carries out the action in that row and all of the immediately following actions that are preceded by an ellipsis (...) in the Condition column. For example, the following macro carries out the MsgBox and StopMacro actions only when there is no value in the SupplierID field (when the value is Null).

Macro with a conditional expression

Microsoft Access then runs any additional actions in the macro that have a blank Condition column until it reaches another expression, a macro name, or the end of the macro.

If the condition is false, Microsoft Access ignores the action and any immediately following actions that are preceded by an ellipsis in the Condition column and moves to the next action row that contains another condition or a blank Condition column.

For examples of macro conditions, click [image] . For information on creating expressions, click [image] .


 Show and hide macro names and conditions in the Macro window

Show and hide macro names and conditions in the Macro window

  • Click Macro Names [image] on the toolbar to show or hide the Macro Name column, or click Conditions [image] to show or hide the Condition column.

To change whether Microsoft Access displays these columns when you create macros, click Options on the Tools menu, click the View tab, and select or clear the Names Column and Conditions Column check boxes under Show In Macro Design.


 Examples of macro conditions

Examples of macro conditions

Use this expression | To carry out the action if
[City]="Paris" | Paris is the City value in the field on the form from which the macro was run.
DCount("[OrderID]", "Orders")>35 | There are more than 35 entries in the OrderID field of the Orders table.
DCount("*", "Order Details", "[OrderID]=Forms![Orders]![OrderID]")>3 | There are more than three entries in the Order Details table for which the OrderID field of the table matches the OrderID field on the Orders form.
[ShippedDate] Between #2-Feb-1995# And #2-Mar-1995# | The value of the ShippedDate field on the form from which the macro is run is no earlier than 2-Feb-1995 and no later than 2-Mar-1995.
Forms![Products]![UnitsInStock]<5 | The value of the UnitsInStock field on the Products form is less than five.
IsNull([FirstName]) | The FirstName value on the form from which the macro is run is Null (has no value). This expression is equivalent to [FirstName] Is Null.
[Country]="UK" And Forms![SalesTotals]![TotalOrds]>100 | The value in the Country field on the form from which the macro is run is UK, and the value of the TotalOrds field on the SalesTotals form is greater than 100.
[Country] In ("France", "Italy", "Spain") And Len([PostalCode])<>5 | The value in the Country field on the form from which the macro is run is France, Italy, or Spain, and the postal code isn't five characters long.
MsgBox("Confirm changes?",1)=1 | You click OK in a dialog box that the MsgBox function displays. If you click Cancel in the dialog box, Microsoft Access ignores the action.

Tip To cause Microsoft Access to temporarily ignore an action, enter False as a condition. Temporarily ignoring an action can be helpful when you are trying to find problems in a macro.


 Force a page break in a report if a condition is met

Force a page break in a report if a condition is met

You can force a page break in a report if a condition is met by setting the Visible property of a page break control in a macro or an event procedure.

What do you want to do?

Use a macro to force a page break in a report if a condition is met

Use Visual Basic for Applications to force a page break in a report if a condition is met


Example of using a macro to display related records when you move between records

When you move between supplier records on a Suppliers form, you might want to see the products each supplier carries in a Product List form. You can accomplish this by carrying out an OpenForm action in a macro that runs in response to the Supplier form's Current event. You can make the Product List form display records whose value in the SupplierID field in the underlying table matches the value in the SupplierID field on the Suppliers form. Set the action's Where Condition argument as follows:

[SupplierID]=Forms![Suppliers]![SupplierID]

Tip If you don't always want the Products form to open when you move between records on the Suppliers form, include a conditional expression in the macro that checks whether or not the Product List form is open.

Display records in another table by using a macro

After creating the macro, set the Suppliers form's OnCurrent event property to the name of the macro.


 Convert macros to Microsoft Visual Basic

Convert macros to Microsoft Visual Basic

Microsoft Access can automatically convert macros to Visual Basic event procedures or modules that perform equivalent actions by using Visual Basic code. You can convert macros on a form or report, or you can convert global macros that aren't attached to a specific form or report.

What do you want to do?

Convert macros on a form or report

Convert global macros


 Carry out a macro action in a Visual Basic procedure

Carry out a macro action in a Visual Basic procedure

Microsoft Access defines a special object, DoCmd, that you use to carry out macro actions in Visual Basic procedures. You carry out an action by adding a method of the DoCmd object to your procedure. Most actions have a corresponding DoCmd method.

  • In the procedure, add the DoCmd method that corresponds to the action by using the following syntax:

    DoCmd.method [arguments]

Method is the name of a method. Arguments are the method arguments, if there are any.

For example, to create a procedure that carries out the OpenForm action, add the OpenForm method of the DoCmd object to the procedure. The following method is equivalent to the OpenForm action; it opens the Add Products form:

DoCmd.OpenForm "Add Products"

A few actions don't have corresponding DoCmd methods, although some have equivalent Visual Basic statements or functions. For a list of those actions and their Visual Basic equivalents, click [image] .


Macro actions that don't have corresponding DoCmd methods

Action | Visual Basic equivalent
AddMenu | No equivalent
MsgBox | MsgBox function
RunApp | Shell function
RunCode | Procedure call (Call statement)
SendKeys | SendKeys statement
SetValue | Assignment statement (Let statement)
StopAllMacros | Stop or End statements
StopMacro | Exit Sub or Exit Function statements


 Run a macro

Run a macro

When you run a macro, Microsoft Access starts at the beginning of the macro and carries out all the actions in the macro until it reaches either another macro (if the macro is in a macro group) or the end of the macro.

You can run a macro directly, from another macro or an event procedure, or in response to an event that occurs on a form or report, or a control on a form or report. For example, you can attach a macro to a command button on a form so that the macro runs when a user clicks the button. You can also create a custom menu command or toolbar button that runs a macro, assign a macro to a key combination, or run a macro automatically when you open a database.

What do you want to do?

Run a macro directly

Run a macro in a macro group

Run a macro from another macro or an event procedure

Run a macro in response to an event on a form, report, or control

Create a command button that runs a macro

Add a menu command that runs a macro

Add a toolbar button that runs a macro

Assign a macro to a key combination

Run a macro when my database first opens


 Run a macro from another macro or from a Visual Basic procedure

Run a macro from another macro or from a Visual Basic procedure

To run a macro from another macro or from a Visual Basic procedure, add the RunMacro action to your macro or procedure.

  • To add the RunMacro action to a macro, click RunMacro in the action list in a blank action row, and set the Macro Name argument to the name of the macro you want to run.

  • To add the RunMacro action to a Visual Basic procedure, add the RunMacro method of the DoCmd object to your procedure, and specify the name of the macro you want to run; for example, the following RunMacro method runs the macro My Macro:

    DoCmd.RunMacro "My Macro"

For more information on the RunMacro action, click [image] .


 Find problems in a macro by single stepping through it

Find problems in a macro by single stepping through it

By single stepping through a macro, you can observe the flow of the macro and the results of each action, and isolate any action that causes an error or produces unwanted results.

  1. Open the macro.

    How?

  2. Click Single Step [image] on the toolbar.

  3. Click Run [image] on the toolbar.

  4. Click Step to carry out the action shown in the Macro Single Step dialog box.

  5. Click Halt to stop the macro and close the dialog box.

  6. Click Continue to turn off single stepping and run the remainder of the macro.

Tip To halt a macro while it's running and then single step through it, press CTRL+BREAK.


 Assign an action or set of actions to a key

Assign an action or set of actions to a key

You can assign an action or set of actions to a specific key or key combination by creating an AutoKeys macro group. When you press the key or key combination, Microsoft Access carries out the action.

  1. In the Database window, click Macros [image] under Objects.

  2. Click New.

  3. Click Macro Names [image] on the toolbar.

  4. In the Macro Name column, type the key or key combination to which you want to assign the action or set of actions.

    For information about the key combinations you can use to make key assignments, click [image] .

  5. Add the action or set of actions you want the key or key combination to carry out. For example, you could add a RunMacro action that runs the Print Current Record macro when CTRL+P is pressed.

    Select a macro action to run for a key combination you define.

  6. Repeat steps 4 and 5 for any other key assignments you want to make.

  7. Save the macro group with the name AutoKeys.

The new key assignments are in effect as soon as you save the macro group and each time you open the database.

Note If you assign a set of actions to a key combination that is already being used by Access (for example, CTRL+C is the key combination for Copy), the actions you assign this key combination replace the Access key assignment.


 AutoKeys key combinations

AutoKeys key combinations

The following table shows the key combinations you can use to make key assignments in an AutoKeys macro group. These key combinations are a subset of the syntax used in the SendKeys statement in Visual Basic. For more information about the syntax of the SendKeys statement, click [image] .

SendKeys syntax | Key combination
^A or ^4 | CTRL+Any letter or number key
{F1} | Any function key
^{F1} | CTRL+Any function key
+{F1} | SHIFT+Any function key
{INSERT} | INS
^{INSERT} | CTRL+INS
+{INSERT} | SHIFT+INS
{DELETE} or {DEL} | DEL
^{DELETE} or ^{DEL} | CTRL+DEL
+{DELETE} or +{DEL} | SHIFT+DEL


 About getting Help on Visual Basic

About getting Help on Visual Basic

There are many ways to access Help for answers to questions about Microsoft Visual Basic and for information about Visual Basic keywords. Descriptions of a few of the most common and useful ways of accessing Help follow.

To access Help, you can:

  • Press F1 in a Visual Basic module. While you are working in a module, you can go directly to Help on a method, property, function, statement, or object by clicking the keyword in a line of code and then pressing F1.

  • Press F1 in a Object Browser. You can use the Object Browser to see information about objects, properties, methods, and constants. For information on using the Object Browser, click [image] .

  • Ask the Office Assistant. To display the assistant balloon and type an entry, either click Office Assistant on the toolbar, or if the assistant is already displaying with no balloon, click the assistant. The assistant makes it easy to find the topics you're looking for. Just type the method, property, function, statement, or function you want help on, or type a query, and then select one of the topics the assistant suggests. The more specific your task is, the more specific the suggested topics will be. An example of a specific entry is "Program my form to automatically update data."

    Notes

    • When the Visual Basic Editor is active, the Office Assistant by default searches for topics only in programming Help files. To change this default so that both programming Help and product Help files are searched, right-click the Office Assistant, click Options and select Search For Both Product And Programming Help When Programming.

    • When any window other than the Visual Basic Editor is active, the Office Assistant searches for topics only in product Help files. Help on actions and Microsoft Access properties is available with both product and programming Help.
  • Use the Contents and Search tabs. The Help Topics dialog box contains several tabs that you can use to access Help information in different ways.
    • Click the Contents tab, and then double-click the Microsoft Access Programming and Language Reference or Visual Basic for Applications book to see the categories of reference information, such as actions, events, functions, objects and collections, methods, properties, and statements. Double-click a category book to view lists of topics for each category.

      To print a topic or book of topics, select the topic or book and then click Print.

    • Click the Search tab, and then click the topic you want.

Tips

  • To switch between your application and language reference Help, press ALT+TAB or use the Windows taskbar. If you leave Help active, you can immediately return to the last topic you were viewing.


 Copy Visual Basic code examples from Help to the Code window

Copy Visual Basic code examples from Help to the Code window

  1. Select the example code you want to copy from the Help topic, and then right-click it.

  2. On the shortcut menu, click Copy.

  3. Switch to the Visual Basic Editor.

  4. Paste the example into the Code window of your module.


 Modules: What they are and how they work

Modules: What they are and how they work

What is a module?

A module is a collection of Visual Basic for Applications declarations and procedures that are stored together as a unit.

Parts of a module

There are two basic types of modules: class modules and standard modules. Each procedure in a module can be a Function procedure or a Sub procedure.

Class modules

Form and report modules are class modules that are associated with a particular form or report. Form and report modules often contain event procedures that run in response to an event on the form or report. You can use event procedures to control the behavior of your forms and reports, and their response to user actions, such as clicking the mouse on a command button.

When you create the first event procedure for a form or report, Microsoft Access automatically creates an associated form or report module. To see the module for a form or report, click Code [image] on the toolbar in form or report Design view.

Choose an object and an event to select a procedure

Procedures in your form and report modules can call procedures you have added to standard modules.

In Access 95, class modules exist in association only with a form or report. In Access 97 or later, class modules can also exist independent of a form or report, and this type of class module is listed in Modules under Objects on the Database window. You can use a class module in Modules to create a definition for a custom object. To find out more about programming with these class modules, click [image] .

Standard modules

Standard modules contain general procedures that aren't associated with any other object and frequently used procedures that can be run from anywhere within your database.

Standard modules contain procedures that are available from anywhere in the database

You can view the list of standard modules in your database by clicking Modules under Objects in the Database window. Form, report, and standard modules are also listed in the Object Browser.

For more information on procedures, click [image] .


 What is a procedure?

What is a procedure?

A procedure is a unit of Visual Basic code. A procedure contains a series of statements and methods that perform an operation or calculate a value. For example, the following event procedure uses the OpenForm method to open the Orders form:

Private Sub OpenOrders_Click()

    DoCmd.OpenForm "Orders"

End Sub

There are two kinds of procedures:

  • Sub procedures perform an operation or series of operations but don't return a value. You can create your own Sub procedures or use the event procedure templates that Microsoft Access creates for you.

    Each form and report in your database has a built-in form module or report module that contains event procedure templates. You can add code that runs in response to events that occur on the form, the report, or the controls on the form or report. When Microsoft Access recognizes that an event has occurred on a form, report, or control, it automatically runs the event procedure named for the object and event. For example, you can write an event procedure that sets the focus to a Spouse Name text box when the user selects a Married check box.

    Tip Many wizards (for example, the Command Button Wizard) that create objects also create event procedures for the object. You can look at these event procedures to see examples of how procedures work.

  • Function procedures (often just called functions) return a value, such as the result of a calculation. Microsoft Visual Basic includes many built-in functions; for example, the Now function returns the current date and time. In addition to these built-in functions, you can create your own custom functions.

    Because functions return values, you can use them in expressions. You can use functions in expressions in many places in Microsoft Access, including in a Visual Basic statement or method, in many property settings, or in a criteria expression in a filter or query.

Here is an example of a Function procedure, FirstOfNextMonth, that returns the date of the first day of the month following the current date:

Function FirstOfNextMonth()

    FirstOfNextMonth = _
        DateSerial(Year(Now), Month(Now) + 1, 1)

End Function

This custom function consists of a single assignment statement that assigns the results of an expression (on the right side of the equal sign [=]) to the name of the function, FirstOfNextMonth (on the left side of the equal sign). The function calculates a result by using the built-in Visual Basic DateSerial, Year, Now, and Month functions.

After you create this function, you can use it in an expression almost anywhere in Microsoft Access. For example, you could specify that a text box display the first day of the month following the current date as its default value by setting the text box control's DefaultValue property to the following expression in the property sheet:

=FirstOfNextMonth()

Note To use a function as a property setting, the function must be in the form or report module, or in a standard module. You can't use a function in a class module that isn't associated with a form or report as a form or report property setting.

Both Sub and Function procedures can accept arguments. For more information on using arguments in Visual Basic, click [image] .


 Create your first custom Visual Basic procedure

Create your first custom Visual Basic procedure

By extending your database to include Visual Basic procedures, you can customize the way the tables, forms, reports, and queries in your database work together. There are several types of procedures. You can create an event procedure by adding code to predefined templates in a form module or report module. You also can create your own Function procedures or Sub procedures in standard modules, or in class modules (which include form and report modules).

You can call procedures in a standard module or a class module from expressions, from other procedures, event procedures, procedures in other modules, and macros. Event procedures run automatically in response to events — such as mouse clicks — that occur on a form, report, or control.

What do you want to do?

Create a custom function

Create a custom Sub procedure

Create an event procedure


 Create a class module that is not associated with a form or report

Create a class module that is not associated with a form or report

  1. In the Database window or in the Visual Basic Editor, click Class Module on the Insert menu.

    An empty class module appears in the Visual Basic Editor.

  2. Add any declarations and procedures that you want to the module.

  3. To save the module, click Save [image] on the toolbar, and specify a name for the class module in the Save As dialog box.

To open the class module after you save it for the first time, in the Database window, click Modules [image] under Objects, and click Design.

For information on using class modules, click [image] . Also, see Building Applications with Forms and Reports.


 Use arguments in Visual Basic

Use arguments in Visual Basic

An argument supplies additional information to a procedure, statement, or method. When you create a Function or Sub procedure, you declare arguments if you want to be able to supply information to the procedure when you call it.

When you call a procedure that has arguments, you specify the arguments that you want to pass to it. You also specify arguments for many statements and methods.

What do you want to do?

Create a custom function

Create a Sub procedure

Specify arguments when you use a procedure, statement, or method


 About working with data and database objects by using Visual Basic code

About working with data and database objects by using Visual Basic code

In addition to working with data and objects such as forms and reports in the Microsoft Access interface, you can use Microsoft Visual Basic to write procedures that dynamically create, delete, and modify data and objects. For example, you can write a procedure that places a caption on a form or that changes the color of a field on a form when a user performs a particular action.

You can refer to data and objects directly in your code, or you can declare object variables to represent them. After an object variable is declared and assigned, you can use it just as you would the name of the object it represents, and you can change its value, just as you can change the value of any variable.

For example, the following Sub procedure creates a table, Old Invoices, with a single field, OrderID:

Sub CreateTable ()

    ' Declare variables.
    Dim dbs As Database, tbl As TableDef, fld As Field

    ' Assign the current database to the database
    ' variable.
    Set dbs = CurrentDB

    ' Create a new table and field, and assign them
    ' to the table and field variables.
    Set tbl = dbs.CreateTableDef("Old Invoices")
    Set fld = tbl.CreateField("OrderID", dbText)

    ' Add the field to the table, then add the table
    ' to the database.
    tbl.Fields.Append fld
    dbs.TableDefs.Append tbl
    dbs.TableDefs.Refresh

End Sub

Microsoft Data Access Objects (DAO) provides the objects, such as tables, queries, relationships, and indexes, that handle data-management tasks in a Microsoft Access database. These objects are called data access objects. You can share Visual Basic code that uses data access objects with other applications that use Microsoft DAO, such as Microsoft Excel.

You can also use Jet and Replication Objects to access and manipulate data in a database server through any OLE DB provider.

In addition, Microsoft Access defines a variety of objects that you use for working with data, such as forms, reports, and controls.

For more information on working with data access objects, click [image] or see Building Applications with Forms and Reports. For more information about working with Jet and Replication Objects, click [image] .


 About running Visual Basic code

About running Visual Basic code

You run Visual Basic code in Microsoft Access by running a Sub procedure or Function procedure. Procedures contain a series of statements and methods that perform an operation or calculate a value.

Procedures are stored in units called modules. However, you don't run a module; rather, you call the procedures from expressions, other procedures, or macros. Event procedures in form or report modules also run in response to user actions.

Here are the ways to run Visual Basic code in Microsoft Access:

  • Create an event procedure. When the user performs an action that causes that event, the event procedure runs.

    For example, you can add code to the Click event procedure of a command button that opens a form when a user clicks the button. For more information on creating an event procedure, click [image] .

  • Use a function in an expression or in the Immediate window of the Visual Basic Editor.

    For example, you can use a function in an expression that defines a calculated field in a form, report, or query. You can use expressions as property settings in queries and filters, in macros and actions, in Visual Basic statements and methods, or in SQL statements. For more information on creating a custom function, click [image] .

  • Call a Sub procedure in another procedure or in the Immediate window of the Visual Basic Editor.

    If you have certain code you run frequently, you can put it in a Sub procedure. Rather than repeating the Visual Basic code that performs the operation in each procedure, you write it once in the common procedure and then call the common procedure each time you want to perform the operation. For more information on creating a Sub procedure, click [image] .

  • Click the Run Sub/UserForm command on the Run menu in the Visual Basic Editor to run a procedure that does not take arguments.

    In the Code window, place the cursor in the procedure that you want to run. Then click Run Sub/UserForm on the Run menu.

  • Carry out the RunCode action in a macro.

    You can use the RunCode action to run a built-in Visual Basic function or a function you've created. To run a Sub procedure or an event procedure, create a function that calls the Sub procedure or event procedure, and then use the RunCode action to run the function. For more information on the RunCode action, click [image] .


 Use the Microsoft Visual Basic Editor

Use the Microsoft Visual Basic Editor

The Microsoft Visual Basic Editor (VBE) is the development environment in which you create and edit Visual Basic for Applications (VBA) code, contained in files that you have created in Microsoft Office applications — including Microsoft Access databases and Microsoft Access projects. VBE features include the Project Explorer, the Properties window, the Object Browser, and the Code window, as well as debugging tools.

What do you want to do?

Learn more about running Visual Basic for Applications code

Create a Visual Basic procedure

Work with objects in Visual Basic by using the Object browser

Debug Visual Basic code

Get Help on Visual Basic


 Work with objects in Visual Basic by using the Object Browser

Work with objects in Visual Basic by using the Object Browser

You can use the Object Browser to view and navigate among the objects available in Microsoft Access and other applications that support Microsoft Visual Basic, as well as the methods and properties of each object. When you locate a method or property in the Object Browser, you can paste it into the active module.

What do you want to do?

Locate a method or property in the Object Browser

Use the Object Browser to paste method or property syntax into a Visual Basic module


 Locate a method or property in the Object Browser

Locate a method or property in the Object Browser

  1. Open any module in the Visual Basic Editor.

  2. Click Object Browser [image] on the toolbar.

  3. In the Project/Library box (the upper-left box), click Access or another library.

  4. In the Classes box, click the object you're interested in.

  5. In the Members Of box, click the method or property you want.

Notes

  • For Help on the class, method, event or property that you select, click Help [image] in the Object Browser.

  • To view objects provided by the Microsoft Office 9.0 Object Library, such as command bar objects, you must set a reference to this library. In the Visual Basic Editor, click References on the Tools menu, and select the Microsoft Office 9.0 Object Library check box.


 Use the Object Browser to paste a method or property syntax into a module

Use the Object Browser to paste a method or property syntax into a module

  1. Select the method or property in the Object Browser.

  2. In the bottom section of the Object Browser, select the syntax you want to paste.

  3. Click Copy To Clipboard [image] in the Object Browser.

  4. Click in the Code window of the module where you want to paste the name.

  5. Click Paste [image] on the toolbar.

Microsoft Access pastes the method or property syntax into the module.

Note After pasting syntax for Sub procedures, you need to remove any parentheses surrounding placeholders in the syntax.


Customize the Visual Basic Code window

What do you want to do?

Change how Visual Basic code is displayed in the Code window

Disable syntax-error checking for Visual Basic code

Ignore error handling for Visual Basic code

Require variable declarations for Visual Basic code


 Change how Visual Basic code is displayed in the Code window

Change how Visual Basic code is displayed in the Code window

  1. On the Tools menu, click Options.

  2. Set the appropriate options.

    By setting options in the Options dialog box, you can change the color, font, font size, and tab width used when you type Visual Basic code in the Code window. You can also specify whether the entire module is displayed (default) or each procedure is displayed individually in the Code window, and set various additional options for working in the Code window.


 Display syntax information in the Visual Basic Editor Code window

Display syntax information in the Visual Basic Editor Code window

  1. On the Tools menu, click Options.

  2. Click the Editor tab.

  3. Under Code Settings, make sure Auto Quick Info is selected.

When Auto Quick Info is selected, the Visual Basic Editor displays syntax information in the Code window. When you type a method or the name of an existing procedure followed by a space or opening parenthesis, a tip automatically appears giving syntax information about the method or procedure, such as the arguments for you to specify.


 Display the value of variables in the Visual Basic Editor Locals window

Display the value of variables in the Visual Basic Editor Locals window

  1. Suspend execution of Visual Basic code.

    How?

  2. Click Locals Window on the View menu.

In the Locals window, Microsoft Access automatically displays the name, current value, and type of all the variables and objects in the current procedure. The values in the Locals window are updated each time you suspend code execution. You can change the value of a variable in the Locals window by selecting the existing value and entering the new value.


 Display a list of relevant objects, properties, and methods in the Visual Basic Editor Code window

Display a list of relevant objects, properties, and methods in the Visual Basic Editor Code window

  1. On the Tools menu, click Options.

  2. Click the Editor tab.

  3. Under Code Settings, make sure Auto List Members is selected.

When Auto List Members is selected, Microsoft Access assists you in completing statements while you're writing Visual Basic code. When you type the name of an object, followed by a space or opening parenthesis, Microsoft Access displays a list of relevant objects, properties, and methods that could follow the object name. There are several keys you can use to enter an item from the list into the current line of code.

Key | Effect
TAB | Enters the item
SPACEBAR | Enters the item followed by a space
ENTER | Enters the item and moves the cursor to the next line

Note To make the list disappear, press ESC.


 Require variable declarations for Visual Basic code

Require variable declarations for Visual Basic code

Microsoft Visual Basic doesn't automatically require that you explicitly declare a variable before using it in a procedure. If you use a variable that hasn't been explicitly declared, Visual Basic implicitly declares it as a variable with the Variant data type.

Although implicit declarations are convenient, they can lead to subtle errors in your code. To require that variables be declared before they are used in a procedure, do the following:

  1. On the Tools menu, click Options.

  2. Click the Editor tab.

  3. Under Code Settings, select the Require Variable Declaration check box.

    When the Require Variable Declaration check box is selected, Microsoft Access automatically includes an Option Explicit statement in the Declarations section of all new modules in the database, including the form and report modules associated with new forms or reports. For more information on the Option Explicit statement, click [image] .


Debug Visual Basic code

What do you want to do?

Read more about resolving errors

Use a breakpoint to suspend running of Visual Basic code

Step through code one line at a time

Examine the values of expressions and variables by using the Visual Basic Editor Immediate window

Monitor the values of expressions and variables by setting a watch expression

Trace Visual Basic procedure calls

Display the value of variables in the Visual Basic Editor Locals window

Display the value of a variable or expression in the Visual Basic Editor when code is suspended


 Disable syntax-error checking for Visual Basic code

Disable syntax-error checking for Visual Basic code

Microsoft Visual Basic automatically checks the code you type in the Visual Basic Editor Code window for syntax errors as you type it. To disable this feature, do the following:

  1. On the Tools menu, click Options.

  2. Click the Editor tab.

  3. Under Code Settings, clear the Auto Syntax Check check box.


 Use the Immediate window of the Visual Basic Editor while working with Visual Basic

Use the Immediate window of the Visual Basic Editor while working with Visual Basic

Use the Immediate window of the Visual Basic Editor to check the results of a line of Visual Basic code. You can use the Immediate window to check the value of a control, field, or property; to display the result of an expression; or to assign a new value to a variable, field, column, or property. The Immediate window is a kind of scratchpad window in which statements, methods, and Sub procedures are evaluated immediately.

  1. If you want to use the Immediate window at a certain point during execution of the code, suspend execution at that point.

    How?

  2. Click Immediate Window on the Debug toolbar.

  3. Type a statement, method, Function, or Sub procedure call in the window, and then press ENTER.

Tips

  • You can view the results of an expression in the Immediate window by entering the Print method of the Debug object, followed by the expression. You can use a question mark (?) as shorthand for the Print method. For example, Microsoft Visual Basic displays the value returned by the FirstOfNextMonth custom function if you type either of the following lines in the Immediate window:
    Debug.Print FirstOfNextMonth()

? FirstOfNextMonth()

    You can also add the Print method of the Debug object to your Visual Basic code to display values or the results of expressions in the Immediate window while the code is running. When the code has finished running, you can look at the results.

  • You can display the Immediate window at any time in Microsoft Access by pressing CTRL+G.


 Ignore error handling for Visual Basic code

Ignore error handling for Visual Basic code

When you add an On Error statement to a Visual Basic procedure, Microsoft Visual Basic automatically branches to an error-handling routine when an error occurs. You may want to ignore a procedure's error-handling code in some circumstances — for example, while you're debugging the procedure.

  1. On the Tools menu, click Options.

  2. Click the General tab.

  3. Under Error Trapping, select Break On All Errors.

    When you check this option, you'll automatically enter Break mode when an error occurs, regardless of error handling.


 Optimizing Visual Basic code performance

Optimizing Visual Basic code performance

Often, the best way to improve the speed at which your Visual Basic code runs is to choose a more efficient approach. However, certain techniques can help make your code run faster.

  • Make sure the code in your database is compiled. In the Visual Basic Editor Code window, click Compile on the Debug menu.

    Note Make sure to recompile your code after you rename a database file. Renaming a database decompiles the code in the database.

  • Always explicitly declare variables. You can require that variables be explicitly declared before they are used in a procedure by setting the Require Variable Declaration option on the Editor tab of the Options dialog box. For more information, click [image] .

  • Use the most specific type possible when you declare variables. For example, declare a variable that will be used to represent a form as type Form rather than as type Object or Variant.

  • Use variables to refer to properties, controls, and data access objects. If you refer more than once to the value of a property or control on a form, or to a data access object or its property, create object variables and refer to the variables rather than using full identifiers.

  • Use the Me keyword for form references within an event procedure.

  • Use the Ilf function judiciously. Avoid using the Ilf function if either of the return expressions takes a long time to evaluate.

  • Use string functions when appropriate. Use the $ functions (for example, the Str$ function) when working with strings and the non-$ functions when working with Variant or other data types.

  • Use the Integer or Long data type for math when possible.

  • Use dynamic arrays and the Erase or ReDim statement to reclaim memory.

  • Use constants whenever possible.

  • Use bookmarks for fast relocation. Use bookmarks instead of the FindNext method or some other means to return to a particular record.

  • Use the FindRecord and FindNext methods on indexed fields. These methods are much more efficient when used on a field that is indexed.

  • Organize your modules. Visual Basic loads modules on demand — that is, it loads a module into memory only when your code calls one of the procedures in that module. Placing related procedures in the same module causes Visual Basic to load additional modules only as needed.

  • Eliminate unused procedures and unused variables. As you develop and modify your applications, you may leave behind procedures that aren't called from anywhere in your code or declared variables that are no longer used. Consider reviewing your code to find and remove unused procedures and variables.

For more information, see Building Applications with Forms and Reports.


 About Visual Basic scripts in a Web page

About Visual Basic scripts in a Web page

A script is a type of computer code that can be used to make your Web page dynamic. For example, a script could be used to include a "number of visitors" counter that increments each time someone visits your Web page. Or a script could be used to include a countdown to a special event: "only x more days", where x decreases by 1 every day. Creating scripts is an advanced Office feature that requires programming knowledge. If you are a developer, you can create and edit scripts directly on your Web pages in Microsoft Access. Usually scripts are run by a Web browser when a Web page is opened or in Web page Page view, typically to display information produced by the script.

Note of caution

Be careful when copying and moving scripts. Although some scripts are self-contained and work correctly in any location on any Web page, other scripts are dependent on the structure of the Web page. When copied or moved to another Web page — or to another location on a Web page — these scripts might not run correctly or might return errors when viewed in a browser or Page view.


 About creating and editing a Visual Basic script on a Web page

About creating and editing a Visual Basic script on a Web page

You can add Microsoft Visual Basic Scripting Edition (VBScript) or JScript to your page in Microsoft Access.

Scripting is useful for custom Web-based solutions development. It provides a full object model for the Web browser and the objects on the current page. This makes it easy for you to write code that manipulates elements on the page without having to know HTML or how the objects are implemented. You can also create script code that is specifically designed to handle events that occur on objects (such as ActiveX controls) on your Web page.

To view the HTML code or edit a script for your Web page, open the Microsoft Script Editor. In the Script Editor, you can add text, edit HTML tags, and edit any script code. You can also view your Web page as it would appear in a Web browser.

For more information about creating a script, see Microsoft Script Editor Help.

More information

Create a script on a Web page

View or edit a script on a Web page


 Change the default script language

Change the default script language

  1. Open the Web page in Design view or Page view.

  2. On the Tools menu, point to Macro, and then click Microsoft Script Editor.

  3. In the Properties window, click Document in the list box.

  4. Change the value of the defaultClientScript property to either VBScript or JavaScript.


About Java applet support

A Java applet is a small software program written in the Java language, a programming language used primarily on the World Wide Web. A Java applet is a separate file referenced by an HTML document. A Java applet might be used to add animation, music, database operations, or updates to a Web page. Java was and continues to be developed by Sun Microsystems, Inc. When you open a Web page that contains a Java applet in Microsoft Access, an icon representing the applet Java applet icon appears on the page.

The icon does not appear when you view the Web page in a browser or when you print your Web page.

If you are a developer, you can also edit Java applet code.

Note of caution

Be careful when copying and moving Java applets. Although some Java applets are self-contained and work correctly in any location on any Web page, other Java applets are dependent on the structure of the Web page. When copied or moved to another Web page — or to another location on a Web page — these Java applets might not run correctly or might return errors when viewed in a browser.


 View or edit a Web script

View or edit a Web script

  1. Open the Web page in Design view or Page view.

  2. On the Tools menu, point to Macro, and then click Microsoft Script Editor.


 Scoping and Object-Naming Compatibility

Scoping and Object-Naming Compatibility

Visual Basic scoping rules affect the names you choose for your objects, modules, and procedures.

Modules and Other Objects with the Same Name

When you name a module, avoid prefacing module names with "Form_" or "Report_". Naming a module in this way could conflict with existing code you've written behind forms and reports.

If you have a module in an application created with version 1.x or 2.0 of Microsoft Access that doesn't follow these naming rules, Microsoft Access 2000 generates an error when you try to convert your application. For example, a module named Form_Orders in a Microsoft Access version 1.x or 2.0 database would generate an error and you would be asked to rename the module before attempting to convert it.

Modules and Procedures with the Same Name

Although it is not suggested, you can have a procedure with the same name as a module. To call that procedure from an expression anywhere in your application, you must use a fully qualified name for the procedure, including both the module name and the procedure name, as in the following example:

IsLoaded.IsLoaded("Orders")

Note This will not work with the Runcode action in macros. Accessing procedures with the same name as a module is not possible with Macros.

Procedures and Controls with the Same Name

If you call a procedure from a form, and that procedure has the same name as a control on the form, you must fully qualify the procedure call with the name of the module in which it resides. For example, if you want to call a procedure named PrintInvoice that resides in a standard module named Utilities, and there's also a button on the same form named PrintInvoice, use the fully qualified name Utilities.PrintInvoice when you call the procedure from your form or form module.

Controls with Similar Names

You can't have a control with a name that differs from an existing control's name by only a space or a symbol. For example, if you have a control named [Last_Name], you can't have a control named [Last Name] or [Last+Name].

Modules with the Same Names as Type Libraries

You can't save a module with the same name as a type library. If you try to save a module with the name "ADO", "Access", "DAO" or "VBA", you'll get an error stating that the name conflicts with an existing module, project, or object library. Similarly, if you've set a reference to another type library, such as the Microsoft Excel type library, you can't save a module with the name "Excel".

Fields with the Same Names as Methods

If a field in the table has the same name as an ActiveX Data Objects (ADO) method on an ADO Recordset object, or a Data Access Object (DAO) method on a DAO Recordset object, you can't refer to the corresponding field in the recordset with the . (dot) syntax. You must use the ! (exclamation point) syntax, or Microsoft Access will generate an error. The following example shows how to refer to a field called AddNew in a recordset opened on a table called Contacts:

ADO

Dim rst As New ADODB.Recordset
rst.Open "Contacts",CurrentProject.Connection, _
    adOpenKeySet,adLockOptimistic
Debug.Print rst!AddNew

DAO

Dim dbs As Database, rst As DAO.Recordset
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("Contacts")
Debug.Print rst!AddNew

Modules with the Same Names as Visual Basic Functions

If you save a module with the same name as an intrinsic Visual Basic function, Microsoft Access will generate an error when you try to run that function. For example, if you save a module named MsgBox, and then try to run a procedure that calls the MsgBox function, Microsoft Access generates the error "Expected variable or procedure, not module."

Modules with the Same Names as Objects

If a database created with a previous version of Microsoft Access includes a module that has the same name as a Microsoft Access object, an ADO object, or a DAO object, you may encounter compilation errors when you convert your database to Microsoft Access 2000. For example, a module named "Form" or "Database" may generate a compilation error. To avoid these errors, rename the module.

Naming Fields Used in Expressions or Bound to Controls on Forms and Reports

When you create a field in a table that will be bound to a control on a report or used in an expression in the ControlSource property of a control or a report, avoid assigning the field a name that's the same name as a method of the Application object. To see a list of methods of the Application object, click Object Browser on the View menu while in module Design view. Click Access in the Project/Library box, click Application in the Classes box, and view the methods of the Application object in the Members Of box.

When you create a field in a table that will be bound to a control on a form or report, avoid assigning the field any of the following names: AddRef, GetIDsOfNames, GetTypeInfo, GetTypeInfoCount, Invoke, QueryInterface, or Release.

Identifiers with Same Names as Visual Basic Keywords

The version of Visual Basic that's used by Microsoft Access 97 and 2000 contains some new Visual Basic keywords, so you can no longer use these keywords as identifiers. These keywords are: AddressOf, Assert, Decimal, DefDec, Enum, Event, Friend, Implements, RaiseEvent, and WithEvents. When you convert a database developed with a prior version of Microsoft Access, existing identifiers that are the same as a new Visual Basic keyword will cause a compile error. To correct this problem, rename the identifiers.

Project Names the Same as Microsoft Access Objects

A project name is the string that is the name of your Microsoft Access application. In prior versions of Microsoft Access, the project name was the name of the database. In Microsoft Access 2000, the project name is specified by the ProjectName property setting and its default setting is the name of the database. If you convert a database with a name that is the same as a class of objects, for example, "application," "form," or "report," Microsoft Access will append an underscore character to the database name to create a project name that does not conflict with existing objects.


 Custom Methods and Properties

Custom Methods and Properties

You can use a class module to create a definition for a new custom object. When you create a new instance of a class, you create a new object and return a reference to it.

Any public procedures defined within the class module become methods of the new object. The Sub statement defines a method that doesn't return a value; the Function statement defines a method that may return a value of a specified type.

Any Property Let, Property Get or Property Set procedures you define become properties of the new object. Property Get procedures retrieve the value of a property. Property Let procedures set the value of a nonobject property. Property Set procedures set the value of an object property.

For example, you can use a class module to create an interface layer between your application and a set of Windows application programming interface (API) functions that it calls. To do this, you create a set of simple procedures that call more complicated procedures in a DLL. When you create an instance of this class, the procedures you've created become methods of the new object. You can apply these methods as you would the methods of any object, and in doing so you also call the API functions.


 Program Toolbars and Menu Bars

Program Toolbars and Menu Bars

Microsoft Access 2000 includes command bars, which are programmable toolbars and menu bars. Using command bars, you can create custom toolbars and menus for your application.

In order to program with command bars, you must set a reference to the Microsoft Office 9.0 object library. Click References on the Tools menu while in module Design view, and select the check box next to Microsoft Office 9.0 Object Library.

The CommandBars collection includes all the command bars that currently exist within the application. You can add a new CommandBar object to the CommandBars collection by using the Add method of the CommandBars collection. For example, the following code creates a new command bar named MyCommandBar. Note that you need to set the new command bar's Visible property to True (–1) in order to see it.

Dim cmb As CommandBar
Set cmb = Application.CommandBars.Add("MyCommandBar")
cmb.Visible = True

Each CommandBar object has a CommandBarControls collection, which contains all the controls on the command bar. Command bar controls are different from the controls on a form. You can create different types of command bar controls, including buttons, combo boxes, and pop-ups. You can combine these controls to create a custom toolbar or menu bar.

To refer to the CommandBarControls collection, use the Controls property of the CommandBar object. To add a control to a command bar, use the Add method of the CommandBarControls collection, specifying which type of control you want to create. The following example adds a new button to the command bar created in the previous example:

Dim cbc As CommandBarControl
Set cbc = cmb.Controls.Add(msoControlButton)
cbc.Caption = "Button1"
cbc.Style = msoButtonCaption

You can specify an expression to evaluate or a macro to run when the user clicks a command bar control. Set the OnAction to the name of a macro or to an expression that contains a built-in or user-defined function. For example, the following line of code sets the OnAction property of a CommandBarControl object to an expression that includes the MsgBox function. This example uses the CommandBar and CommandBarControl objects created in the previous two examples:

CommandBars("MyCommandBar").Controls("Button1").OnAction = _
    "=MsgBox(""Wow!"")"

Note Unlike most other collections in Microsoft Access, the CommandBars collection and all the collections it contains are indexed beginning with 1 rather than 0.


 Improvements in Compilation Performance

Improvements in Compilation Performance

Microsoft Access includes improvements to module loading and compilation performance to make your code compile and run faster.

Form and Report Modules Created on Demand

When you create a form or report in Microsoft Access 2000, the form or report doesn't automatically have an associated module. When you click Code [image] on the toolbar to view the form's or report's module, the module is created. You can also create the module from Visual Basic by referring to the form's Module property while the form or report is in Design view, or by setting the HasModule property to True (–1).

The setting of the HasModule property indicates whether a form or report currently has an associated module.

Since a form or report module isn't created until you need to add code to it, your project may have fewer modules to compile, resulting in improved compilation performance. Also, forms and reports without modules load more quickly than those with modules.

Compiling on Demand

It's a good idea to explicitly compile the modules in your project by using the commands described above, but it's not necessary. Microsoft Access compiles a module before running a procedure in it if the module hasn't already been compiled.

When a module is loaded for execution, Microsoft Access checks to see whether the module has already been compiled. If not, Microsoft Access compiles the module immediately prior to executing a procedure within it. The process of compiling slows down your code, so code in modules that have been saved in a compiled state will run faster.

Note that in Microsoft Access 95, when you run a procedure in one module, all modules in the potential call tree are loaded, although by default they aren't compiled until a procedure within them is called. Because Microsoft Access 97and Access 2000 load modules on a need-only basis, your code may run faster in many cases.

You can further enhance performance by grouping procedures in modules to reduce unnecessary compilations. Group procedures in modules with other procedures that they call, as opposed to grouping them in modules with unrelated procedures.


 Macro Actions and Methods of the DoCmd Object

Macro Actions and Methods of the DoCmd Object

To carry out macro actions from code in Microsoft Access 2000, use the DoCmd object and its methods. This object replaces the DoCmd statement that you used in versions 1.x and 2.0 of Microsoft Access to carry out a macro action.

When you convert a database, Microsoft Access automatically converts any DoCmd statements and the actions that they carried out in your Access Basic code to methods of the DoCmd object by replacing the space with the . (dot) operator.

Some macro actions work differently in Microsoft Access 2000 than in version 1.x, 2.0, or 7.0; these differences are detailed below.

Databases Created with Microsoft Access 95

The DoMenuItem Action

The DoMenuItem action is no longer used in Microsoft Access 2000. The new RunCommand action can be used to accomplish the tasks for which you used to use the DoMenuItem action.

When you enable a database created with a prior version of Microsoft Access, the DoMenuItem action will continue to work as it did before.

When you convert a database created with a prior version of Microsoft Access, all DoMenuItem actions in macros are replaced with RunCommand actions the first time that the macros are saved after conversion. DoMenuItem methods used in Visual Basic procedures aren't changed.

Databases Created with Microsoft Access Version 1.x or 2.0

The TransferSpreadsheet Action

Microsoft Access 2000 can't import Microsoft Excel version 2.0 spreadsheets or Lotus 1-2-3 version 1.0 spreadsheets. If your converted database contains a macro that provided this functionality by using the TransferSpreadsheet action in Microsoft Access version 1.x or 2.0, converting the database will change the Spreadsheet Type argument to Microsoft Excel version 3.0 (if you originally specified Microsoft Excel version 2.0), or causes an error if you originally specified Lotus 1-2-3 version 1.0 format.

To work around this problem, convert the spreadsheets to a later version of Microsoft Excel or Lotus 1-2-3 before importing them into Microsoft Access.

The TransferText and TransferSpreadsheet Actions

In Microsoft Access 2000, you can't use a SQL statement to specify data to export when you're using the TransferText action or the TransferSpreadsheet action. Instead of using a SQL statement, you must first create a query and then specify the name of the query in the Table Name argument.

Comparisons Involving Null Values

In Microsoft Access versions 1.x and 2.0, if you compare two expressions within a macro condition by using a comparison operator and one of the expressions is Null, Access Basic will return True or False for the comparison, depending on which comparison operator you use. In Microsoft Access 2000, Visual Basic returns Null for a comparison in which one expression is Null. To determine whether the comparison evaluates to Null, use the IsNull function to check the result of the comparison.


 Using Enumerated Constants in Microsoft Access 2000

Using Enumerated Constants in Microsoft Access 2000

In Microsoft Access 2000, a number of intrinsic constants have been added or changed. This was done to create lists of "enumerated" constants that are displayed in the Auto List Members list in the Module window for the arguments of various Microsoft Access methods, functions, and properties, or as the setting of various Microsoft Access properties. You can select the appropriate constant from the list in the Module window, instead of having to remember the constant or look it up in the Help topic.

The following information applies to enumerated constants:

  • The set of enumerated constants for each method, function, or property argument has a name, which is displayed in the syntax line for the method, function, or property in the Module window when the Auto Quick Info option is selected in the Editor tab of the Options dialog box, available by clicking Options on the Tool menu. (For property settings, the name isn't displayed, just the list of constants.) For example, the syntax line for the OpenForm method of the DoCmd object shows [View as AcFormView = acNormal] for the view argument of this method. AcFormView is the name of this set of enumerated constants, and acNormal is the default setting for the argument. The Object Browser also lists the names of the sets of enumerated constants in the Classes box and lists the intrinsic constants contained in each of these sets in the Members box.

  • For constant names that have changed, the old constants will still work. For example, one of the intrinsic constants for the save argument of the Close method of the DoCmd object was acPrompt. It's now acSavePrompt, but acPrompt will still work.

  • In a number of cases in previous versions of Microsoft Access, you could leave an argument setting blank, and Microsoft Access would perform the default action for that argument. For example, you could leave the objecttype (and objectname) arguments of the Close method blank, and Microsoft Access would close the active window. For the new sets of enumerated constants, the blank setting has been replaced with a new default constant. For example, the objecttype argument of the Close method now has a new default constant, acDefault. Setting this argument to the new constant has the same effect as leaving the argument blank. In addition, you can still leave such arguments blank, and Microsoft Access will assume the new default constant.

  • There's one exception to this. If you run Visual Basic code from previous versions of Visual Basic in Microsoft Access by using Automation, blank arguments will cause an error for those arguments that have the new default constants. This problem doesn't occur for old Visual Basic for Applications or Visual Basic code run directly in Microsoft Access.

The following table lists all the intrinsic constants that have been added or changed in order to create enumerated constant lists in Microsoft Access 2000.

Language element | Argument | Old constant | New constant
Close method | objecttype | (none) | acDataAccessPage acDiagram acServerView acStoredProcedure
CopyObject method | sourceobjecttype | (none) | acDataAccessPage acDiagram acServerView acStoredProcedure
DeleteObject method | objecttype | (none) | acDataAccessPage acDiagram acServerView acStoredProcedure
OpenDataAccessPage method | view | (none) | acDataAccessPageBrowse acDataAccessPageDesign
OutputTo method | objecttype | (none) | acOutputDataAccessPage acOutputServerView acOutputStoredProcedure
Rename method | objecttype | (none) | acDataAccessPage acDiagram acServerView acStoredProcedure
RepaintObject method | objecttype | (none) | acDataAccessPage acDiagram acServerView acStoredProcedure
RunCommand method | command | (none) | acCmdDataAccessPageBrowse acCmdDataAccessPageDesignView acCmdDiagramAddRelatedTables acCmdDiagramAutosizeSelectedTables acCmdDiagramDeleteRelationship acCmdDiagramLayoutDiagram acCmdDiagramLayoutSelection acCmdDiagramModifyUserDefinedView acCmdDiagramNewLabel acCmdDiagramNewTable acCmdDiagramRecalculatePageBreaks acCmdDiagramRelationshipLabels acCmdDiagramViewPageBreaks acCmdEditTriggers acCmdHidePane acCmdMicrosoftScriptEditor acCmdNewObjectAutoDataAccessPage acCmdNewObjectDataAccessPage acCmdNewObjectDiagram acCmdNewObjectStoredProcedure acCmdNewObjectView acCmdQueryAddToOutput acCmdSelectDataAccessPage acCmdShowPaneDiagram acCmdShowPaneGrid acCmdShowPaneView acCmdViewDataAccessPages acCmdViewDiagrams acCmdViewFieldList acCmdViewStoredProcedures acCmdViewTableColumnNames acCmdViewTableColumnProperties acCmdViewTableKeys acCmdViewTableNameOnly acCmdViewTableUserView acCmdViewViewVerifySQL acCmdViewViewViews acCmdZoomSelection
Save method | objecttype | (none) | acDataAccessPage acDiagram acServerView acStoredProcedure
SelectObject method | objecttype | (none) | acDataAccessPage acDiagram acServerView acStoredProcedure
SendObject method | objecttype | (none) | acSendDataAccessPage
TransferDatabase method method | objecttype | (none) | acDataAccessPage acDiagram acServerView acStoredProcedure


 Comparison of Data Types

Comparison of Data Types

The Microsoft Jet database engine recognizes several overlapping sets of data types. In Microsoft Access, there are four different contexts in which you may need to specify a data type — in table Design view, in the Query Parameters dialog box, in Visual Basic, and in SQL view in a query.

The following table compares the five sets of data types that correspond to each context. The first column lists the Type property settings available in table Design view and the five FieldSize property settings for the Number data type. The second column lists the corresponding query parameter data types available for designing parameter queries in the Query Parameters dialog box. The third column lists the corresponding Visual Basic data types. The fourth column lists DAO Field object data types. The fifth column lists the corresponding Jet database engine SQL data types defined by the Jet database engine along with their valid synonyms.

Table fields | Query parameters | Visual Basic | ADO Data Type property constants | Microsoft Jet database engine SQL and synonyms
Not supported | Binary | Not supported | adBinary | BINARY (See Notes) (Synonym: VARBINARY)
Yes/No | Yes/No | Boolean | adBoolean | BOOLEAN (Synonyms: BIT, LOGICAL, LOGICAL1, YESNO)
Number (FieldSize = Byte) | Byte | Byte | adUnsignedTinyInt | BYTE (Synonym: INTEGER1)
AutoNumber (FieldSize= Long Integer) | Long Integer | Long | adInteger | COUNTER (Synonym: AUTOINCREMENT)
Currency | Currency | Currency | adCurrency | CURRENCY (Synonym: MONEY)
Date/Time | Date/Time | Date | adDate | DATETIME (Synonyms: DATE, TIME, TIMESTAMP)
Number (FieldSize = Double) | Double | Double | adDouble | DOUBLE (Synonyms: FLOAT, FLOAT8, IEEEDOUBLE, NUMBER, NUMERIC)
AutoNumber /GUID (FieldSize = Replication ID) | Replication ID | Not supported | adGUID | GUID
Number (FieldSize = Long Integer) | Long Integer | Long | adInteger | LONG (See Notes) (Synonyms: INT, INTEGER, INTEGER4)
OLE Object | OLE Object | String | adLongVarBinary | LONGBINARY (Synonyms: GENERAL, OLEOBJECT)
Memo | Memo | String | adLongVarWChar | LONGTEXT (Synonyms: LONGCHAR, MEMO, NOTE)
Number (FieldSize = Single) | Single | Single | adSingle | SINGLE (Synonyms: FLOAT4, IEEESINGLE, REAL)
Number (FieldSize = Integer) | Integer | Integer | adSmallInt | SHORT (See Notes) (Synonyms: INTEGER2, SMALLINT)
Text | Text | String | adVarWChar | TEXT (Synonyms: ALPHANUMERIC, CHAR, CHARACTER, STRING, VARCHAR)
Hyperlink | Memo | String | adLongVarWChar | LONGTEXT (Synonyms: LONGCHAR, MEMO, NOTE)
Not supported | Value | Variant | adVariant | VALUE (See Notes)

Notes

  • Microsoft Access itself doesn't use the BINARY data type. It's recognized only for use in queries on linked tables from other database products that support the BINARY data type.

  • The INTEGER data type in Jet database engine SQL doesn't correspond to the Integer data type for table fields, query parameters, or Visual Basic. Instead, in SQL, the INTEGER data type corresponds to a Long Integer data type for table fields and query parameters and to a Long data type in Visual Basic.

  • The VALUE reserved word doesn't represent a data type defined by the Jet database engine. However, in Microsoft Access or SQL queries, the VALUE reserved word can be considered a valid synonym for the Visual Basic Variant data type.

  • If you are setting the data type for a DAO object in Visual Basic code, you must set the object's Type property.


 Call Procedures in a Subform or Subreport

Call Procedures in a Subform or Subreport

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

In the Orders Subform class module enter:

Function GetProductID()
    ‘Return current productID
    GetProductID = ProductID
End Function
Forms!Orders![Orders Subform].Form.GetProductID

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

Dim frm As New [Form_Orders Subform]
frm.GetProductID

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


 Program with Class Modules

Program with Class Modules

In Microsoft Access 2000, there were two types of modules: standard modules and class modules. In Microsoft Access 95, class modules existed only in association with a form or report. In Microsoft Access 97, they also existed on the Modules tab of the Database window.

Creating Custom Objects with Class Modules

You can use a class module to create a definition for a custom object. The name with which you save the class module becomes the name of your custom object. Public Sub and Function procedures that you define within a class module become custom methods of the object. Public Property Let, Property Get, and Property Set procedures become properties of the object.

Once you've defined procedures within the class module, you can create the new object by creating a new instance of the class. To create a new instance of a class, you declare a variable of the type defined by that class. For example, if the name of your class is ABasicClass, you would create a new instance of it in the following manner:

Dim abc As New ABasicClass

When you run the code containing this declaration, Visual Basic creates the new instance. You can then apply its methods and properties by using the variable abc. For example, if you've defined a custom method called ListNames, you could apply it as follows:

abc.ListNames

New in Microsoft Access 95: Creating the Default Instance of a Form Class

When you open a form in Form view, whether from the user interface or from Visual Basic, you create an instance of that form's class module. In other words, you designate space in memory where the object now exists, and you can then call its methods and set or return its properties from code, as you would for any built-in object. The same is true when you open a report in Print Preview.

When you refer to a form in Visual Basic code, you're usually working with the default instance of the form's class. A form's class has only one default instance. You can also create multiple instances of the same form's class from Visual Basic. When you create multiple instances of a form's class, you create nondefault instances.

There are four ways to create the default instance of a form. You can open an existing form by using the user interface, by executing the OpenForm method of the DoCmd object, by calling the CreateForm method and switching the new form into Form view, or by using Visual Basic to create a variable of type Form to refer to the default instance. The following example opens an Employees form and points a Form object variable to it:

Dim frm As Form
DoCmd.OpenForm "Employees"
Set frm = Forms!Employees

Microsoft Access also provides a shortcut that enables you to open a form and refer to a method or property of that form or one of its controls in one step. You refer to the form's class module as shown in the following example:

Form_Employees.Visible = True
Form_Employees.Caption = "New Employees"

When you run this code, Microsoft Access opens the Employees form in Form view if it's not already open and sets the form's caption to "New Employees." The form isn't visible until you explicitly set its Visible property to True (–1). When the procedure that calls this code has finished executing, this instance of the form is destroyed — that is, the form is closed.

If you try to run this code when the Employees form is open in Design view, Microsoft Access generates a run-time error. The form must either be open in Form view or not open at all.

If you use this syntax to change a property of the form or one of its controls, that change is lost when the instance of the form is destroyed. This holds true any time you change a property setting for a form in Form view. You must change the property in Design view and save the change with the form.

Creating Multiple Nondefault Instances of Forms

You can create multiple nondefault instances of a form's class if you want to display more than one instance of a form at a time. For example, you might want to display the records for an employee and the employee's manager at the same time. You can create one instance of the Employees form's class to display the employee's record, and one to display the manager's record.

To create new, nondefault instances of a form's class from Visual Basic, declare a variable for which the type is the name of the form class module. You must include the New keyword in the variable declaration. For example, the following code creates a new instance of the Employees form and assigns it to a variable of type Form:

Dim frm As New Form_Employees

This nondefault instance of the form isn't visible until you explicitly set its Visible property.

When the procedure that creates this instance has finished executing, the instance is removed from memory unless you've declared the variable representing it as a module-level variable. Since module-level variables retain their values until they are reset with the Reset command on the Run menu or the Reset button [image] on the toolbar, the form will stay open if the variable has been declared as a module-level variable.

Any properties that you set will affect this instance of the form's class, but won't be saved with the form. Also, a new instance of the form's class can't be created if the form is open in Design view.

A nondefault instance of a form's class can't be referred to by name in the Forms collection. You can refer to it by index number only. Since you can create multiple nondefault instances of a form, and each instance has the same name, you can have more than one form with the same name in the Forms collection, without any means of distinguishing them other than by index number.


 Option Private Module not permitted in Class module

Option Private Module not permitted in Class module

Microsoft Access form modules and report modules are class modules. You can't include an Option Private Module statement within a form or report module.


 Set References to Type Libraries

Set References to Type Libraries

When you set a reference to another application's type library, you can use the objects supplied by that application in your code. For example, if you set a reference from Microsoft Access to the Microsoft Excel library, you can then use Microsoft Excel objects through Automation (formerly called OLE Automation). If you set a reference to a Visual Basic project in another Microsoft Access database, you can call its public procedures. If you set a reference to an ActiveX control, you can use that control on Microsoft Access forms.

You can set a reference from Microsoft Access while the Microsoft Visual Basic Editor is open, or you can set a reference in Visual Basic code.

Setting a Reference from Microsoft Access

To set a reference to an application's type library:

  1. On the Tools menu, click References. The References command on the Tools menu is available only when a Module window is open and active in Design view.

  2. Select the check boxes for those applications whose type libraries you want to reference.

Setting a Reference from Visual Basic

To set a reference from Visual Basic, you create a new Reference object representing the desired reference. The References collection contains all currently set references.

To create a new Reference object, use either the AddFromFile or AddFromGUID method of the References collection. To remove a Reference object, use the Remove method.

Advantages of Setting References

Your Automation code will run faster if you set a reference to another application's type library before you work with its objects. If you've set a reference, you can declare an object variable representing an object in the other application as its most specific type. For example, if you're writing code to work with Microsoft Excel objects, you can declare an object variable of type Excel.Application by using the following syntax only if you've created a reference to the Microsoft Excel type library:

Dim appXL As New Excel.Application

If you haven't set a reference to the Microsoft Excel type library, you must declare the variable as a generic variable of type Object. The following code runs more slowly:

Dim appXL As Object

Additionally, if you set a reference to an application's type library, all of its objects, as well as their methods and properties, are listed in the Object Browser. This makes it easy to determine what properties and methods are available to each object.

Since Microsoft Access is an COM component that supports Automation, you can also set a reference to its type library from another application and work with Microsoft Access objects from that application.


 Set a Reference to a Visual Basic Project in Another Microsoft Access Database or Project

Set a Reference to a Visual Basic Project in Another Microsoft Access Database or Project

Each Microsoft Access database (.mdb or .adp) includes a Visual Basic project. The Visual Basic project is the set of all modules in the project, including both standard modules and class modules. Every Microsoft Access database (.mdb or .adp), library database, or add-in contained in an .mde file includes a Visual Basic project.

The name of the Access database and the name of the project can differ. The name of the Access database is determined by the name of the .mdb (or .mda or .mde) or .adp file, while the name of the project is determined by the setting of the Project Name option on the Advanced tab of the Options dialog box, available by clicking Options on the Tools menu. When you first create a database (.mdb or .adp), the database name and project name are the same by default. However, if you rename the database, the project name doesn't automatically change. Likewise, changing the project name has no effect on the database name.

You can set a reference from a Visual Basic project in one Microsoft Access database to a project in another Microsoft Access database, a library database, or an add-in contained in an .mde file. Once you've set a reference, you can run Visual Basic procedures in the referenced project. For example, the Northwind sample database includes a module named Utility Functions that contains a function called IsLoaded. You can set a reference to the project in the Northwind sample database from the project in the current database, and then call the IsLoaded function just as you would if it were defined within the current database.

To set a reference to the project in the Northwind sample database from another project:

  1. Open the Module window.

  2. On the Tools menu, click References, and click Browse in the References dialog box.

  3. In the Files Of Type box, click Microsoft Access Databases (*.mdb).

  4. Locate the Northwind.mdb file. If you've installed this file, it will be in the \Program Files\Microsoft Office\Office\Samples folder by default.

  5. Click OK.

You should now see "Northwind.mdb" in the list of available references in the References dialog box.

Notes

  • Set a reference to the project in another Microsoft Access database when you want to call a public procedure that's defined within a standard module in that database. You can't call procedures that are defined within a class module or procedures in a standard module that are preceded with the Private keyword.

  • You can set a reference to the project in a Microsoft Access database only from another Microsoft Access database.

  • You can set a reference to a project only in another Microsoft Access 2000 database. To set a reference to a project in a database created in a previous version of Microsoft Access, first convert that database to Microsoft Access 2000.

  • If you set a reference to a project or type library from Microsoft Access and then move the file that contains that project or type library to a different folder, Microsoft Access will attempt to locate the file and reestablish the reference. If the RefLibPaths key exists in the registry, Microsoft Access will first search there. If there's no matching entry, Microsoft Access will search for the file first in the current folder, then in all the folders on the drive. You can create the RefLibPaths key by using the Registry Editor in Windows, under the registry key \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\9.0\Access. For more information about using the Registry Editor, see your Windows documentation.


 Set Form, Report, and Control Properties

Set Form, Report, and Control Properties

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

To set properties

  1. In form Design view or report Design view, select the control, section, form, or report for which you want to set the property. You can select:
    • One or more controls. To select multiple controls, hold down the SHIFT key and click the controls, or drag the mouse pointer over the controls you wish to select. If you select multiple controls, the property sheet will display only those properties that the selected controls have in common.

    • One section. Click the section selector of the section you wish to select.

    • The entire form or report. Click the form selector or report selector in the upper-left corner of the form or report.
  2. Display the property sheet by right-clicking the object or section and then clicking Properties on the shortcut menu, or by clicking Properties [image] on the toolbar.

  3. Click the property for which you want to set the value, and then do one of the following:
    • In the property box, type the appropriate setting or expression.

    • If the property box contains an arrow, click the arrow and then click a value in the list.

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

If the property sheet is blank or if you don't see the properties you expect in the property sheet, see Troubleshoot property sheets.

Tips

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

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

  • You can change the default property settings for a type of control so that future controls you create will have the new default settings.

  • The property settings of a bound control might not match the corresponding settings in the field in the underlying table or query to which the control is bound. If the settings are different, the form or report settings typically override those in the table or query. For more information about how properties are inherited, see How control properties relate to properties in their underlying fields.


Set Properties by Using Visual Basic

You can set most properties from Visual Basic code. How you set a property depends on whether you are setting it for a Form, Report, or Control object, an ActiveX Data Object (ADO), a Data Access Object (DAO), or for a DataAccessPage object. The following topics outline the steps involved for setting properties of each type of object:

Set Form, Report, and Control Properties in Visual Basic

Set Properties of ActiveX Data Objects in Visual Basic

Set Properties of Data Access Objects in Visual Basic

Set Properties of Data Access Pages in Visual Basic


 Set Properties by Using Macros

Set Properties by Using Macros

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

You can't use a macro to set properties of other Microsoft Access objects or ActiveX Data Objects (ADO), or to set the default properties of a control, but you can set them either by using Visual Basic or an object's property sheet in Design view.

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

  1. In a macro, add a SetValue action.

  2. Set the Item action argument of the SetValue action to an expression that refers to the property you want to set:
    • To set a form or report property, use the syntax Forms!formname.propertyname or Reports!reportname.propertyname. For example, the following expression refers to the Visible property of the Customers form:
      Forms!Customers.Visible
    • To set a property of a control on a form or report, use the syntax Forms!formname!controlname.propertyname or Reports!reportname!controlname.propertyname. For example, the following expression refers to the Visible property of the HiddenPageBreak control on the Invoices report:
      Reports!Invoices!HiddenPageBreak.Visible

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

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

To set a section property by using a macro

  1. In a macro, add a SetValue action.

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

Note For each property you want to set, you can look up the property in the Help index to find information about:

  • Whether you can set the property from a macro.

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

  • Which values you can use to set the property. Some properties require settings that don't correspond to values in the property sheet but to numeric values. You may need to set the property by using the settings you would use in Visual Basic rather than those you would use in the property sheet. For example, if the property settings are selections from a list, you must use the value or numeric equivalent for each selection.


 Set Data Access Page and Control Properties

Set Data Access Page and Control Properties

Each data access page, section, and its control have property settings that you can change to alter the look or behavior of that particular item. You view and change properties by using the property sheet, or the Microsoft Visual Script Editor.

To set properties

  1. In page Design view, select the data access page, section, or control for which you want to set the property. You can select:
    • A control. Click the control you wish to select.

    • One section. Click the section selector of the section you wish to select.

    • The entire data access page. Click the data access page title bar.
  2. Display the property sheet by selecting the object and clicking Properties [image] on the toolbar. For sections and controls, you can right-click the section or control and then click Properties on the shortcut menu.

  3. Click the property for which you want to set the value, and then do one of the following:
    • In the property box, type the appropriate setting or expression.

    • If the property box contains an arrow, click the arrow and then click a value in the list.

If the property sheet is blank or if you don't see the properties you expect in the property sheet, see Troubleshoot property sheets.

Tips

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

  • The property settings of a bound control might not match the corresponding settings in the field in the underlying table, query, or view to which the control is bound. If the settings are different, the form or report settings typically override those in the table, query, or view. For more information about how properties are inherited, see How control properties relate to properties in their underlying fields.


Set Startup Properties and Options in Code

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

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

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

Set Startup Properties from Visual Basic

Set Options from Visual Basic


 Startup Properties Within New Projects and Databases

Startup Properties Within New Projects and Databases

When you create a new Microsoft Access project (.adp) or Microsoft Access database (.mdb), Microsoft Access adds a set of properties to the project's AccessObjectProperties collection or a database's Properties collection.

  • In a Access project, the following properties are added to the CurrentProject object.

    Build AccessVersion

    You access these properties using the following syntax.

    CurrentProject.Properties("propertyname").Value

  • In a Access database, the following properties are added to the Database object.

    Name | RecordsAffected
    Connect | ReplicaID
    Transactions | DesignMasterID
    Updatable | Connection
    CollatingOrder | AccessVersion
    QueryTimeout | Build
    Version

    You access these properties using the following syntax.

    CurrentDB.Properties("propertyname").Value

When you set a startup property in a project or database through the Startup dialog box, available by clicking Startup on the Tools menu, Microsoft Access adds a set of startup properties to the appropriate Properties collection. These properties are not added when a startup property is added programatically.

  • In a Access project, a subset of the following startup properties are added to the CurrentProject object. The set of startup properties varies depending on the startup property set through the Startup dialog box.

    AppTitle | AllowBuiltinToolbars
    StartupForm | AllowToolbarChanges
    StartupShowDBWindow | AllowBreakIntoCode
    StartupShowStatusbar | AllowSpecialKeys
    StartupMenubar | AppIcon
    AllowShortcutMenus | StartupShortcutMenubar
    AllowFullMenus | HijriCalendar

  • In a Access database, a subset of the following startup properties are added to the Database object. The set of startup properties varies depending on the startup property set through the Startup dialog box.

    AppTitle | AllowBuiltinToolbars
    StartupForm | AllowToolbarChanges
    StartupShowDBWindow | AllowBreakIntoCode
    StartupShowStatusbar | AllowSpecialKeys
    StartupMenubar | AppIcon
    AllowShortcutMenus | StartupShortcutMenubar
    AllowFullMenus | HijriCalendar


 Date and Time Criteria Expressions

Date and Time Criteria Expressions

To specify date or time criteria for an operation, you supply a date or time value as part of the string expression that forms the criteria argument. This value must be enclosed in number signs (#).

Note The number signs indicate to Microsoft Access that the criteria argument contains a date or time within a string.

Suppose that you are creating a filter for an Employees form to display records for all employees born on or after January 1, 1960. You could construct the criteria argument for the form's Filter or ServerFilter property as in the following example. Note the placement of the number signs.

Forms!Employees.Filter = "[BirthDate] >= #1-1-60#"


 Date and Time Criteria from a Control on a Form

Date and Time Criteria from a Control on a Form

If you want to change the criteria argument for an operation based on a user's decision, you can specify that the criteria comes from a control on a form. For example, you could specify that the criteria argument comes from a list box containing order dates from an Orders table.

To specify date and time criteria that comes from a control on a form, you include in the criteria argument an expression that references the control on the form. This expression should be separate from the string expression, so that Microsoft Access will evaluate the control expression first and concatenate it with the rest of the string expression before performing the appropriate operation.

In addition to enclosing the entire string expression in double quotation marks ("), you must also ensure that the date or time criteria within the string expression is enclosed in number signs (#). The number signs must be included in the strings flanking the expression that references the control on the form.

Note The number signs indicate to Microsoft Access that the criteria argument contains a date or time within a string.

The following examples set a form's Filter or ServerFilter property based on criteria that comes from a control named HireDate that's on the form. Note the placement of the number signs.

Forms!Employees.Filter = "[HireDate] >= #" _
 &     Forms!Employees!HireDate & "#"
Forms!Employees.FilterOn = True

– or –

Forms!Employees.ServerFilter = "[HireDate] >= #" _
 &     Forms!Employees!HireDate & "#"
Forms!Employees.FilterOn = True

If the current value of the HireDate control is 5-1-92, the Filter or ServerFilter property will have the following criteria argument:

"[HireDate] >= #5-1-92#"

Tip To troubleshoot an expression in the criteria argument, break the expression into smaller components and test each individually in the Immediate window. When all of the components are working correctly, put them back together one at a time until the complete expression works correctly.

You can also include a variable representing a date or time in the criteria argument. The variable should be separate from the string expression, so that Microsoft Access will evaluate the variable first and then concatenate it with the rest of the string expression. The date or time criteria must be enclosed in number signs.

The following example shows how to construct a criteria argument that includes a variable representing a date or time:

Dim datHireDate As Date
datHireDate = #5-1-92#
Forms!Employees.Filter = "[HireDate] >= #" _
 &     datHireDate & "#"


 Multiple Fields in Criteria Expressions

Multiple Fields in Criteria Expressions

You can specify multiple fields in a criteria argument.

To specify multiple fields in the criteria argument, you must ensure that multiple string expressions are concatenated correctly to form a valid SQL WHERE clause. In an SQL WHERE clause with multiple fields, fields may be joined with one of three keywords: AND, OR, or NOT. Your expression must evaluate to a string that includes one of these keywords.

For example, suppose that you wish to set the Filter property of an Employees form to display records restricted by two sets of criteria. The following example filters the form so that it displays only those employees whose title is "Sales Representative" and who were hired since January 1, 1993:

Dim datHireDate As Date, strTitle As String
datHireDate = #1/1/93#
strTitle = "Sales Representative"
Forms!Employees.Filter = "[HireDate] >= #" & _
    datHireDate & "# AND [Title] = '" & strTitle & "'"
Forms!Employees.FilterOn = True

The criteria argument evaluates to the following string:

"[HireDate] >= #1-1-93# AND [Title] = 'Sales Representative'"

Tip To troubleshoot an expression in the criteria argument, break the expression into smaller components and test each individually in the Immediate window. When all of the components are working correctly, put them back together one at a time until the complete expression works correctly.


 Numeric Criteria Expressions

Numeric Criteria Expressions

To specify numeric criteria for an operation, you supply a numeric value as part of the string expression that forms the criteria argument.

Suppose that you are performing the DLookup function on an Employees table to find the last name of a particular employee, and you want to use a value from the EmployeeID field in the function's criteria argument. You could construct a criteria argument like the following example, which returns the last name of the employee whose EmployeeID is 7:

=DLookup("[LastName]", "Employees", "[EmployeeID] = 7")


 Numeric Criteria from a Control on a Form

Numeric Criteria from a Control on a Form

If you want to change the criteria argument for an operation based on a user's decision, you can specify that the criteria comes from a control on a form. For example, you could specify that the criteria argument comes from a text box containing the EmployeeID number.

To specify numeric criteria coming from a control on a form, you can include in the criteria argument an expression that references that control. This control expression should be separate from the string expression, so that Microsoft Access will evaluate control expression first and concatenate it with the rest of the string expression before performing the appropriate operation.

Suppose that you are performing the DLookup function on an Employees table to find the last name of an employee based on the EmployeeID number. In the following example, the criteria is determined by the current value of the EmployeeID control on the Orders form. The expression referencing the control is evaluated each time the function is called, so that if the value of the control changes, the criteria argument will reflect that change.

=DLookup("[LastName]", "Employees", "[EmployeeID] = " _
    & Forms!Orders!EmployeeID)

If the current value of the EmployeeID field is 7, the criteria argument that is passed to the DLookup function is:

"[EmployeeID] = 7"

Tip To troubleshoot an expression in the criteria argument, break the expression into smaller components and test each individually in the Immediate window. When all of the components are working correctly, put them back together one at a time until the complete expression works correctly.

You can also include a variable representing a numeric value in the criteria argument. The variable should be separate from the string expression, so that Microsoft Access will evaluate the variable first and then concatenate it with the rest of the string expression.

The following example shows how to construct a criteria argument that includes a variable:

Dim intNum As Integer, varResult As Variant
intNum = 7
varResult = DLookup("[LastName]", "Employees", _
    "[EmployeeID] = " & intNum)


 Textual Criteria Expressions

Textual Criteria Expressions

To specify textual criteria for an operation, you supply a text string as part of the string expression that forms the criteria argument. This text string must be enclosed in single quotation marks (').

Note The single quotation marks indicate to Microsoft Access that the criteria argument contains a string within a string.

Suppose that you are using the ADO Find method to find the first occurrence of a last name in an Employees table. You could construct the criteria argument as in the following example, which moves the current record pointer to the first record in which an employee's last name is Buchanan. Note that the string literal Buchanan is enclosed in single quotation marks and the entire string comprising the criteria argument must also be enclosed in double quotation marks (").

Dim rs As New ADODB.Connection

rs.open "Employees", CurrentProject.Connection,_
     dbOpenDynaset, adlockoptimistic)
rs.Find "[LastName] = 'Buchanan'"


 Textual Criteria from a Control on a Form

Textual Criteria from a Control on a Form

If you want to change the criteria argument for an operation based on a user's decision, you can specify that the criteria comes from a control on a form. For example, you could specify that the criteria argument comes from a list box containing the last names of all employees in an Employees table.

To specify textual criteria coming from a control on a form, you include in the criteria argument an expression that references the control on the form. This expression should be separate from the string expression, so that Microsoft Access will evaluate the control expression first and concatenate it with the rest of the string expression before performing the appropriate operation.

In addition to enclosing the entire string expression in double quotation marks ("), you must also ensure that the textual criteria within the string expression is enclosed in single quotation marks ('). The quotation marks must be included in the strings flanking the expression that references the control on the form.

Note The single quotation marks indicate to Microsoft Access that the criteria argument contains a string within a string.

The following example performs a lookup on an Employees table and returns the region in which an employee lives, based on the employee's last name. The current value of a list box control called LastName on the Employees form determines the criteria. Note the placement of the single quotation marks.

=DLookup("[Region]", "Employees", "[LastName] = '" _
    & Forms!Employees!LastName & "'")

If the current value of the control is King, the following criteria argument is passed to the DLookup function after Microsoft Access evaluates the expression and concatenates the strings:

"[LastName] = 'King'"

Keep in mind that the entire string comprising the criteria argument must also be enclosed in double quotation marks once the strings have been concatenated.

Tip To troubleshoot an expression in the criteria argument, break the expression into smaller components and test each individually in the Immediate window. When all of the components are working correctly, put them back together one at a time until the complete expression works correctly.

You can also include a variable representing a textual string in the criteria argument. The variable should be separate from the string expression, so that Microsoft Access will evaluate the variable first and then concatenate it with the rest of the string expression. The textual string must be enclosed in single or double quotation marks.

The following example shows how to construct a criteria argument that includes a variable representing a textual string:

Dim strLastName As String, varResult As Variant
strLastName = "King"
varResult = DLookup("[EmployeeID]", "Employees", "[LastName] = '" _
    & strLastName & "'")


Differences in String Function Operations

Language-specific information

The memory storage formats for text are different in Visual Basic for Microsoft Access 7.0 and Access Basic of previous versions of Microsoft Access. Text is stored in ANSI format within Access Basic code, and in Unicode format in Visual Basic.

The Unicode format is used in Visual Basic to match the format of text within OLE, which is indirectly related to Visual Basic.

For example, the text string "ABC [image] [image] [image] " would be stored in memory as shown below.

Storage format | Storage pattern | Description
Unicode | 41 00 42 00 43 00 42 30 44 30 46 30 | Each character is stored as 2 bytes.
ANSI | 41 42 43 82 A0 82 A2 82 A4 | ASCII characters are stored as 1 byte; Japanese characters are stored as 2 bytes.

Because of these differences in internal format, there are string processing functions that operate differently in Access Basic and Visual Basic. The functions that operate differently and their statements are as shown below.

Asc function, Chr function, InputB function, InStrB function, LeftB function, LenB function, RightB function, MidB function, and their corresponding statements.

Also, the ChrB function and AscB function have been added to Visual Basic.

In that these functions and statements both process text in byte units, they are the same in Access Basic and Visual Basic, but because their storage formats for text are different, they operate differently. For example, in LenB("A") would be 1 in Access Basic, but 2 in Visual Basic.

Programs created in previous versions of Microsoft Access that use the string processing functions that work in byte units must be changed in Visual Basic to a source code that recognizes Unicode. However, if only string processing functions that process character units, such as the Len function, Left function, and Right function, are used, there is no need to recognize them.

If programs created in a previous version of Microsoft Access are moved to Microsoft Access 7.0, consider the following points regarding string processing.

Asc Function and AscB Function

This program ran properly in previous versions of Access, but produces a run-time error in Visual Basic in Microsoft Access 7.0.

Print Asc(MidB("  ", 2,1))

This is because MidB(" [image] ", 2,1), an argument of the Asc function, does not correctly return data to Unicode text.

Use the following AscB function to make this program run in Microsoft Access 7.0:

Print AscB(MidB("  ", 2,1))

In this program, the value (&H30) of the second Unicode byte is returned.

Chr Function and ChrB Function

The Chr function in Microsoft Access 7.0 always returns 2-byte characters. In previous versions of Microsoft Access, Chr(&H41) and ChrB(&H41) were equal, but in Microsoft Access 7.0, Chr(&H41) and ChrB(&H41) + ChrB(0) are equal.

Also, in previous versions of Microsoft Access, " [image] " was expressed as ChrB(&H82) + ChrB(&HA0), but in Microsoft Access 7.0 it is expressed as ChrB(&H42) + ChrB(&H30).

Calling the Windows Application Programming Interface (API)

In several Windows API the byte length of a string has a special meaning. For example, the following program returns a folder set up in Windows. In Microsoft Access 7.0, LeftB(Buffer, ret) does not return the correct string. This is because, in spite of the fact that it shows the byte length of an ANSI string, the LeftB function processes Unicode strings. In this case, use the InStr function so that only the character string, without nulls, is returned.

Private Declare Function GetWindowsDirectory Lib "kernel32" _
    Alias "GetWindowsDirectoryA" (ByVal lpBuffer As String, _
    ByVal nSize As Long) As Long

Private Sub Command1_Click()
    Buffer$ = Space(255)
    ret = GetWindowsDirectory(Buffer$, 255)
    ' WinDir = LeftB(Buffer, ret)   '<--- Incorrect code"

    WinDir = Left(Buffer$, InStr(Buffer$, Chr(0)) - 1)
                                        '<--Correct code"
    Print WinDir
End Sub

Input Function and InputB Function

The Input function in Microsoft Access 7.0 converts the number of characters designated when the text is read from the file into a Unicode string and reads them as variables. The InputB function, on the other hand, assumes the data to be binary data and stores it as variables without converting it. If the InputB function is used when reading a file stored in a fixed length field, the fixed byte length data must be converted once it is read.

Open "Data.Dat" For Input As 1
dat1 = StrConv(InputB(10, 1), vbUnicode)
dat2 = StrConv(InputB(10, 1), vbUnicode)
dat3 = StrConv(InputB(10, 1), vbUnicode)

===DATA.DAT
123456789012345678901234567
Name      Address      Telephone

Processing ANSI string bytes in Microsoft Access 7.0

If it is necessary to process ANSI string bytes in Microsoft Access 7.0, use the StrConv function. You can convert text between ANSI and Unicode by setting the vbUnicode or vbFromUnicode constant. If you process bytes after temporarily converting a string to an ANSI string, and then reconvert it back to Unicode once the process is finished, you can use codes from previous version of Access relatively easily.

'                                                    ANSI
dat = StrConv(dat, vbFromUnicode)
.
.
.    '
.    '
.
.
'                                                     Unicode
dat = StrConv(dat, vbUnicode)

Sample Functions that perform operations that are compatible with byte processing functions of 16-bit versions

In Microsoft Access 7.0's Visual Basic, the internal processing of strings is performed using Unicode. Thus, the binary processing functions are different from those of Access Basic used in previous versions of Microsoft Access.

The ANSI function was created to preserve compatibility between the operations of Access Basic and Visual Basic.

Note Strings input and removed with these ANSI processing functions are always Unicode. After being converted temporarily to ANSI strings within the function, they are restored to Unicode once the process is finished.

The following cannot combine the first and second byte of a DBCS character to create a DBCS character.

AnsiMidB("  ",1,1) + AnsiMidB("  ",2,1)

These functions have been created to process strings in byte units. However, a different character cannot be created by the byte-unit processing. In this case, it would be expressed as follows:

StrArg = "  "
StrArg = StrConv(StrArg, vbFromUnicode)    ' ANSI
RetArg = MidB(StrArg,1,1) + MidB(StrArg,2,1)    '
    '
StrArg = StrConv(StrArg, vbUnicode)    '                Unicode
RetArg = StrConv(RetArg, vbUnicode)    '

Generally, if you convert a string to an ANSI character before processing, you should restore the converted string to a Unicode character after the process is finished.

A byte string process is always a function for processing a string. To process binary data, use a byte Array, not a string variable or a byte string processing function.

A string stored in a byte Array appears as follows:

       Array
Dim Var() As Byte
Var = "            "             ' Unicode
Var = StrConv("            ", vbFromUnicode)    ' ANSI

Function AnsiStrConv(StrArg, flag)
    nsiStrConv = StrConv(StrArg, flag)
End Function

' LenB               ANSI                               Unicode
Function AnsiLenB(ByVal StrArg As String) As Long
    AnsiLenB = LenB(AnsiStrConv(StrArg, vbFromUnicode))
End Function

' MidB                 ANSI                                 Unicode
'
Function AnsiMidB(ByVal StrArg As String, ByVal arg1 As Long, _
            Optional arg2) As String
    If IsMissing(arg2) Then
    AnsiMidB = AnsiStrConv(MidB(AnsiStrConv(StrArg, vbFromUnicode) _
            , arg1),vbUnicode)
    Else
    AnsiMidB = AnsiStrConv(MidB(AnsiStrConv(StrArg, vbFromUnicode) _
            , arg1, arg2), vbUnicode)
    End If
End Function

' LeftB                  ANSI                                 Unicode
Function AnsiLeftB(ByVal StrArg As String, ByVal arg1 As Long) As String
    AnsiLeftB = AnsiStrConv(LeftB(AnsiStrConv(StrArg, _
            vbFromUnicode), arg1), vbUnicode)
End Function

' RightB                 ANSI                                 Unicode
Function AnsiRightB(ByVal StrArg As String, ByVal arg1 As Long) As String
    AnsiRightB = AnsiStrConv(RightB(AnsiStrConv(StrArg, _
            vbFromUnicode), arg1), vbUnicode)
End Function

' InStrB    2                        Ansi             Ansi
Function AnsiInStrB(arg1, arg2, Optional arg3) As Integer
    If IsNumeric(arg1) Then
    pos = LenB(AnsiLeftB(arg2, arg1))
    AnsiInStrB = InStrB(arg1, AnsiStrConv(arg2, vbFromUnicode) _
            , AnsiStrConv(arg3, vbFromUnicode))
    Else
    AnsiInStrB = InStrB(AnsiStrConv(arg1, vbFromUnicode) _
            , AnsiStrConv(arg2, vbFromUnicode))
    End If
End Function

Using byte data type

In Microsoft Access 7.0 Byte data type is added as a new data type. If a string variable is used when processing binary data, text is converted between ANSI and Unicode, and binary data is changed. Thus, when dealing with binary data, use Byte data type variables.

Dim ByteData() As Byte
ByteData = "        "        ' Unicode
ByteData = StrConv("        ", vbFromUnicode)     'ANSI
ByteData = InputB(10, #1)    '
Debug.Print ByteData(5)        '


 Quotation Marks in Strings

Quotation Marks in Strings

In situations where you must construct strings to be concatenated, you may need to embed a string within another string, or a string variable within a string. Situations in which you might need to nest one string within another include:

  • When specifying criteria for domain aggregate functions.

  • When specifying criteria for the Find methods.

  • When specifying criteria for the Filter or ServerFilter property of a form.

  • When building SQL strings.

In all of these instances, Microsoft Access must pass a string to the Microsoft Jet database engine. When you specify a criteria argument for a domain aggregate function, for example, Microsoft Access must evaluate any variables, concatenate them into a string, and then pass the entire string to the Jet database engine.

If you embed a numeric variable, Microsoft Access evaluates the variable and simply concatenates the value into the string. If the variable is a text string, however, the resulting criteria string will contain a string within a string. A string within a string must be identified by string delimiters. Otherwise, the Jet database engine won't be able to determine which part of the string is the value you want to use.

The string delimiters aren't actually part of the variable itself, but they must be included in the string in the criteria argument. There are three different ways to construct the string in the criteria argument. Each method results in a criteria argument that looks like one of the following examples.

"[LastName] = 'Smith'"

– or –

"[LastName] = ""Smith"""

Include Single Quotation Marks

You should include single quotation marks in the criteria argument in such a way that when the value of the variable is concatenated into the string, it will be enclosed within the single quotation marks. For instance, suppose your criteria argument must contain a string variable called strName. You could construct the criteria argument as in the following example:

"[LastName] = '" & strName & "'"

When the variable strName is evaluated and concatenated into the criteria string, the criteria string becomes:

"[LastName] = 'Smith'"

Note This syntax does not permit the use of apostrophes (') within the value of the variable itself. If the value of the string variable includes an apostrophe, Microsoft Access generates a run-time error. If your variable may represent values containing apostrophes, consider using one of the other syntax forms discussed in the following sections.

Include Double Quotation Marks

You should include double quotation marks within the criteria argument in such a way so that when the value of the variable is evaluated, it will be enclosed within the quotation marks. Within a string, you must use two sets of double quotation marks to represent a single set of double quotation marks. You could construct the criteria argument as in the following example:

"[LastName] = """ & strName & """"

When the variable strName is evaluated and concatenated into the criteria argument, each set of two double quotation marks is replaced by one single quotation mark. The criteria argument becomes:

"[LastName] = 'Smith'"

This syntax may appear more complicated than the single quotation mark syntax, but it enables you to embed a string that contains an apostrophe within the criteria argument. It also enables you to nest one or more strings within the embedded string.

Include a Variable Representing Quotation Marks

You can create a string variable that represents double quotation marks, and concatenate this variable into the criteria argument along with the value of the variable. The ANSI representation for double quotation marks is Chr$(34); you could assign this value to a string variable called strQuote. You could then construct the criteria argument as in the following example:

"[LastName] = " & strQuote & strName & strQuote

When the variables are evaluated and concatenated into the criteria argument, the criteria argument becomes:

[LastName] = "Smith"


 Restrict Data to a Subset of Records

Restrict Data to a Subset of Records

When working with records you will often need to restrict your data to a specific set of records. Some procedures take a criteria argument that enables you to specify what data should be returned. For example, you specify the criteria argument to restrict which records are returned when you use domain aggregate functions. You may also specify criteria when you use the Find method of a Recordset object, set the Filter or ServerFilter property of a form, or construct an SQL statement. Although each of these operations involves a different syntax, you construct the criteria expression in a similar manner for each.

For example, you can use the DSum function, a domain aggregate function, to find the sum total of all freight costs in the Orders table. You could create a calculated control by entering the following expression in the ControlSource property:

=DSum("[Freight]", "Orders")

If you specify the optional criteria argument, the DSum function will be performed on a subset of domain. For example, you could find the sum total of all freight costs in the Orders table for only those orders being shipped to California:

=DSum("[Freight]", "Orders", "[ShipRegion] = 'CA'")

When you supply a criteria argument, Microsoft Access first evaluates any expressions included in the argument to form a string expression. Then the string expression is passed to the domain function. The string expression is equivalent to an SQL WHERE clause, without the word WHERE.

You can specify numeric, textual, or date/time criteria. No matter what type of criteria you specify, the criteria argument is always converted to a string before being passed to the domain aggregate function. Therefore, you must make certain that after any expressions have been evaluated, all parts of the argument are concatenated into a single string, the whole of which is enclosed in double quotation marks (").

Use caution when constructing criteria to ensure that the string will be properly concatenated.

The following list of topics outlines the different ways in which you can specify criteria:

Numeric Criteria Expressions

Textual Criteria Expressions

Date and Time Criteria Expressions

Change Numeric Criteria from a Control on a Form

Change Textual Criteria from a Control on a Form

Change Date and Time Criteria from a Control on a Form

Multiple Fields in Criteria Expressions


 Calculate Fields in Domain Aggregate Functions

Calculate Fields in Domain Aggregate Functions

You can use the string expression argument (the expr argument) in a domain aggregate function to perform a calculation on values in a field. For example, you can calculate a percentage (such as a surcharge or sales tax) by dividing a field value by a number.

The following table provides examples of calculations on fields from an Orders table and an Order Details table.

Calculation | Example
Add a number to a field | "[Freight] + 5"
Subtract a number from a field | "[Freight] - 5"
Multiply a field by a number | "[Freight] * 2"
Divide a field by a number | "[Freight] / 2"
Add one field to another | "[UnitsInStock] + [UnitsOnOrder]"
Subtract one field from another | "[ReorderLevel] - [UnitsInStock]"

You would most likely use a domain aggregate function in a macro or module, in a calculated control on a form or report, or in a criteria expression in a query.

For example, you can calculate the average discount amount for all orders in an Order Details table. Multiply the Unit Price and Discount fields to determine the discount for each order, then calculate the average. Enter the following example in a procedure in a module.

Dim dblX As Double
dblX = DAvg("[UnitPrice] * [Discount]", "[Order Details]")


 Build SQL Statements That Include Variables and Controls

Build SQL Statements That Include Variables and Controls

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

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

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

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

Dim dbs As Database, qdf As QueryDef, strSQL As String
Set dbs = CurrentDb
strSQL = "SELECT * FROM Orders WHERE OrderDate >#3-31-96#;"
Set qdf = dbs.CreateQueryDef("SecondQuarter", strSQL)

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

Dim dbs As Database, qdf As QueryDef, strSQL As String
Dim dteStart As Date
dteStart = #3-31-96#
Set dbs = CurrentDb
strSQL = "SELECT * FROM Orders WHERE OrderDate" _
    & "> #" & dteStart & "#;"
Set qdf = dbs.CreateQueryDef("SecondQuarter", strSQL)

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

Dim dbs As Database, qdf As QueryDef, strSQL As String
Set dbs = CurrentDb
strSQL = "SELECT * FROM Orders WHERE OrderDate" _
    & "> #" & Forms!Orders!OrderDate & "#;"
Set qdf = dbs.CreateQueryDef("SecondQuarter", strSQL)


 Use International Date Formats in SQL Statements

Use International Date Formats in SQL Statements

You must use English (United States) date formats in SQL statements in Visual Basic. However, you can use international date formats in the query designgrid.


 Error Trapping

Error Trapping

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

On Error GoTo ErrorHandler

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

Sub CausesAnError()
    ' Direct procedure flow.
    On Error GoTo ErrorHandler
    ' Raise division by zero error.
    Err.Raise 11
    Exit Sub

ErrorHandler:
    ' Display error information.
    MsgBox "Error number " & Err.Number & ": " & Err.Description
    ' Resume with statement following occurrence of error.
    Resume Next
End Sub

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

Notes

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

  • Versions 1.x and 2.0 of Microsoft Access returned only one error for all Automation, (formerly called OLE Automation) errors. The COM component application that generated the error now returns the same error information that you would receive if you were working in that application. You may need to rewrite existing error-handling code to handle new Automation errors properly.

  • If you wish to return the descriptive string associated with a Microsoft Access error or a Data Access Objects (DAO) error, but the error has not actually occurred in your code, you can use the AccessError method to return the string.

For more information about setting error traps and writing error-handling statements, see Chapter 9, "Error Handling and Debugging," in the OPG9TBD. For information about how to obtain the OPG9TBD, click [image] .


 Elements of Run-Time Error Handling

Elements of Run-Time Error Handling

Errors and Error Handling

When you're programming an application, you need to consider what happens when an error occurs. An error can occur in your application for one of two of reasons. First, some condition at the time the application is running makes otherwise valid code fail. For example, if your code attempts to open a table that the user has deleted, an error occurs. Second, your code may contain improper logic that prevents it from doing what you intended. For example, an error occurs if your code attempts to divide a value by zero.

If you've implemented no error handling, then Visual Basic halts execution and displays an error message when an error occurs in your code. The user of your application is likely to be confused and frustrated when this happens. You can forestall many problems by including thorough error-handling routines in your code to handle any error that may occur.

When adding error handling to a procedure, you should consider how the procedure will route execution when an error occurs. The first step in routing execution to an error handler is to enable an error handler by including some form of the On Error statement within the procedure. The On Error statement directs execution in event of an error. If there's no On Error statement, Visual Basic simply halts execution and displays an error message when an error occurs.

When an error occurs in a procedure with an enabled error handler, Visual Basic doesn't display the normal error message. Instead it routes execution to an error handler, if one exists. When execution passes to an enabled error handler, that error handler becomes active. Within the active error handler, you can determine the type of error that occurred and address it in the manner that you choose. Microsoft Access provides three objects that contain information about errors that have occurred, the ADO Error object, the Visual Basic Err object, and the DAO Error object.

For more information about handling errors, see Chapter 8, "Error Handling and Debugging," in the Microsoft Access 2000/Visual Basic Programmer's Guide.

Routing Execution When an Error Occurs

An error handler specifies what happens within a procedure when an error occurs. For example, you may want the procedure to end if a certain error occurs, or you may want to correct the condition that caused the error and resume execution. The On Error and Resume statements determine how execution proceeds in the event of an error.

The On Error Statement

The On Error statement enables or disables an error-handling routine. If an error-handling routine is enabled, execution passes to the error-handling routine when an error occurs.

There are three forms of the On Error statement: On Error GoTo label, On Error GoTo 0, and On Error Resume Next. The On Error GoTo label statement enables an error-handling routine, beginning with the line on which the statement is found. You should enable the error-handling routine before the first line at which an error could occur. When the error handler is active and an error occurs, execution passes to the line specified by the label argument.

The line specified by the label argument should be the beginning of the error-handling routine. For example, the following procedure specifies that if an error occurs, execution passes to the line labeled Error_MayCauseAnError:

Function MayCauseAnError()
    ' Enable error handler.
    On Error GoTo Error_MayCauseAnError
    .            ' Include code here that may generate error.
    .
    .

Error_MayCauseAnError:
    .            ' Include code here to handle error.
    .
    .
End Function

The On Error GoTo 0 statement disables error handling within a procedure. It doesn't specify line 0 as the start of the error-handling code, even if the procedure contains a line numbered 0. If there's no On Error GoTo 0 statement in your code, the error handler is automatically disabled when the procedure has run completely. The On Error GoTo 0 statement resets the properties of the Err object, having the same effect as the Clear method of the Err object.

The On Error Resume Next statement ignores the line that causes an error and routes execution to the line following the line that caused the error. Execution isn't interrupted. You can use the On Error Resume Next statement if you want to check the properties of the Err object immediately after a line at which you anticipate an error will occur, and handle the error within the procedure rather than in an error handler.

The Resume Statement

The Resume statement directs execution back to the body of the procedure from within an error-handling routine. You can include a Resume statement within an error-handling routine if you want execution to continue at a particular point in a procedure. However, a Resume statement isn't necessary; you can also end the procedure after the error-handling routine.

There are three forms of the Resume statement. The Resume or Resume 0 statement returns execution to the line at which the error occurred. The Resume Next statement returns execution to the line immediately following the line at which the error occurred. The Resume label statement returns execution to the line specified by the label argument. The label argument must indicate either a line label or a line number.

You typically use the Resume or Resume 0 statement when the user must make a correction. For example, if you prompt the user for the name of a table to open, and the user enters the name of a table that doesn't exist, you can prompt the user again and resume execution with the statement that caused the error.

You use the Resume Next statement when your code corrects for the error within an error handler, and you want to continue execution without rerunning the line that caused the error. You use the Resume label statement when you want to continue execution at another point in the procedure, specified by the label argument. For example, you might want to resume execution at an exit routine, as described in the following section.

Exiting a Procedure

When you include an error-handling routine in a procedure, you should also include an exit routine, so that the error-handling routine will run only if an error occurs. You can specify an exit routine with a line label in the same way that you specify an error-handling routine.

For example, you can add an exit routine to the example in the previous section. If an error doesn't occur, the exit routine runs after the body of the procedure. If an error occurs, then execution passes to the exit routine after the code in the error-handling routine has run. The exit routine contains an Exit statement.

Function MayCauseAnError()
    ' Enable error handler.
    On Error GoTo Error_MayCauseAnError
    .            ' Include code here that may generate error.
    .
    .

Exit_MayCauseAnError:
    Exit Function

Error_MayCauseAnError:
    .            ' Include code to handle error.
    .
    .
    ' Resume execution with exit routine to exit function.
    Resume Exit_MayCauseAnError
End Function

Handling Errors in Nested Procedures

When an error occurs in a nested procedure that doesn't have an enabled error handler, Visual Basic searches backward through the calls list for an enabled error handler in another procedure, rather than simply halting execution. This provides your code with an opportunity to correct the error within another procedure. For example, suppose Procedure A calls Procedure B, and Procedure B calls Procedure C. If an error occurs in Procedure C and there's no enabled error handler, Visual Basic checks Procedure B, then Procedure A, for an enabled error handler. If one exists, execution passes to that error handler. If not, execution halts and an error message is displayed.

Visual Basic also searches backward through the calls list for an enabled error handler when an error occurs within an active error handler. You can force Visual Basic to search backward through the calls list by raising an error within an active error handler with the Raise method of the Err object. This is useful for handling errors that you don't anticipate within an error handler. If an unanticipated error occurs, and you regenerate that error within the error handler, then execution passes back up the calls list to find another error handler, which may be set up to handle the error.

For example, suppose Procedure C has an enabled error handler, but the error handler doesn't correct for the error that has occurred. Once the error handler has checked for all the errors that you've anticipated, it can regenerate the original error. Execution then passes back up the calls list to the error handler in Procedure B, if one exists, providing an opportunity for this error handler to correct the error. If no error handler exists in Procedure B, or if it fails to correct for the error and regenerates it again, then execution passes to the error handler in Procedure A, assuming one exists.

To illustrate this concept in another way, suppose that you have a nested procedure that includes error handling for a type mismatch error, an error which you've anticipated. At some point, a division-by-zero error, which you haven't anticipated, occurs within Procedure C. If you've included a statement to regenerate the original error, then execution passes back up the calls list to another enabled error handler, if one exists. If you've corrected for a division-by-zero error in another procedure in the calls list, then the error will be corrected. If your code doesn't regenerate the error, then the procedure continues to run without correcting the division-by-zero error. This in turn may cause other errors within the set of nested procedures.

In summary, Visual Basic searches back up the calls list for an enabled error handler if:

  • An error occurs in a procedure that doesn't include an enabled error handler.

  • An error occurs within an active error handler. If you use the Raise method of the Err object to raise an error, you can force Visual Basic to search backward through the calls list for an enabled error handler.

Getting Information About an Error

Once execution has passed to the error-handling routine, your code must determine which error has occurred and address it. Visual Basic and Microsoft Access provide several language elements that you can use to get information about a specific error. Each is suited to different types of errors. Since errors can occur in different parts of your application, you need to determine which to use in your code based on what errors you expect.

The language elements available for error handling include:

  • The Err object.

  • The ADO Error object and Errors collection

  • The DAO Error object and Errors collection.

  • The AccessError method.

  • The Error event.

The Err Object

The Err object is provided by Visual Basic. When a Visual Basic error occurs, information about that error is stored in the Err object. The Err object maintains information about only one error at a time. When a new error occurs, the Err object is updated to include information about that error instead.

To get information about a particular error, you can use the properties and methods of the Err object. The Number property is the default property of the Err object; it returns the identifying number of the error that occurred. The Err object's Description property returns the descriptive string associated with a Visual Basic error. The Clear method clears the current error information from the Err object. The Raise method generates a specific error and populates the properties of the Err object with information about that error.

The following example shows how to use the Err object in a procedure that may cause a type mismatch error:

Function MayCauseAnError()
    ' Declare constant to represent likely error.
    Const conTypeMismatch As Integer = 13

    On Error GoTo Error_MayCauseAnError
        .            ' Include code here that may generate error.
        .
        .

Exit_MayCauseAnError:
    Exit Function

Error_MayCauseAnError:
    ' Check Err object properties.
    If Err = conTypeMismatch Then
        .            ' Include code to handle error.
        .
        .
    Else
        ' Regenerate original error.
        Dim intErrNum As Integer
        intErrNum = Err
        Err.Clear
        Err.Raise intErrNum
    End If
    ' Resume execution with exit routine to exit function.
    Resume Exit_MayCauseAnError
End Function

Note that in the preceding example, the Raise method is used to regenerate the original error. If an error other than a type mismatch error occurs, execution will be passed back up the calls list to another enabled error handler, if one exists.

The Err object provides you with all the information you need about Visual Basic errors. However, it doesn't give you complete information about Microsoft Access errors or Microsoft Jet database engine errors. Microsoft Access and Data Access Objects (DAO)) provide additional language elements to assist you with those errors.

The Error Object and Errors Collection

The Error object and Errors collection are provided by ADO and DAO. The Error object represents an ADO or DAO error. A single ADO or DAO operation may cause several errors, especially if you are performing DAO ODBC operations. Each error that occurs during a particular data access operation has an associated Error object. All the Error objects associated with a particular ADO or DAO operation are stored in the Errors collection, the lowest-level error being the first object in the collection and the highest-level error being the last object in the collection.

When a ADO or DAO error occurs, the Visual Basic Err object contains the error number for the first object in the Errors collection. To determine whether additional ADO or DAO errors have occurred, check the Errors collection. The values of the ADO Number or DAO Number properties and the ADO Description or DAO Description properties of the first Error object in the Errors collection should match the values of the Number and Description properties of the Visual Basic Err object.

The AccessError Method

You can use the Raise method of the Err object to generate a Visual Basic error that hasn't actually occurred and determine the descriptive string associated with that error. However, you can't use the Raise method to generate a Microsoft Access error, an ADO error, or a DAO error. To determine the descriptive string associated with a Microsoft Access error, an ADO error, or a DAO error that hasn't actually occurred, use the AccessError method.

The Error Event

You can use the Error event to trap errors that occur on a Microsoft Access form or report. For example, if a user tries to enter text in a field whose data type is Date/Time, the Error event occurs. If you add an Error event procedure to an Employees form, then try to enter a text value in the HireDate field, the Error event procedure runs.

The Error event procedure takes an integer argument, DataErr. When an Error event procedure runs, the DataErr argument contains the number of the Microsoft Access error that occurred. Checking the value of the DataErr argument within the event procedure is the only way to determine the number of the error that occurred. The Err object isn't populated with error information after the Error event occurs. You can use the value of the DataErr argument together with the AccessError method to determine the number of the error and its descriptive string.

Note The Error statement and Error function are provided for backward compatibility only. When writing new code, use the Err and Error objects, the AccessError function, and the Error event for getting information about an error.


Determine the Error Codes Reserved by Microsoft Access and the Microsoft Jet Database Engine

The following procedure creates a table containing many of the error codes and strings used or reserved by Microsoft Access and by the Microsoft Jet database engine. Not all error codes are included in the resulting table, as some exist outside the range of error codes evaluated by this procedure (0 to 4500).

Function AccessAndJetErrorsTable() As Boolean
    Dim cat As New ADOX.Catalog
    Dim tbl As New ADOX.Table
    Dim cnn As ADODB.Connection
    Dim rst As New ADODB.Recordset, lngCode As Long
    Dim strAccessErr As String

    Const conAppObjectError = "Application-defined or object-defined error"
    On Error GoTo Error_AccessAndJetErrorsTable

    Set cnn = CurrentProject.Connection
        ' Create Errors table with ErrorNumber and ErrorDescription fields.
    tbl.Name = "AccessAndJetErrors"
    tbl.Columns.Append "ErrorCode", adInteger
    tbl.Columns.Append "ErrorString", adLongVarWChar

    Set cat.ActiveConnection = cnn
    cat.Tables.Append tbl
    ' Open recordset on Errors table.
    rst.Open "AccessAndJetErrors", cnn, adOpenStatic, adLockOptimistic
    ' Loop through error codes.
    For lngCode = 0 To 3500
        On Error Resume Next
        ' Raise each error.
        strAccessErr = AccessError(lngCode)
        DoCmd.Hourglass True
        ' Skip error numbers without associated strings.
        If strAccessErr <> "" Then
            ' Skip codes that generate application or object-defined errors.
            If strAccessErr <> conAppObjectError Then
                ' Add each error code and string to Errors table.
                rst.AddNew
                rst!ErrorCode = lngCode
                ' Append string to memo field.
                rst!ErrorString = strAccessErr
                rst.Update
            End If
        End If
    Next lngCode
    ' Close recordset.
    rst.Close
    DoCmd.Hourglass False
    RefreshDatabaseWindow
    MsgBox "Access and Jet errors table created."
    AccessAndJetErrorsTable = True

Exit_AccessAndJetErrorsTable:
    Exit Function

Error_AccessAndJetErrorsTable:
    MsgBox Err & ": " & Err.Description
    AccessAndJetErrorsTable = False
    Resume Exit_AccessAndJetErrorsTable
End Function


 Determine the Error Codes Reserved by Visual Basic

Determine the Error Codes Reserved by Visual Basic

The following procedure creates a table in Microsoft Access containing the error codes and strings used or reserved by Visual Basic. The table doesn't include ActiveX Data Objects (ADO) errors.

Visual Basic reserves a portion of the first thousand possible error numbers, so this example considers only error numbers between 1 and 1000. Other error numbers are reserved by the Microsoft Jet database engine, or are available for defining custom errors.

Sub CreateErrorsTable()
    Dim cat As New ADOX.Catalog
    tbl As New ADOX.Table
    cnn As ADODB.Connection
    Dim rst As New ADODB.Recordset, lngCode As Long
    Const conAppObjectError = "Application-defined or object-defined error"

    Set cnn = CurrentProject.Connection
    ' Create Errors table with ErrorNumber and ErrorDescription fields.
    tbl.Name = "Errors"
    tbl.Columns.Append "ErrorCode", adInteger
    tbl.Columns.Append "ErrorString", adVarWChar
    Set cat.ActiveConnection = cnn
    cat.Tables.Append tbl
    ' Open recordset on Errors table.
    rst.Open"Errors", cnn adOpenStatic, adLockOptimistic
    ' Loop through first 1000 Visual Basic error codes.
    For lngCode = 1 To 1000
        On Error Resume Next
        ' Raise each error.
        Err.Raise lngCode
        DoCmd.Hourglass True
        ' Skip error codes that generate application or object-defined errors.
        If Err.Description <> conAppObjectError Then
            ' Add each error code and string to Errors table.
            rst.AddNew
            rst!ErrorCode = Err.Number
            rst!ErrorString = Err.Description
            rst.Update
        End If
        ' Clear Err object.
        Err.Clear
    Next lngCode
    ' Close recordset.
    rst.Close
    DoCmd.Hourglass False
    MsgBox "Errors table created."
End Sub


 Information About Properties, Methods, and Events of an ActiveX Control

Information About Properties, Methods, and Events of an ActiveX Control

This topic contains useful information on setting and using ActiveX control language elements in Microsoft Access 2000, and points out some features of ActiveX controls that were added in Microsoft Access 95 and Microsoft Access 97.

Note This information does not apply for ActiveX controls on a data access page environment.

General

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

ActiveXCtl0.Object.MonthLength = 0
ActiveXCtl0.MonthLength = 0

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

ActiveX control variables can only be dimensioned as type Control; they can't be a more specific type such as Calendar.

Properties

ActiveX control properties appear in the Microsoft Access property sheet. You can set most of these properties in either the ActiveX control's custom properties dialog box or the Microsoft Access property sheet.

Note The ActiveX control properties aren't listed in the ADO Properties or DAO Properties collections. The only way to access these properties is using the syntax shown in the previous section.

Events

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

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


 Microsoft Access Language Elements That Apply to ActiveX Controls

Microsoft Access Language Elements That Apply to ActiveX Controls

In addition to the properties, methods, and events specific to an ActiveX control, some existing Microsoft Access properties, methods, and events also apply to ActiveX controls. For information on how these language elements work, see the Microsoft Access topic on each language element.

Properties

The following Microsoft Access properties apply to ActiveX controls on forms and reports, and are available in the Microsoft Access property sheet:

BorderColor

BorderStyle

BorderWidth

Class

ControlSource (only available for ActiveX controls that support binding)

ControlTipText

DisplayWhen

Enabled

HelpContextID

 Height

Left

Locked (only available for ActiveX controls that support binding)

Name

Object

OLEClass

OnEnter

OnExit

OnGotFocus

 OnLostFocus

OnUpdated

SpecialEffect

TabIndex

TabStop

Tag

Top

Verb

Visible

Width

The following Microsoft Access properties apply to ActiveX controls, and are available only in a macro or Visual Basic:

ControlType | InSelection | Parent
EventProcPrefix | ObjectVerbsCount | Section

Events

The following Microsoft Access events apply to ActiveX controls on forms and reports:

Enter | GotFocus | Updated
Exit | LostFocus |

Methods

The following Microsoft Access methods apply to ActiveX controls on forms and reports:


 The ActiveX Control's Custom Properties Dialog Box

The ActiveX Control's Custom Properties Dialog Box

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

Note This information only applies to ActiveX controls in a Microsoft Access database (.mdb) environment.

Two Ways to Set Properties

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

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

  • The Microsoft Access property sheet.

  • The ActiveX control's custom properties dialog box.

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

Finding the Custom Properties Dialog Box

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

Using the Custom Properties Dialog Box

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

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

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


 View an ActiveX Control's About Box

View an ActiveX Control's About Box

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

Note The About box is not available for ActiveX controls on a data access page.


 Conversion and Compatibility Issues

Conversion and Compatibility Issues

You can't open a Microsoft Access 2000 database by using prior versions of Microsoft Access. However, you can link and import Microsoft Access 2000 (version 9.0) tables into Microsoft Access 97 (version 8.0) databases. You can also export a version 8.0 table to a version 7.0 database, and you can cut, copy, or paste data from a version 8.0 table to a version 7.0 table.

You can enable a database created in a prior version of Microsoft Access to run in Microsoft Access 2000 but you can't add new objects to, or change the design of objects in, the database.

If your attempt to convert a database to Microsoft Access 2000 fails, you can also create a new Microsoft Access 2000 database and then import all the objects from the earlier version into your new database.

Note If you need to share a database with users who are running a previous version of Microsoft Access, you should open the prior-version database with the Enable option rather than the Convert option. If you must share the database with users running a previous version of Microsoft Access do not convert the database to the Microsoft Access 2000 format.

Convert a Database

Convert a Secured Database from a Previous Version of Microsoft Access

Convert Library Databases and Add-ins

What's New for Developers: Overview

Convert Access Basic Code to Visual Basic

Convert Code That Calls a DLL

Macro Actions and Methods of the DoCmd Object

Convert SendKeys Key Combinations

Style for Intrinsic Constants

Scoping and Object-Naming Compatibility

DAO Object Library Compatibility

Examples of Converting DAO Code


 Convert Microsoft Access Tables, Forms, and Reports

Convert Microsoft Access Tables, Forms, and Reports

Several changes introduced by Microsoft Access 2000 might affect the behavior of your version 1.x or 2.0 applications. The following sections provide more information about those changes.

Indexes and Relationships

A Microsoft Access table can contain up to 32 indexes. Very complex tables that are a part of many relationships may exceed the index limit, and you won't be able to convert the database that contains these tables. Version 3.5 of the Microsoft Jet database engine creates indexes on both sides of relationships between tables. If your database won't convert, delete some relationships and try again to convert the database.

The LimitToList Property of Combo Boxes

In Microsoft Access 2000, combo boxes accept Null values when the LimitToList property is set to True (–1), whether or not the list contains Null values. In version 2.0, a combo box that has the LimitToList property set to True won't accept a Null value unless the list contains a Null value. If you want to prevent users from entering a Null value by using a combo box, set the Required property of the field in the table to Yes.

Menus and In-Place Activation of OLE Objects

In order to make additional functionality available to you while activating OLE objects in place, some menu commands may have been moved to a menu that isn't replaced when you activate an OLE server.

Macros in your converted application that use a DoMenuItem action to carry out a version 2.0 menu command when a component is activated won't be affected by the changes. Version 2.0 commands are mapped to their Microsoft Access 2000 equivalents.

Referencing a Control on a Read-Only Form

In Microsoft Access 2000, you can't use an expression to refer to the value of a control on a read-only form that's bound to an empty record source. In previous versions, the expression returns a Null value. Before you reference a control on a read-only form, you should make sure that the form's record source contains records.

Date Fields and Data Entry

If you enter 3/3 in a field of type Date on a form or a table datasheet, Microsoft Access 2000 automatically fills in the current year. However, if you enter 3/3/ in the same field, Microsoft Access returns an error message. You must omit the last date delimiter so that Microsoft Access can translate the date into the proper format.

Buttons Created with the Command Button Wizard

If you used the Command Button Wizard in version 2.0 or 7.0 of Microsoft Access to generate code that called another application, you should delete the button and re-create it by using the Command Button Wizard in Microsoft Access 2000.

Form and Report Class Modules

In prior versions of Microsoft Access, Form and Report objects have associated class modules even if there's no code behind the object. In Microsoft Access 2000, you can set a form's or report's HasModule property to False. When you set the HasModule property to False, the form or report will take up less disk space and will load faster than because it will no longer have an associated class module.

Converted Version 2.0 Report Has Different Margins

You may encounter problems when trying to print or preview a Microsoft Access 2000 report that has been converted from Microsoft Access 2.0 if the report has some margins set to 0. When you convert a Microsoft Access 2.0 report, margins aren't set to 0; they are instead set to the minimum margin that's valid for the default printer. This prevents the report from printing data in the unprintable region of the printer.

To resolve this problem, reduce the column width, column spacing, or number of columns in the report so that the width of the columns plus the width of the default margins is equal to or less than the width of your paper.

Can't Use the Format Property to Distinguish Null Values and Zero-Length Strings

In versions 1.x and 2.0, you can use the Format property of a control to display different values for Null values and zero-length strings (" "). In Microsoft Access 2000, to distinguish between Null values and zero-length strings in a control on a form, set the control's ControlSource property to an expression that tests for the Null value case. For example, to display "Null" or "ZLS" in a control, set its ControlSource property to the following expression:

=IIf(IsNull([MyControl]), "Null", Format([MyControl], "@;ZLS"))


Converting DAO Code to ADO

Microsoft Access includes ActiveX Data Objects (ADO) 2.1 as the default data access library. Although Data Access Objects (DAO) 3.6 is included it is not referenced by default. To aid in converting code to the newer ADO standard the following information is provided.

Note Versions of the DAO library prior to 3.6 are no longer provided or supported in Microsoft Access 2000

DAO to ADO object Map

DAO | ADO(ADODB) | Note
DBEngine | None |
Workspace | None |
Database | Connection |
Recordset | Recordset |
Dynaset-Type | Keyset | Retrieves a set of pointers to the records in the recordset
Snapshot-Type | Static | Both retrieve full records but a Static recordset can be updated.
Table-Type | Keyset with adCmdTableDirect Option |
Field | Field | When referred to in a recordset

DAO ADO
Open a Recordset
Dim db as Database
Dim rs as DAO.Recordset
Set db = CurrentDB()
Set rs = db.OpenRecordset(“Employees”)

Dim rs as New ADODB.Recordset
rs.Open “Employees”, CurrentProject.Connection, adOpenKeySet, adLockOptimistic
Edit a Recordset
rs.Edit
rs(“TextFieldName”) = “NewValue”
rs.Update

rs(“TextFieldName”) = “NewValue”
rs.Update

Note Moving focus from current record via MoveNext, MoveLast, MoveFirst, MovePrevious without first using the CancelUpdate method will implicitly execute the Update method.


Converting DAO DDL elements to ADOX

Microsoft Access includes additional libraries to use when converting DAO's Data Definition Language (DDL) functionality to the ActiveX Data Objects DDL functionality.

Note ADO DDL is not referenced by default in Microsoft Access 2000. You must first create a reference to MSADOX.DLL by selecting References on the Tools menu and selecting Microsoft ADO Ext. 2.1 for DDL and Security.

DAO to ADO object map

DAO | ADO(ADOX)
DBEngine | None
Workspace | None
Database | Catalog
QueryDef(Simple Select) | View
QueryDef(Action/Paramaterized) | Procedure
TableDef | Table
Parameter | Parameter
Field | Column

DAO to ADO security constants map

DAO | ADO(ADOX) | Note
dbSecNoAccess | adRightNone | User has no access to document
dbSecFullAccess | adRightFull | Has full object access
dbSecDelete | adRightDelete | Can delete object
dbSecReadSec | adRightReadDesign | Can read security-related information
dbSecWriteSec | adRightWriteDesign | Can change access
dbSecWriteOwner | adRightWriteOwner | Can change owner
dbSecCreate | adRightCreate or adRightWithGrant | Can create new documents
dbSecReadDef | adRightRead or adRightReadDesign | Read the definition of a table or query
dbSecWriteDef | adRightUpdate or adRightWriteDesign | Alter the definition of a table or query
dbSecRetrieveData | adRightRead | Read data stored ina table or query. Implicitly grants read permission to the definition.
dbSecInsertData | adRightInsert | Insert new rows into table or query
dbSecReplaceData | adRightUpdate | Modify table or query data
dbSecDeleteData | adRightDelete or adRightWithGrant | Delete rows from table or query

Jet Field Data Types | DAO Data types | ADO Data Types
Yes/No | dbBoolean | adBoolean
Number (FieldSize = Byte) | dbByte | adUnsignedTinyInt
AutoNumber (FieldSize = Long Integer) | dbLong | adInteger
Currency | dbCurrency | adCurrency
Date/Time | dbDate | adDate
Number (FieldSize = Double) | dbDouble | adDouble
Number or AutoNumber (FieldSize =Replication ID) | dbGUID | adGUID
Number (FieldSize = Long Integer) | dbLong | adInteger
OLE Object | dbLongBinary | adLongVarBinary
Memo | dbMemo | adLongVarWChar
Number (FieldSize = Single) | dbSingle | adSingle
Number (FieldSize = Integer) | dbInteger | adSmallInt
Text | dbText | adVarWChar
Hyperlink | dbMemo | adLongVarWChar
Numeric (FieldSize=Decimal) | dbDecimal | adDecimal

  4. DAO
  1. ADO
Creating a Database
Dim wsp As Workspace, dbs As Database
Set wsp = DBEngine(0)
Set dbs = wsp.CreateDatabase("Newdb.mdb")

Dim cat As New ADOX.Catalog
cat.Create "Provider = Microsoft.Jet.OLEDB.4.0;" _
       & "Data Source = Newdb.mdb"
Creating a Table
Dim dbs As Database
Dim tdf As TableDef, fld As Field

Set dbs = CurrentDb
Set tdf = dbs.CreateTableDef("NewTable")
Set fld = tdf.CreateField("FName", dbText, 50)
tdf.Fields.Append fld
dbs.TableDefs.Append tdf
Dim cat As New ADOX.Catalog
Dim tbl As New ADOX.Table

Set cat.ActiveConnection = CurrentProject.Connection
tbl.Name = “NewTable”
tbl.Columns.Append “FName”, adVarWChar, 50
Cat.Tables.Append tbl
Creating a Query
Dim dbs As Database
Dim qdf As QueryDef

Set dbs = CurrentDb
Set qdf = dbs.CreateQueryDef("NewQuery", _
     "Select * From Employees")
dbs.QueryDefs.Append qdf
Dim cat As New ADOX.Catalog
Dim cmd As New ADODB.Command

Set cat.ActiveConnection = CurrentProject.Connection
cmd.CommandText “Select * From Employees”
Cat.Views.Append "NewQuery", cmd


Converting DAO Replication to JRO

In Addition to the ADO and ADOX object libraries Microsoft Access provides Jet and Replication Objects (JRO). This set of objects provides an object model and methods that are specifically designed for use with ADO and the Jet Database Engine.

Note You must first create a reference to MSJRO.DLL by selecting References on the Tools menu and selecting Microsoft Jet and Replication Objects 2.1 Library to use JRO functionality.

Below are listed some common DAO Replication methods and their JRO equivalents.

DAO | ADO(JRO) | Note
DBEngine | JetEngine |
Database | Catalog |

Creating a Replica
'Given an open database Object dbReplicable
Dim dbTemp As Database

Set dbTemp=OpenDatabase(dbReplicable)
dbTemp.MakeReplica strNewReplica, _
"Replica of " & strReplicableDB
dbsTemp.Close

Dim rpMaster As New JRO.Replica
rpMaster.MakeReplicable "northwind.mdb",False
Set rpMaster = Nothing
rpMaster.ActiveConnection ="northwind.mdb"
rpMaster.CreateReplica "northwind2.mdb", _
 "My Full Replica1", jrRepTypeFull, jrRepVisibilityGlobal
Set rpMaster = Nothing
Compact and Encrypt a Database
Dim dbNWD As Database
Set dbNWD =OpenDatabase("Northwind.mdb")
DBEngine.CompactDatabase "Northwind.mdb", _
"NWD_DAOComp.mdb", , dbEncrypt

Dim je As New JRO.JetEngine
je.CompactDatabase _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb", _   "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NWD_ADOComp.mdb.mdb;" _
& "Jet OLEDB:Encrypt Database=True"


 Examples of Converting DAO Code

Examples of Converting DAO Code

Microsoft Access includes version 4.0 of the Microsoft Jet database engine and the DAO 3.6 object library. All previous version of DAO are no longer supported in Microsoft Access 2000. The following examples demonstrate how to convert code constructs in Microsoft Access databases created with earlier versions of the Jet database engine and DAO object libraries

Note This information is provided for reference only. Versions of DAO code prior to 3.6 are no longer supported in Access 2000. It is suggested that you use the ADO methods of accessing data in your current database for all new applications and future version compatibility.

Setting a Reference to the current database

Version Example
1.x
Dim dbs As Database
Set dbs = CurrentDb
2.x
Dim dbs As Database
Set dbs = DBEngine.Workspaces(0).Databases(0)
or
Dim dbs As Database
Set dbs = DBEngine(0)(0)
7.0 or Later
Dim dbs As DAO.Database
Set dbs = CurrentDb
9.0

(Recommended)

Dim cnn As ADODB.Connection
Set cnn = CurrentProject.Connection

Note In Microsoft Access, the current database is the default database in the Databases collection, so you can still use the DBEngine(0)(0) syntax to return a Database object variable pointing to the current database. However, when using DAO the CurrentDb method is the preferred means of returning this object variable, because it enables you to create more than one Database object variable that points to the current database.

Opening a Database and Setting a Reference

Version Example
1.x
Set dbs = OpenDatabase("Contacts.mdb")
2.x and later
Set dbs = DBEngine.Workspaces(0).OpenDatabase("Contacts.mdb")
or
Set dbs = Workspaces(0).OpenDatabase("Contacts.mdb")
or
Set dbs = OpenDatabase("Contacts.mdb")
9.x (Recommended)
cnn.Open “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Contact.mdb”

Opening a Table-Type Recordset

Version Example
1.x
Dim tbl As Table
Set tbl = dbs.OpenTable("Orders")
2.x
Dim rst As Recordset
Set rst = dbs.OpenRecordset("Orders", DB_OPEN_TABLE)
or
Dim rst As Recordset
Set rst = dbs!Orders.OpenRecordset
7.0 or later
Dim rst As DAO.Recordset
Set rst = dbs.OpenRecordset("Orders", dbOpenTable)
or
Dim rst As DAO.Recordset
Set rst = dbs!Orders.OpenRecordset
9.0 (Recommended)
Dim rst As New ADODB.Recordset
rst.Open “Orders”,cnn,adOpenKeyset,adLockOptimistic,adCmdTableDirect

Opening a Table-Type Recordset Exclusively

Version Example
1.x
Dim tbl As Table
Set tbl = dbs.OpenTable("Orders", DB_DENY_READ)
2.x
Dim rst As Recordset
Set rst = dbs.OpenRecordset("Orders", DB_OPEN_TABLE, DB_DENY_READ)
or
Dim rst As Recordset
Set rst = dbs!Orders.OpenRecordset(DB_OPEN_TABLE, DB_DENY_READ)
7.0 or later
Dim rst As DAO.Recordset
Set rst = dbs.OpenRecordset("Orders", dbOpenTable, dbDenyRead)
or
Dim rst As DAO.Recordset
Set rst = dbs!Orders.OpenRecordset(dbOpenTable, dbDenyRead)
9.0 (Recommended)
S/A (Not available via ADO)

Opening a Dynaset-Type Recordset

Version Example
1.x
Dim dyn As Dynaset
Set dyn = dbs.CreateDynaset("Orders")
2.x
Dim rst As Recordset
Set rst = dbs.OpenRecordset("Orders", DB_OPEN_DYNASET)
or
Set rst = dbs!Orders.OpenRecordset(dbOpenDynaset)
7.0 or later
Dim rst As Recordset
Set rst = dbs.OpenRecordset("Orders", dbOpenDynaset)
or
Set rst = dbs!Orders.OpenRecordset(dbOpenDynaset)
9.0 (Recommended)
Dim rst As New ADODB.Recordset
rst.Open “Orders”, cnn, adOpenKeyset, adLockOptimistic

Opening a Snapshot-Type Recordset

Version Example
1.x
Dim snp As Snapshot
Set snp = dbs.CreateSnapshot("Orders")
2.x
Dim rst As Recordset
Set rst = dbs.OpenRecordset("Orders", DB_OPEN_SNAPSHOT)
or
Set rst = dbs!Orders.OpenRecordset(DB_OPEN_SNAPSHOT)
7.0 or later
Dim rst As Recordset
Set rst = dbs.OpenRecordset("Orders", dbOpenSnapshot)
or
Set rst = dbs!Orders.OpenRecordset(dbOpenSnapshot)
9.0 (Recommended)
Dim rst As New ADODB.Recordset
rst.Open “Orders”, cnn, adOpenStatic, adLockReadOnly

Listing Fields

Version Example
1.x
' Given open Table object tbl.
Dim snp As Snapshot
Set snp = tbl.ListFields()
While Not snp.EOF
   Debug.Print snp!Name, snp!Type
   snp.MoveNext
Wend
snp.Close
2.x
' Given open TableDef object tdf.
Dim intI As Integer, fld As Field
For intI = 0 To tdf.Fields.Count - 1
   Set fld = tdf.Fields(intI)
   Debug.Print fld.Name, fld.Type
Next intI
7.0 or later
' Given open TableDef object tdf.
Dim fld As Field
For Each fld in tdf.Fields
   Debug.Print fld.Name, fld.Type
Next fld
9.0 (Recommended)
‘ Given open Table object tbl
Dim col as ADOX.column
For Each col in tbl.Columns
   Debug.Print col.Name, col.Type
Next col

Listing Tables in a Database

Version Example
1.x
' Given open Database object dbs.
Dim snp As Snapshot
Set snp = dbs.ListTables()
While Not snp.EOF
   Debug.Print snp!Name
   snp.MoveNext
Wend snp.Close
2.x
' Given open Database object dbs.
Dim intJ As Integer, tdf As TableDef
For intJ = 0 To dbs.TableDefs.Count - 1
   Set tdf = dbs.TableDefs(intJ)
   Debug.Print tdf.Name
Next intJ
7.0 or later
' Given open Database object dbs.
Dim tdf As TableDef
For Each tdf in dbs.TableDefs
   Debug.Print tdf.Name
Next tdf
9.0 (Recommended)
‘ Given open Catalog object cat
Dim tbl As ADOX.Table
For Each tbl in cat.Tables
   Debug.Print tbl.Name
Next tbl

Listing a Table's Indexes

Version Example
1.x
' Given open Table object tbl.
Dim snp As Snapshot
Set snp = tbl.ListIndexes()
While Not snp.EOF
   Debug.Print snp!Name
   snp.MoveNext
Wend
snp.Close
2.x
' Given open TableDef object tdf.
Dim intI As Integer, idx As Index
For intI = 0 To tdf.Indexes.Count - 1
   Set idx = tdf.Indexes(intI)
   Debug.Print idx.Name
Next intI
7.0 or later
' Given open TableDef object tdf.
Dim idx As DAO.Index
For Each idx in tdf.Indexes
   Debug.Print idx.Name
Next idx
9.0

(Recommended)

' Given open Table object tbl.
Dim idx As ADOX.Index
For Each idx in tbl.Indexes
   Debug.Print idx.Name
Next idx

Listing a Query's Parameters

Version Example
1.x
' Given open QueryDef object qdf.
Dim snp As Snapshot
Set snp = qdf.ListParameters()
While Not snp.EOF
   Debug.Print snp!Name
   snp.MoveNext
Wend
snp.Close
2.x
' Given open QueryDef object qdf.
Dim intI As Integer, prm As Parameter
For intI = 0 to qdf.Parameters.Count - 1
   Set prm = qdf.Parameters(i)
   Debug.Print prm.Name
Next intI
7.0 or later
' Given open QueryDef object qdf.
Dim prm As Parameter
For Each prm in qdf.Parameters
   Debug.Print prm.Name
Next prm
9.0 (Recommended)
' Given open Procedure object prc.
Dim prm As ADODB.Parameter
For Each prm in prc.Parameters
   Debug.Print prm.Name
Next prm

Setting Query Parameters Dynamically

Version Example
1.x
' Given open Database dbs.
Dim qdf As QueryDef, dyn As Dynaset
Set qdf = dbs.OpenQueryDef("OrdersQuery")
qdf.ParameterName = "[Start date]"
Set dyn = qdf.CreateDynaset()
2.x
' Given open QueryDef object qdf.
Dim intI As Integer, prm As Parameter, rst As Recordset
For intI = 0 To qdf.Parameters.Count - 1
   Set prm = qdf.Parameters(intI)
   prm.Value = InputBox("Value for " & prm.Name)
Next intI
Set rst = qdf.OpenRecordset
7.0 or later
' Given open QueryDef object qdf.
Dim prm As Parameter, rst As Recordset
For Each prm in qdf.Parameters
   prm.Value = InputBox("Value for " & prm.Name)
Next prm
Set rst = qdf.OpenRecordset
9.0 (Recommended)
' Given open Procedure object prc.
Dim prm As ADODB.Parameter, rst As ADODB.Recordset
For Each prm in prc.Command.Parameters
   prm.Value = InputBox("Value for " & prm.Name)
Next prm
rst.Open prc.Command,,adOpenKeyset, adLockOptimistic

Running a Pass-Through Query

Version Example
1.x
' Given open Database object dbs.
Dim lngRows As Long
' Run stored procedure on server.
lngRows = dbs.ExecuteSQL("EXECUTE SP_StoredProc")
or
Dim snp As Snapshot
Set snp = dbs.CreateSnapshot("EXECUTE SP_StoredProc", DB_SQLPassThrough)
2.x and later
' Given open Database object dbs.
Dim qdf As QueryDef, rst As Recordset
Set qdf = dbs.CreateQueryDef("ODBCQuery")
qdf.Connect = "ODBC;" & "DSN=MyServer;" _
   & "UID=sa;" & "PWD=hithere;" & "DATABASE=pubs"
qdf.SQL = "EXECUTE SP_StoredProc"
qdf.ReturnsRecords = True
.
.
.
Set rst = qdf.OpenRecordset
9.0 and later
' Given open Catalog Object with Activeconnection set, object cat.
Dim rst As Recordset, cmdPassthru As New ADODB.Command
Set cmdPassthru.ActiveConnection = Currentproject.connection
cmdPassthru("Jet OLEDB:Passthru Query conection string")= _
   "ODBC;DSN=MyServer;UID=sa;PWD=hithere;DATABASE=pubs"
cmdPassthru.CommandText = "EXECUTE SP_StoredProc"
cat.Procedures.Append "ODBCQuery", cmdPassthru

Set rst = cmd.Execute

Creating a Temporary Query

Version Example
1.x
' Given open Database object dbs.
Dim qdf As QueryDef, strTemp As String
strTemp = "TMP:" & User() & Time()
qdf = dbs.CreateQueryDef(strTemp)
qdf.SQL = "UPDATE Table1 SET Table1.Field1 = Field1 * 1.1;"
.
.
.
qdf.Execute
qdf.Close
.
.
dbs.DeleteQueryDef(strTemp)
2.x and later
qdf = dbs.CreateQueryDef("")
qdf.Execute
qdf.Close
9.0 and later
cmd.CommandText = "UPDATE Table1 SET Table1.Field1 = Field1 * 1.1;" cmd.Execute
set cmd = Nothing


 Automation with Microsoft Access

Automation with Microsoft Access

Microsoft Access is an COM component that supports Automation, formerly called OLE Automation. Microsoft Access supports Automation in two ways. From Microsoft Access, you can work with objects supplied by another component. Microsoft Access also supplies its objects to other COM components.

In previous versions of Microsoft Access, you could use the CreateObject function or the GetObject function to point a variable to an instance of a component. In Microsoft Access 97 and Access 2000, you can also use the New keyword to create a new instance of some components. Check the component's documentation to determine which syntax it supports.

In Microsoft Access, you can set a reference to a component's type library to improve performance when you work with that component through Automation. Microsoft Access also includes the Object Browser, a tool that enables you to view objects in another component's type library, as well as their methods and properties.

The Microsoft Access type library provides information about Microsoft Access objects to other components. You can set a reference to the Microsoft Access type library from a component and view its objects in the Object Browser.

To work with Microsoft Access objects through Automation, you must create an instance of the Microsoft Access Application object. For example, suppose you want to display data from Microsoft Excel in a Microsoft Access form or report. To launch Microsoft Access from Microsoft Excel, you can use the New keyword to create an instance of the Microsoft Access Application object. You can also use the CreateObject function to create a new instance of the Microsoft Access Application object, or you can use the GetObject function to point an object variable to an existing instance of Microsoft Access. Check your component's documentation to determine which syntax it supports.

Once you've launched an instance of Microsoft Access, if you want to control any Microsoft Access objects, you must open a database (.mdb) or project (.adp) in the Microsoft Access window by using either the OpenCurrentDatabase or the NewCurrentDatabase method for a database or by using the OpenAccessProject or the NewAccessProject method for a project.

If you've opened Microsoft Access only as a means of using the Data Access Objects provided by Microsoft DAO, then you don't need to open a database in the Microsoft Access window. You can use the DBEngine property of the Microsoft Access Application object to access objects in the Microsoft DAO 3.6 object library during an Automation operation.


 Using ActiveX Data Objects in Microsoft Access 2000

Using ActiveX Data Objects in Microsoft Access 2000

Microsoft Access 2000 provides three new object models to use in the creation, maintaining and managing of your Access 2000 databases and their related data by using Visual Basic.

Microsoft ActiveX Data Objects (ADO)

ADO contains the objects needed to create, maintain, and delete records in a given datasource.

Microsoft ADO Ext. for DDL and Security (ADOX)

ADOX provides the Data Definition Language(DDL) objects needed to create a new database and its contained objects in addition to the objects needed to manage security.

Microsoft Jet and Replication Objects 2.1 Library (JRO)

Since ADO objects were designed to work with many databases in addition to Microsoft Jet databases, functionality specific to Jet was broken out into the JRO library.

The following table lists the functionality provided by each compared to DAO.

Functionality | DAO | ADO1 | ADOX2 | JRO (MDB's Only)
Create Recordsets | X | X |  |
Edit Startup properties | X | X** |  |
Support ANSI92 SQL*** |  | X | X |
Create Tables | X |  | X |
Create New Database | X |  | X* |
Edit Existing Table properties | X |  | X |
Create table relationships | X |  | X* |
Create New Users/Groups | X |  | X |
Edit security settings | X |  | X* |
Support for new Jet 4.0 Decimal datatype |  |  | X |
Support for Compression attribute for column data |  |  | X |
Edit stored, basic SQL queries or views | X |  | X* |
Create permanent queries that are accessible only through code. |  |  | X* |
Create queries accessible through database container/UI and code. | X |  |  |
Compact/Encrypt database | X |  |  | X4
Refresh Cache | X |  |  | X
Make Database Replicable | X |  |  | X3
Make Database Replicas | X |  |  | X3
Synchronize Replicas | X |  |  | X3
Edit Database properties | X |  |  |
Create custom database properties | X |  |  |
Edit table column properties | X |  |  |

* Only available when working with Microsoft Access databases (.mdb). Future versions of the SQL Provider may provide this functionality in Microsoft Access projects (.adp).

** Only available when working with Access projects.

*** Though Jet does support some ANSI 92 SQL it is not yet fully ANSI92 compliant.

1 Uses Connection object to reference to database

2 Uses Catalog object to reference database

3 Uses Replica object to reference database

4 Uses JetEngine object to reference database

Note Unlike DAO, ADO and ADOX objects can perform the marked actions in databases other then Jet as long as the provider for those databases supports that action.


 DAO Object Library Compatibility

DAO Object Library Compatibility

Microsoft Access 2000 includes DAO objects, methods, and properties that replace those in versions 1.x, 2.0, and 7.0. You'll need to replace the older language elements that Microsoft Access 2000 doesn't support with the ones provided in the DAO 3.6 object library.

You can use the following table to identify the objects, methods, and properties that aren't included in the Microsoft DAO 3.6 object library and the features that replace them. You can use the new items in the second column to modify code written in earlier versions of Microsoft Access.

For examples of how to modify your code, see Examples of Converting DAO Code.

Functionality not present in DAO 3.6 | Recommended DAO 3.6 replacements
FreeLocks | Idle method of the DBEngine object (not needed for Microsoft Access 2000 databases)
SetDefaultWorkspace | DefaultUser/DefaultPassword properties of the DBEngine object
SetDataAccessOption | IniPath property of the DBEngine object
Database.BeginTrans | Workspace.BeginTrans
Database.CommitTrans | Workspace.CommitTrans
Database.CreateDynaset | Database.OpenRecordset of type dbOpenDynaset
Database.CreateSnapshot | Database.OpenRecordset of type dbOpenSnapshot
Database.DeleteQueryDef | Delete method of the QueryDefs collection
Database.ExecuteSQL | Database.Execute method and Database.RecordsAffected property
Database.ListTables | Database.TableDefs collection
Database.OpenQueryDef | Database.QueryDefs collection
Database.OpenTable | Database.OpenRecordset of type dbOpenTable
Database.Rollback | Workspace.Rollback
ListFields method of the Table, Dynaset, and Snapshot objects | Recordset.Fields collection
Table.ListIndexes | TableDef.Indexes collection
QueryDef.CreateDynaset | QueryDef.OpenRecordset
QueryDef.CreateSnapshot | QueryDef.OpenRecordset
QueryDef.ListParameters | QueryDef.Parameters collection
Dynaset object | Dynaset-type Recordset object
Snapshot object | Snapshot-type Recordset object
Table object | Table-type Recordset object
CreateDynaset method of the Dynaset and QueryDef objects | Recordset.OpenRecordset with dbOpenDynaset parameter
CreateSnapshot method of the Dynaset and QueryDef objects | Recordset.OpenRecordset with dbOpenSnapshot parameter


 Use ODBCDirect with Microsoft Access

Use ODBCDirect with Microsoft Access

What Is ODBCDirect?

ODBCDirect is a technology that enables you to work with ODBC database servers without loading the Microsoft Jet database engine. ODBCDirect relies on the Microsoft DAO 3.6 object model, so that you can easily modify your existing DAO code to take advantage of ODBCDirect. Microsoft DAO 3.6 includes new objects, methods, and properties to support ODBCDirect.

Advantages of Accessing ODBC Data with ODBCDirect

ODBCDirect offers the following advantages for ODBC operations:

  • ODBCDirect can make your code faster and more efficient by providing direct access to ODBC data sources. Since it doesn't require loading the Microsoft Jet database engine, ODBCDirect consumes fewer resources on the client side. The ODBC server is responsible for all query processing.

  • ODBCDirect gives you improved access to server-specific features that aren't available by using ODBC through Microsoft Jet. For example, for servers that support cursor specification, ODBCDirect allows you to specify where cursors are located, whether locally or on the server. In addition, to interact with stored procedures at the server level, you can specify input values and check return values, which you can't do when using Microsoft Jet.

  • ODBCDirect also supports asynchronous queries. When you execute a query, you don't have to wait for the query to finish running before you begin another operation. You can track the query's execution by checking the StillExecuting property.

  • ODBCDirect supports batch updating, enabling you to cache Recordset object changes locally and then submit these changes to the server in a single batch.

  • With ODBCDirect, you can create simple cursorless result sets, or more complex cursors. You can also run queries that return any number of result sets. You can limit the number of rows returned and monitor all the messages and errors generated by the remote data source without affecting the performance of the executing query.

Creating an ODBCDirect Workspace

You can create an ODBCDirect workspace by specifying the constant dbUseODBC for the type argument of the CreateWorkspace method. You can also specify that an ODBCDirect workspace be created by default by setting the DefaultType property of the DBEngine object.

Once you've created an ODBCDirect workspace, you can use specific DAO objects, properties, and methods to work with data on the ODBC database server.

Advantages of Accessing ODBC Data with Microsoft Jet

Microsoft Jet and ODBCDirect workspaces provide different but complementary functionality. You should use a Microsoft Jet workspace to access .mdb files and ISAM data formats, such as text and spreadsheets. Microsoft Jet provides unique capabilities that aren't available through ODBCDirect, including the following:

  • Updatable joins. You must use a Microsoft Jet workspace to update data in Recordset objects based on multiple-table joins.

  • Heterogeneous joins. You must use a Microsoft Jet workspace to perform joins of tables in different data sources.

  • Data Definition Language (DDL) operations. You must use a Microsoft Jet workspace to perform DDL operations using DAO. ODBCDirect doesn't provide a TableDef object, so you can't create or modify tables by using DAO. You can, however, perform DDL operations by using ODBCDirect to execute SQL DDL statements.

  • Form and control binding. If your application requires that forms or controls be bound to data in an ODBC data source, you must use Microsoft Jet. Data accessed within an ODBCDirect workspace can't be bound to forms or controls.

If you don't need these capabilities, you can use an ODBCDirect workspace.

Note You can define both Microsoft Jet and ODBCDirect workspaces in your applications and mix them in any fashion. For example, in the same function, you can define a Microsoft Jet workspace to perform DDL operations using DAO and you can also define an ODBCDirect workspace to perform asynchronous queries.


 Use Microsoft Access as a DDE Server

Use Microsoft Access as a DDE Server

Microsoft Access supports dynamic data exchange (DDE) as either a destination (client) application or a source (server) application. For example, an application such as Microsoft Word, acting as a client, can request data through DDE from a Microsoft Access database that's acting as a server.

Tip If you need to manipulate Microsoft Access objects from another application, you may want to consider using Automation.

A DDE conversation between a client and server is established on a particular topic. A topic can be either a data file in the format supported by the server application, or it can be the System topic, which supplies information about the server application itself. Once a conversation has begun on a particular topic, only a data item associated with that topic can be transferred.

For example, suppose you are running Microsoft Word and want to insert data from a particular Microsoft Access database into a document. You begin a DDE conversation with Microsoft Access by opening a DDE channel with the DDEInitiate function and specifying the database file name as the topic. You can then transfer data from that database to Microsoft Word through that channel.

As a DDE server, Microsoft Access supports the following topics:

  • The System topic

  • The name of a database (database topic)

  • The name of a table (tablename topic)

  • The name of a query (queryname topic)

  • A Microsoft Access SQL string (sqlstring topic)

Once you've established a DDE conversation, you can use the DDEExecute statement to send a command from the client to the server application. When used as a DDE server, Microsoft Access recognizes any of the following as a valid command:

  • The name of a macro in the current database.

  • Any action that you can carry out in Visual Basic by using one of the methods of the DoCmd object.

  • The OpenDatabase and CloseDatabase actions, which are used only for DDE operations. (For an example of how to use these actions, see the example later in this topic.)

Note When you specify a macro action as a DDEExecute statement, the action and any arguments follow the DoCmd object syntax and must be enclosed in brackets ([ ]). However, applications that support DDE don't recognize intrinsic constants in DDE operations. Also, string arguments must be enclosed in quotation marks (" ") if the string contains a comma. Otherwise, quotation marks aren't required.

The client application can use the DDERequest function to request text data from the server application over an open DDE channel. Or the client can use the DDEPoke statement to send data to the server application. Once the data transfer is complete, the client can use the DDETerminate statement to close the DDE channel, or the DDETerminateAll statement to close all open channels.

Note When your client application has finished receiving data over a DDE channel, it should close that channel to conserve memory resources.

The following example demonstrates how to create a Microsoft Word procedure with Visual Basic that uses Microsoft Access as a DDE server. (For this example to work, Microsoft Access must be running.)

Sub AccessDDE()
    Dim intChan1 As Integer, intChan2 As Integer
    Dim strQueryData As String

    ' Use System topic to open Northwind sample database.
    ' Database must be open before using other DDE topics.
    intChan1 = DDEInitiate("MSAccess", "System")
    ' You may need to change this path to point to actual location
    ' of Northwind sample database.
    DDEExecute intChan1, "[OpenDatabase C:\Access\Samples\Northwind.mdb]"

    ' Get all data from Ten Most Expensive Products query.
    intChan2 = DDEInitiate("MSAccess", "Northwind.mdb;" _
        & "QUERY Ten Most Expensive Products")
    strQueryData = DDERequest(intChan2, "All")
    DDETerminate intChan2

    ' Close database.
    DDEExecute intChan1, "[CloseDatabase]"
    DDETerminate intChan1

    ' Print retrieved data to Debug Window.
    Debug.Print strQueryData
End Sub

For information on using Microsoft Access as a DDE client, see information in the Microsoft Office 2000/Visual Basic Programmer's Guide. For information about how to obtain the Microsoft Office 2000/Visual Basic Programmer's Guide, click [image] .

The following sections provide information about the valid DDE topics supported by Microsoft Access.

The System Topic

The System topic is a standard topic for all Microsoft Windows–based applications. It supplies information about the other topics supported by the application. To access this information, your code must first call the DDEInitiate function with "System" as the topic argument, and then execute the DDERequest statement with one of the following supplied for the item argument.

Item | Returns
SysItems | A list of items supported by the System topic in Microsoft Access.
Formats | A list of the formats Microsoft Access can copy onto the Clipboard.
Status | "Busy" or "Ready".
Topics | A list of all open databases.

The following example demonstrates the use of the DDEInitiate and DDERequest functions with the System topic:

' In Visual Basic, initiate DDE conversation with Microsoft Access.
Dim intChan1 As Integer, strResults As String
intChan1 = DDEInitiate("MSAccess", "System")
' Request list of topics supported by System topic.
strResults = DDERequest(intChan1, "SysItems")
' Run OpenDatabase action to open Northwind.mdb.
' You may need to change this path to point to actual location
' of Northwind sample database.
DDEExecute intChan1, "[OpenDatabase C:\Access\Samples\Northwind.mdb]"

The database Topic

The database topic is the file name of an existing database. You can type either just the base name (Northwind), or its path and .mdb extension (C:\Access\Samples\Northwind.mdb). After you start a DDE conversation with the database, you can request a list of the objects in that database.

Note You can't use DDE to query the Microsoft Access workgroup information file.

The database topic supports the following items.

Item | Returns
TableList | A list of tables.
QueryList | A list of queries.
FormList | A list of forms.
ReportList | A list of reports.
MacroList | A list of macros.
ModuleList | A list of modules.
ViewList | A list of views
StoredProcedureList | A list of stored procedures
DatabaseDiagramList | A list of database diagrams

The following example shows how you can open the Employees form in the Northwind sample database from a Visual Basic procedure:

' In Visual Basic, initiate DDE conversation with
' Northwind sample database.
' Make sure database is open.
intChan2 = DDEInitiate("MSAccess", "Northwind")
' Request list of forms in Northwind sample database.
strResponse = DDERequest(intChan2, "FormList")
' Run OpenForm action and arguments to open Employees form.
DDEExecute intChan2, "[OpenForm Employees,0,,,1,0]"

The TABLE tablename, QUERY queryname, and SQL sqlstring Topics

These topics use the following syntax:

databasename; TABLE tablename

databasename; QUERY queryname

databasename; SQL [sqlstring]

Part | Description
databasename | The name of the database that the table or query is in or that the SQL statement applies to, followed by a semicolon (;). The database name can be just the base name (Northwind) or its full path and .mdb extension (C:\Access\Samples\Northwind.mdb).
tablename | The name of an existing table.
queryname | The name of an existing query.
sqlstring A valid SQL statement up to 256 characters long, ending with a semicolon. To exchange more than 256 characters, omit this argument and instead use successive DDEPoke statements to build an SQL statement.

For example, the following Visual Basic code uses the DDEPoke statement to build an SQL statement and then request the results of the query.

intChan1 = DDEInitiate("MSAccess", "Northwind;SQL")
DDEPoke intChan1, "SQLText", "SELECT *"
DDEPoke intChan1, "SQLText", " FROM Orders"
DDEPoke intChan1, "SQLText", " WHERE [Freight] > 100;"
strResponse = DDERequest(intChan1, "NextRow")
DDETerminate intChan1

The following table lists the valid items for the TABLE tablename, QUERY queryname, and SQL sqlstring topics.

Item | Returns
All | All the data in the table, including field names.
Data | All rows of data, without field names.
FieldNames | A single-row list of field names.
FieldNames;T | A two-row list of field names (first row) and their data types (second row).
These are the values returned and the data types they represent:
Value | Data type
0 | Invalid
1 | True/False (non-Null)
2 | Unsigned byte
3 | 2-byte signed integer (Integer)
4 | 4-byte signed integer (Long)
5 | 8-byte signed integer (Currency)
6 | 4-byte single-precision floating-point (Single)
7 | 8-byte double-precision floating-point (Double)
8 | Date/Time
9 | Binary data, 256 bytes maximum
10 | ANSI text, not case-sensitive, 256 bytes maximum (Text)
11 | Long binary (OLE Object)
12 | Long text (Memo)
NextRow | The data in the next row in the table or query. When you open a channel, NextRow returns the data in the first row. If the current row is the last record and you run NextRow, the request fails.
PrevRow | The data in the previous row in the table or query. If PrevRow is the first request on a new channel, the data in the last row of the table or query is returned. If the first record is the current row, the request for PrevRow fails.
FirstRow | The data in the first row of the table or query.
LastRow | The data in the last row of the table or query.
FieldCount | The number of fields in the table or query.
SQLText | An SQL statement representing the table or query. For tables, this item returns an SQL statement in the form "SELECT * FROM table;".
SQLText;n An SQL statement, in n-character chunks, representing the table or query, where n is an integer up to 256. For example, suppose a query is represented by the following SQL statement:
"SELECT * FROM Orders;"

The item "SQLText;7" returns the following tab-delimited chunks:

"SELECT "
"* FROM "
"Orders;"

The following example shows how you can use DDE in a Visual Basic procedure to request data from a table in the Northwind sample database and insert that data into a text file:

Sub NorthwindDDE
    Dim intChan1 As Integer, intChan2 As Integer, intChan3 As Integer
    Dim strResp1 As Variant, strResp2 As Variant, strResp3 As Variant

    ' In a Visual Basic module, get data from Categories table,
    ' Catalog query, and Orders table in Northwind.mdb.
    ' Make sure database is open first.
    intChan1 = DDEInitiate("MSAccess", "Northwind;TABLE Shippers")
    intChan2 = DDEInitiate("MSAccess", "Northwind;QUERY Catalog")
    intChan3 = DDEInitiate("MSAccess", "Northwind;SQL SELECT * " _
        & "FROM Orders " _
        & "WHERE OrderID > 10050;")

    strResp1 = DDERequest(intChan1, "All")
    strResp2 = DDERequest(intChan2, "FieldNames;T")
    strResp3 = DDERequest(intChan3, "FieldNames;T")
    DDETerminate intChan1
    DDETerminate intChan2
    DDETerminate intChan3

    ' Insert data into text file.
    Open "C:\DATA.TXT" For Append As #1
    Print #1, strResp1
    Print #1, strResp2
    Print #1, strResp3
    Close #1
End Sub


Microsoft Access Objects

Application object
Forms collection (Form object)
Controls collection (Control object)
Properties collection (Control object)

Properties collection (Form object)
Reports collection (Report object)
Controls collection (Control object)
Properties collection (Control object)

Properties collection (Form object)
Modules collection (Module object)
References collection (Reference object)
DataAccessPages collection (DataAccessPage object)

Legend

yellow box Object and collection
bluebox Object only

right arrow Click red arrow to expand chart
AllForms collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllReports collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllDataAccessPages collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllMacros collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllModules collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AccessObjectProperties collection (AccessObjectProperty object)

AllTables collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllQueries collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllViews collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllStoredProcedures collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllDatabaseDiagrams collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)

AllForms collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllReports collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllDataAccessPages collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllMacros collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllModules collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AccessObjectProperties collection (AccessObjectProperty object)

AllTables collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllQueries collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllViews collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllStoredProcedures collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)
AllDatabaseDiagrams collection (AccessObject object)
AccessObjectProperties collection (AccessObjectProperty object)


Actions Grouped by Task

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

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


 AddMenu Action

AddMenu Action

You can use the AddMenu action to create:

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

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

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

  • 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 98 (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.
 | 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.

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.

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:

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

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

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

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


 ApplyFilter Action

ApplyFilter Action

You can use the ApplyFilter action to apply a filter, a query, or a 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.

Note You can only use this action to apply a SQL WHERE clause when applying a server filter. A server filter cannot be applied to a stored procedure record source.

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.
 | Note When using this action to apply a server filter, the Filter Name argument must be blank.
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 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 Field names should be surrounded by double quotes and string literals should be surrounded by single quotes.
 | 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.
Filter Type | Specifies whether the search includes formatted data. Click Normal (Microsoft Access searches for the data as it's formatted and displayed in the field) or Server (Microsoft Access searches for the data as it's stored in the database, which isn't always the same as it's displayed). The default is Normal.

Note 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. You must use one or both arguments.

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 or ServerFilter property.

For tables and forms, this action is similar to clicking Apply Filter/Sort or Apply Server Filter on the Records menu or clicking Apply Filter [image] or Apply Server Filter [image] 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.

In a Microsoft Access database (.mdb), 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, in an Access database, you can use the ShowAllRecords action, the Remove Filter/Sort command on the Records menu, or Remove Filter [image] on the toolbar. To remove a filter in a Microsoft Access project (.adp), you can return to the Server Filter By Form window and remove all filter criteria and then click Apply Server Filter on the Records menu, or click Apply Server Filter on the toolbar, or set the ServerFilterByForm property to False (0).

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.


 Beep Action

Beep Action

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

Setting

The Beep action doesn't have any arguments.

Remarks

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

  • Important screen changes have occurred.

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

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

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

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


 CancelEvent Action

CancelEvent Action

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

Setting

The CancelEvent action doesn't 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 validation conditions and to provide helpful information about the kind of data that should be entered.

The following events can be canceled by the CancelEvent action.

ApplyFilter | Dirty | MouseDown
BeforeDelConfirm | Exit | NoData
BeforeInsert | Filter | Open
BeforeUpdate | Format | Print
DblClick | KeyPress | Unload
Delete |  |

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.


 Close Action

Close Action

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

Setting

The Close action 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, Module, Data Access Page, Server View, Diagram, or Stored Procedure in the Object Type box in the Action Arguments section of the Macro window. To select the active window, leave this argument blank.
 | Note If closing a module in the Visual Basic Editor, you must use Module in the Object Type argument.
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.

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 {close.gif} for the object.

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

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


 CopyObject Action

CopyObject Action

You can use the CopyObject action to copy the specified database object to a different Microsoft Access database (.mdb) or to the same database or Microsoft Access project (.adp) 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
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.

Note This argument is only available in the Microsoft Access database environment (.mdb). When using this action in an Access project environment (.adp), the Destination Database argument must be blank.

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, Module. Data Access Page, Server View, Diagram, Stored Procedure. 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.

Remarks

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

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

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

Note When copying data access pages, the CopyObject action only copies the link to the associated .htm and not the actual .htm file.

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.


 DeleteObject Action

DeleteObject Action

You can use the DeleteObject action to delete a specified database object.

Setting

The DeleteObject action has the following arguments.

Action argument | Description
Object Type | The type of object to delete. Click Table, Query, Form, Report, Macro, Module, Data Access Page, Server View, or Diagram, Stored Procedure 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.

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.


 Echo Action

Echo Action

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

Setting

The Echo action has the following arguments.

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

Remarks

When Microsoft Access runs a macro, screen updating often shows information not essential to the functioning of the macro. When you set the Echo On argument to No, the macro runs without updating the screen. When the macro finishes, Microsoft Access automatically turns echo back on and repaints the window. The No setting for 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 98 or "Wait" in Windows NT) to provide a visual indication that the macro is running.

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


 FindNext Action

FindNext Action

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

Setting

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

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

Remarks

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

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

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

If the currently selected text is the same as the search text at the time the FindNext macro action is carried out, the search begins immediately following the selection in the same field as the selection, and in the same record. Otherwise the search begins at the start of the current record. This enables you to find multiple instances of the same search criteria that might appear in a single record.

However, note that if you use a command button to run a macro containing the FindNext action, the first instance of the search criteria will be found repeatedly. This is because clicking the command button changes the focus from the field containing the matching value. The FindNext action will then begin searching from the start of the record. The first instance of the search criteria will be found repeatedly in the same record. To avoid this problem, run the macro by using a technique that doesn't change the focus, such as a custom toolbar button or a key combination defined in an AutoKeys macro, or in the macro set the focus to the field containing the search criteria before you carry out the FindNext action.

The same behavior also occurs if you use a command button to run a macro containing the FindRecord action with the Find First argument set to No.

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


 FindRecord Action

FindRecord Action

You can use the FindRecord action to find the first instance of data that meets the criteria specified by the FindRecord arguments. This can be in the current record, in a succeeding or prior record, or in the first record. You can find records in the active table datasheet, query datasheet, form datasheet, or form.

Setting

The FindRecord action has the following arguments.

Action argument | Description
Find What | Specifies the data you want to find in the record. Enter the text, number, or date you want to find or type an expression, which is preceded by an equal sign (=), in the Find What box in the Action Arguments section of the Macro window. You can use wildcard characters. This is a required argument.
Match | Specifies where the data is located in the field. You can specify a search for data in any part of the field (Any Part Of Field), for data that fills the entire field (Whole Field), or for data located at the beginning of the field (Start Of Field). The default is Whole Field.
Match Case | Specifies whether the search is case-sensitive (uppercase and lowercase letters must match exactly). Click Yes (conduct a case-sensitive search) or No (search without matching uppercase and lowercase letters exactly). The default is No.
Search | Specifies whether the search proceeds from the current record up to the beginning of the records (Up); down to the end of the records (Down); or down to the end of the records and then from the beginning of the records to the current record, so all records are searched (All). The default is All.
Search As Formatted Specifies whether the search includes formatted data. Click Yes (Microsoft Access searches for the data as it's formatted and displayed in the field) or No (Microsoft Access searches for the data as it's stored in the database, which isn't always the same as it's displayed). The default is No.

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

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

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

If you set Match Case to Yes or Only Current Field to No, you must also set Search As Formatted to Yes.
Only Current Field | Specifies whether the search is confined to the current field in each record or includes all fields in each record. The current field search is faster. Click Yes (confine the search to the current field) or No (search in all fields in each record). The default is Yes.
Find First | Specifies whether the search starts at the first record or at the current record. Click Yes (start at the first record) or No (start at the current record). The default is Yes.

Remarks

When a macro runs the FindRecord action, Microsoft Access searches for the specified data in the records (the order of the search is determined by the setting of the Search argument). When Microsoft Access finds the specified data, the data is selected in the record.

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

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

When you want to find a record by using a macro, use the FindRecord action, not the RunCommand action with its argument set to run the Find command.

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

If the currently selected text is the same as the search text at the time the FindRecord macro action is carried out, the search begins immediately following the selection in the same field as the selection, and in the same record. Otherwise the search begins at the start of the current record. This enables you to find multiple instances of the same search criteria that might appear in a single record.

However, note that if you use a command button to run a macro containing the FindRecord action, the first instance of the search criteria will be found repeatedly. This is because clicking the command button changes the focus from the field containing the matching value. The FindRecord action will then begin searching from the start of the record. The first instance of the search criteria will be found repeatedly in the same record. To avoid this problem, run the macro by using a technique that doesn't change the focus, such as a custom toolbar button or a key combination defined in an AutoKeys macro, or in the macro set the focus to the field containing the search criteria before you carry out the FindRecord action.

The same behavior also occurs if you use a command button to run a macro containing the FindNext action.

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


 GoToControl Action

GoToControl Action

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

Note This action is not available for use with data access pages.

Setting

The GoToControl action has the following argument.

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

Remarks

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

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

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


 GoToPage Action

GoToPage Action

You can use the GoToPage action to move the focus in the active form to the first control on a specified page. You can use this action if you'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.

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.

Note The Right and Down arguments are in inches or centimeters, depending on the units set for Measurement System on the Number tab of the Regional Settings Properties dialog box in 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 in the following cases:

  • To move the focus to a page on a hidden form.

  • To move the focus from one page to another within the Tab control.

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


 GoToRecord Action

GoToRecord Action

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.

Action argument | Description
Object Type | The type of object that contains the record you want to make current. Click Table, Query, Form, Server View, or Stored Procedure 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.
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:
  • When the Record argument is Next or Previous, Microsoft Access moves the number of records forward or backward specified in the Offset argument.

  • When the Record argument is Go To, Microsoft Access moves to the record with the number equal to the Offset argument. The record number is shown in the record number box at the bottom of the 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.

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.


 Hourglass Action

Hourglass Action

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

Setting

The Hourglass action has the following argument.

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.

Remarks

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

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

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

  • In either case, you can choose another icon if you want.

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


 Maximize Action

Maximize Action

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.

Note This action cannot be applied to module windows in the Visual Basic Editor (VBE). For information about how to affect module windows see the WindowState property topic.

Setting

The Maximize action doesn't have any arguments.

Remarks

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

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

Tips

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

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

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


 Minimize Action

Minimize Action

You can use the Minimize action to reduce the active window to a small title bar at the bottom of the Microsoft Access window.

Note This action cannot be applied to module windows in the Visual Basic Editor (VBE). For information about how to affect module windows see the WindowState property topic.

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

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

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

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

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

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


 MoveSize Action

MoveSize Action

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

Setting

The MoveSize action has the following arguments.

Action argument | Description
Right | The new horizontal position of the window's upper-left corner, measured from the left edge of its containing window. 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.
Width | The window's new width.
Height | The window's new height.

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

You must enter a value for at least one argument.

Note Each measurement is in inches or centimeters, depending on the units set for Measurement System 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

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

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


 MsgBox Action

MsgBox Action

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

Setting

The MsgBox action has the following arguments.

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.

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:

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.

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


 OpenDiagram Action

OpenDiagram Action

You can use the OpenDiagram action to open a database diagram in Design view.

Setting

The OpenDiagram has the following arguments.

Action argument | Description
Diagram Name | The name of the database diagram to open. The Diagram Name box in the Action Arguments section of the Macro window shows all database diagrams in the current database. This is a required argument. If you run a macro containing the OpenDiagram action in a library database, Microsoft Access looks for the diagram with this name first in the library database, then in the current database.

Remarks

This action is similar to clicking the Design button in the Database window after selecting a database diagram on the Database Diagrams tab.

Tip You can select a database diagram in the Database window and drag it to a macro action row. This automatically creates an OpenDiagram action that opens the database diagram in Design view.

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


 OpenForm Action

OpenForm Action

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

Setting

The OpenForm action has the following arguments.

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

If you run a macro containing the OpenForm action in a library database, Microsoft Access looks for the form with this name first in the library database, then in the current database.
View | The view in which the form will open. Click Form, Design, Print Preview, or Datasheet 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.

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

  • If you leave this argument blank, 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.

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.


 OpenModule Action

OpenModule Action

You can use the OpenModule action to open a specified Visual Basic module at a specified procedure. This can be a Sub procedure, a Function procedure, or an event procedure.

Setting

The OpenModule action has the following arguments.

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.

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.


 OpenQuery Action

OpenQuery Action

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

Note This action is only available in the Microsoft Access database environment (.mdb). See the OpenView or OpenStoredProcedure actions if using the Access Project environment (.adp).

Setting

The OpenQuery action has the following arguments.

Action argument | Description
Query Name | The name of the query to open. The Query Name box in the Action Arguments section of the Macro window shows all queries in the current database. This is a required argument. If you run a macro containing the OpenQuery action in a library database, Microsoft Access looks for the query with this name first in the library database, then in the current database.
View | The view in which the query will open. Click Datasheet, Design, or Print Preview in the View box. The default is Datasheet.
Data Mode | The data entry mode for the query. This applies only to queries opened in Datasheet view. Click Add (the user can add new records but can't edit existing records), Edit (the user can edit existing records and add new records), or Read Only (the user can only view records). The default is Edit.

Remarks

If you 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.


 OpenReport Action

OpenReport Action

You can use the OpenReport action to open a report in Design view or Print Preview, or to print the report immediately. You can also restrict the records that are printed in the report.

Setting

The OpenReport action has the following arguments.

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

If you run a macro containing the OpenReport action in a library database, Microsoft Access looks for the report with this name first in the library database, then in the current database.
View | The view in which the report will open. Click Print (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.
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.

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

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

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


 OpenStoredProcedure Action

OpenStoredProcedure Action

You can use the OpenStoredProcedure action to open a stored procedure in Datasheet view, stored procedure Design view, or Print Preview. This action runs the named stored procedure when opened in Datasheet view.You can select data entry for the stored procedure and restrict the records that the stored procedure displays.

Setting

The OpenStoredProcedure action has the following arguments.

Action argument | Description
Procedure Name | The name of the stored procedure to open. The Procedure Name box box in the Action Arguments section of the Macro window shows all stored procedure in the current database. This is a required argument. If you run a macro containing the OpenStoredProcedure action in a library database, Microsoft Access looks for the stored procedure with this name first in the library database, then in the current database.
View | The view in which the stored procedure will open. Click Datasheet, Design, or Print Preview in the View box. The default is Datasheet.
Data Mode | The data entry mode for the stored procedure. This applies only to stored procedures opened in Datasheet view. Click Add (the user can add new records but can't view or edit existing records), Edit (the user can view or edit existing records and add new records), or Read Only (the user can only view records). The default is Edit.

Remarks

This action is similar to clicking the Run button or Design button in the Database window after selecting a data access page on the Stored Procedures tab.

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

Tips You can select a stored procedure in the Database window and drag it to a macro action row. This automatically creates an OpenStoredProcedure action that opens the stored procedure page in Datasheet view.

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

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


 OpenTable Action

OpenTable Action

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

Setting

The OpenTable action has the following arguments.

Action argument | Description
Table Name | The name of the table to open. The Table Name box in the Action Arguments section of the Macro window shows all tables in the current database. This is a required argument.
 | If you run 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.

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.


 OpenView Action

OpenView Action

You can use the OpenView action to open a View in Datasheet view, view Design view, or Print Preview. This action runs the named view when opened in Datasheet view.This action runs the named view when opened in Datasheet view.You can select data entry for the view and restrict the records that the view displays.

Setting

The OpenView action has the following arguments.

Action argument | Description
View Name | The name of the view to open. The View Name box in the Action Arguments section of the Macro window shows all views in the current database. This is a required argument. If you run a macro containing the OpenView action in a library database, Microsoft Access looks for the view with this name first in the library database, then in the current database.
View | The view in which the view will open. Click Datasheet, Design, or Print Preview in the View box. The default is Datasheet.
Data Mode | The data entry mode for the view. This applies only to views opened in Datasheet view. Click Add (the user can add new records but can't view or edit existing records), Edit (the user can view or edit existing records and add new records), or Read Only (the user can only view records). The default is Edit.

Remarks

This action is similar to clicking the Open button or Design button in the Database window after selecting a view on the Views tab.

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

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

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

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


 OutputTo Action

OutputTo Action

You can use the OutputTo action to output the data in the specified Microsoft Access database object (a datasheet, form, report, module, data access page) to a file in Microsoft Excel 98 (*.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 Active 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, Module, Data Access Page, Stored Procedure, or View 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 Active Server Pages (*.asp), Microsoft Excel (*.xls), Microsoft IIS (*.htx, *.idc), MS-DOS Text (*.txt), Rich Text Format (*.rtf), or Microsoft Data Access Page (*.html) in the box. Modules can be output only to MS-DOS text format. Data access pages can only be output in HTML format. Microsoft Internet Information Server and Microsoft Active 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 Active Server files, Microsoft Access will always create files with the standard .htx and .idc or .asp file name extensions. If you output data access pages, Microsoft Access will always create files with .html file name extensions. If you leave the Output File argument blank, Microsoft Access prompts you for an output file name.
Auto Start | Specifies whether you want the appropriate software 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 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 starts.
Template File | The path and file name of a file you want to use as a template for .html, .htx, or .asp files. The template file is a file containing HTML tags.

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:

  • 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

  • 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 a .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.

If you output the database object to Microsoft Active Server format, Microsoft Access creates a file in .asp format that contains information on how to access and format the object's data. Microsoft Active Server uses the .asp file to create a .html file with the data in the Microsoft Access object you output. You can use the Template File argument to specify a .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 Active Server (some of these rules also apply to the Microsoft Active Server format):

  • You can output data in table, query, and form datasheets. In the output file, all fields in the datasheet look as they do in Microsoft Access, except fields containing OLE objects. The columns for these fields are included in the output file, but the fields are blank.

  • For a control bound to a Yes/No field (a toggle button, option button, or check box), the output file displays the value –1 (Yes) or 0 (No).

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

  • If you output the data in a form in Form view, the output file always contains the form's Datasheet view.

  • If you output the data in a report, the only controls that are included in the output file are text boxes (for .xls output files), or text boxes and labels (for .rtf, .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.

  • Subreports are included in the output file, but subforms will be included when outputting to .asp, but only when outputting as a form (not a datasheet).

  • When you output a datasheet, form, or data access page 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.

For more information on rules and restrictions when outputting to .html files, see Export a datasheet to static HTML format and Export a report to static HTML format.

For more information on rules and restrictions when outputting to Microsoft Internet Information Server files, see Export a datasheet to dynamic HTML format and Export a form to dynamic HTML format.

For more information on rules and restrictions when outputting to Microsoft Active Server files, see Export a datasheet to dynamic HTML format, Export a form to dynamic HTML format, and Supported and unsupported form controls for dynamic ASP format.

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:

  • You can point to Size on the Format menu, then click To Fit to size the controls.

  • You should avoid overlapping controls or placing controls too close together.

  • You can point to Align on the Format menu, then click the appropriate command to align the controls on the report. Controls that 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 Export on the File menu and selecting the Save Formatted check box in the dialog box that's displayed. The action arguments correspond to the settings in the Export dialog box. The 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 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.

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


 PrintOut Action

PrintOut Action

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

Setting

The PrintOut action has the following arguments.

Action argument | Description
Print Range | The range to print. Click All (the user can print all of the object), Selection (the user can print the part of the object that'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.

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.


 Quit Action

Quit Action

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

Setting

The Quit action has the following argument.

Action argument | Description
Options | Specifies what happens to unsaved objects when you quit Microsoft Access. Click Prompt (to display dialog boxes that ask whether to save each object), 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.

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.


 Rename Action

Rename Action

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.
Object Type | The type of object you want to rename. Click Table, Query, Form, Report, Macro, Module, Data Access Page, Server View, Diagram, or Stored Procedure. 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.

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.


 RepaintObject Action

RepaintObject Action

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

Setting

The RepaintObject action has the following arguments.

Action argument | Description
Object Type | The type of object to repaint. Click Table, Query, Form, Report, Macro, Module, Data Access Page, Server View, Diagram, or Stored Procedures 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.

Remarks

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

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

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

Notes

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

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

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


 Requery Action

Requery Action

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

Setting

The Requery action has the following argument.

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.

Remarks

The Requery action does one of the following:

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

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

Note The Requery action does not effect the position of the record pointer.

Controls based on a query or table include:

  • List boxes and combo boxes.

  • Subform controls.

  • OLE objects, such as charts.

  • Controls containing domain aggregate functions, such as DSum.

If the specified control isn't based on a query or table, this action forces a recalculation of the control.

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

Note The Requery action requeries the source of the control or object. In contrast, the RepaintObject action repaints controls in the specified object but doesn't requery the database or display new records. The ShowAllRecords action not only requeries the active object, but it also removes any applied filters, which the Requery action 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 ActiveX Data Object (ADO) Requery method works the same way as the Microsoft Access Requery method.


 Restore Action

Restore Action

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

Note This action cannot be applied to module windows in the Visual Basic Editor (VBE). For information about how to affect module windows see the WindowState property topic.

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-right corner or clicking the Restore command on the window's Control menu.

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


 RunApp Action

RunApp Action

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.

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.

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 Microsoft 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 (formerly called OLE Automation).

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

In Windows 98, 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

RunCode Action

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

Setting

The RunCode action has the following argument.

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 In a Microsoft Access database (.mdb), click the Build button [image] to use the Expression Builder to select a function for this argument, to the right of the Function Name box. Click the desired function in the list in the Expression Builder.

Remarks

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

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

TestFunction()

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

Microsoft Access ignores the return value of the function.

Note You cannot call a Function procedure from a macro if the function name is the same as the module name.

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.


 RunCommand Action

RunCommand Action

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.

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.

Remarks

In Microsoft Access 97, the RunCommand action replaced 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.

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


 RunMacro Action

RunMacro Action

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

You can use this action:

  • To run a macro from within another macro.

  • To run a macro based on a certain condition.

  • To attach a macro to a custom menu command.

Setting

The RunMacro action has the following arguments.

Action argument | Description
Macro Name | The name of the macro to run. The Macro Name box in the Action Arguments section of the Macro window shows all macros (and macro groups) in the current database. If the macro is in a macro group, it'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.

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:

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

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

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

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

When you run 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

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

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

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.


 RunSQL Action

RunSQL Action

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.

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. Prior to Microsoft Access 97, previous versions of Microsoft Access have always included the query in a transaction when you ran this action. Starting with a BeginTrans method, executing the SQL statement, then concluding with a CommitTrans method. If you select No for this argument, the query may run faster.

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.

Query type | SQL statement
Action |
Append | INSERT INTO
Delete | DELETE
Make-table | SELECT...INTO
Update | UPDATE
Data-definition (SQL-specific) |
Create a table | CREATE TABLE
Alter a table | ALTER TABLE
Delete a table | DROP TABLE
Create an index | CREATE INDEX
Delete an index | DROP INDEX

You can also use an IN clause with these statements to modify data in another database.

Note To run a select query or crosstab query from a macro, use the View argument of the OpenQuery action to open an existing select query or crosstab query in Datasheet view. You can also run existing action queries and SQL-specific queries in the same way.

Tip To see the SQL equivalent of a Microsoft Access query, click SQL 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.


 Save Action

Save Action

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

Setting

The Save action has the following arguments.

Action argument | Description
Object Type | The type of object you want to save. Click Table, Query, Form, Report, Macro, Module, Data Access Page, Server View, Diagram, or Stored Procedure 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.

Remarks

The Save action works on all database objects that the user can explicitly open and save. The specified object must be open for the Save action to have any effect on the object. This action has the same effect as selecting an object and then saving it by clicking Save on the File menu, or clicking Save [image] 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 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:

  • A form in Form view or Datasheet view.

  • A report in Print Preview.

  • A module.

  • A server view in Datasheet view or Print Preview.

  • A data access page in Page view.

  • A table in Datasheet view or Print Preview.

  • A query in Datasheet view or Print Preview.

  • A stored procedure in Datasheet view or Print Preview.

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.


 SelectObject Action

SelectObject Action

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

Setting

The SelectObject action has the following arguments.

Action argument | Description
Object Type | The type of database object to select. Click Table, Query, Form, Report, Macro, Module, Data Access Pages, Server View, Diagram, or Stored Procedure 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.
 | Note The object names for ServerView, Diagram, or Stored Procedure objects are not displayed in the Object Name box of a Microsoft Access project (.adp).
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.

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


 SendKeys Action

SendKeys Action

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.

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.

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

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

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


 SendObject Action

SendObject Action

You can use the SendObject action to include the specified Microsoft Access datasheet, form, report, module, or data access page in an electronic mail message, where it can be viewed and forwarded. You can include objects in Microsoft Excel 2000 (*.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.

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, Module, or Data Access Page, Server View, or Stored Procedures 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), Rich Text Format (*.rtf), or Microsoft Access Data Access Page (*.html) in the Output Format box. Modules can be sent only in MS-DOS text format. Data access pages can only be sent in HTML format. If you leave this argument blank, Microsoft Access prompts you for the output format.
 | Note You can't include objects in Microsoft Active Server (*.asp) or Microsoft IIS (*.htx, *.idc) format, although these selections are displayed in the list
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 and an error occurs.
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.
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 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.

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 Mapivi32.dll. For information on how to install and set up Microsoft Access support for VIM mail applications, see the Microsoft Office 2000/Visual Basic Programmer's Guide. For information about how to obtain the Microsoft Office 2000/Visual Basic Programmer's Guide, click [image] .

The object in the mail message is in the selected output format. When you double-click the object, the appropriate software 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 starts.

The following rules apply when you use the SendObject action to include a database object in a mail message:

  • You can send table, query, and form datasheets. In the included object, all fields in the datasheet look as they do in Microsoft Access, except fields containing OLE objects. The columns for these fields are included in the object, but the fields are blank.

  • For a control bound to a Yes/No field (a toggle button, option button, or check box), the output file displays the value –1 (Yes) or 0 (No).

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

  • If you send a form in Form view, the included object always contains the form's Datasheet view.

  • If you send a report, the only controls that are included in the object are text boxes (for .xls files), or text boxes and labels (for .rtf, .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.

  • Subreports are included in the object, but subforms will be included when outputting to .asp, but only when outputting as a form (not a datasheet).

  • When you send a datasheet, form, or data access page 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.

For more information on rules and restrictions when including objects in HTML format, see Export a datasheet to static HTML format and Export a report to static HTML format.

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:

  • You can point to Size on the Format menu, then click To Fit to size the controls.

  • You should avoid overlapping controls or placing controls too close together.

  • You can point to Align on the Format menu, then click the appropriate command to align the controls on the report. Controls that 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.


 SetMenuItem Action

SetMenuItem Action

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

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. If you select a menu with this argument and leave the Command Index and Subcommand Index arguments blank, you can enable or disable the menu name itself. You can't, however, check or uncheck a menu name (Microsoft Access ignores the Check and Uncheck settings for the Flag argument for menu names).
Command Index | The index of the command for which you want to set the state. Enter an Integer value, starting from 0, for the index of the desired command in the menu selected 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).
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.

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.


 SetValue Action

SetValue Action

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

Note You cannot use the SetValue action to set the value of a Microsoft Access property that returns an object.

Setting

The SetValue action has the following arguments.

Action argument | Description
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.

Note In a Microsoft Access database (.mdb), click the Build button [image] to the right of the Item or Expression box to use the Expression Builder to create an expression for either of these arguments.

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.

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:

  • Bound controls and calculated controls on reports.

  • Calculated controls on forms.

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

Changing the value of or adding new data in a control 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.


 SetWarnings Action

SetWarnings Action

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

Setting

The SetWarnings action has the following argument.

Action argument | Description
Warnings On | Specifies whether system messages are displayed. Click Yes (to turn on system messages) or No (not to turn off system messages) in the Warnings On box in the Action Arguments section of the Macro window. The default is No.

Remarks

You can use this action to prevent modal warnings and message boxes from stopping the macro. However, error messages are always displayed. Also, Microsoft Access displays any dialog boxes that require input other than just choosing a button (such as OK, Cancel, Yes, or No) — 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.


 ShowAllRecords Action

ShowAllRecords Action

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

Setting

The ShowAllRecords action doesn't 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 Remove Filter [image] 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.


 ShowToolbar Action

ShowToolbar Action

You can use the ShowToolbar action to display or hide a built-in toolbar or a custom toolbar. You can display a built-in toolbar in all Microsoft Access windows or just the view in which the toolbar is normally displayed (for example, the Form View toolbar in Form view).

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.
 | 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 to display a form or report's custom toolbar in all Microsoft Access windows when the form or report becomes active,Where Appropriate to display a form or report's custom toolbar for the active window displaying the active form or report, or No to hide the toolbar in all Microsoft Access windows.

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.

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.


 StopAllMacros Action

StopAllMacros Action

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.

This action isn't available in Visual Basic.


 StopMacro Action

StopMacro Action

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.


 TransferDatabase Action

TransferDatabase Action

You can use the TransferDatabase action to import or export data between the current Microsoft Access database (.mdb) or Access project (.adp) and another database. For Microsoft Access databases (.mdb) 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.

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.
 | Note The Link transfer type is not supported for Access projects (.adp).
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.
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).
 | 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, Module, Data Access Page, Server View, Diagram, or Stored Procedures 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.
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.

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 2000, if you import a table from another Microsoft Access database (.mdb) 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 databases. You can link to tables in these FoxPro databases if you have a FoxPro ODBC driver.

The TransferDatabase action is similar to pointing to Get External Data or 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.


 TransferSpreadsheet Action

TransferSpreadsheet Action

You can use the TransferSpreadsheet action to import or export data between the current Microsoft Access database (.mdb) or Access project (.adp) 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.

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.
 | Note The Link transfer type is not supported for Access projects (.adp).
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 8.
 | Note 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.
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.
 | In Microsoft Access 2000, 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, 8.0 or Excel 2000 workbook. In that case, Microsoft Access copies the exported data to the next available new worksheet in the workbook.
 | If you are importing from or linking to a Microsoft Excel version 5.0, 7.0, 8.0 or Excel 2000 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 does not work in Microsoft Access 97 or Microsoft Access 2000). If you are importing from or linking to a Microsoft Excel version 5.0, 7.0, Excel 8.0, or Excel 2000 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.

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 corresponding field in the table.

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


 TransferText Action

TransferText Action

You can use the TransferText action to import or export text between the current Microsoft Access database (.mdb) or Access project (.adp) and a text file. You can also link the data in a text file to the current 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.
 | 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.
 | Note Only Import Delimited, Import Fixed Width, Export Delimited, Export Fixed Width, or Export Word for Windows Merge transfer types are supported in an Access project (.adp)..
Specification Name | The specification name for the set of options that determines how a text file is imported, exported, or linked. For a fixed-width text file, you must either specify an argument or use a schema.ini file, which must be stored in the same folder as the imported, linked, or exported text file.
 | You can use the Import or Link Tables subcommand of the Get External Data command or the Export command on the File menu to create a specification for a particular type of text file. For example, 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 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 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 2000, 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.
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.
 | 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.
Code Page | The name of character set used with the code page.

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.

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


 Microsoft Access Constants - Overview

Microsoft Access Constants — Overview

General

A constant represents a numeric or string value that doesn't change. You can use constants to improve the readability of your Visual Basic code and to make your code easier to maintain. In addition, the use of intrinsic constants ensures that code will continue to work even if the underlying values that the constants represent are changed in later releases of Microsoft Access.

Microsoft Access supports three types of constants:

  • Symbolic constants, which you create by using the Const statement and use in modules.

  • Intrinsic constants, which are part of Microsoft Access or a referenced library.

  • System-defined constants: True, False, and Null.

Symbolic Constants

Often, you'll use the same values repeatedly in your code, or you'll find that the code depends on certain numbers that have no obvious meaning. In these cases, you can make the code much easier to read and maintain by using symbolic or user-defined constants, which enable you to use a meaningful name in place of a number or string.

Once you have created a constant by using the Const statement, you can't modify it or assign a new value to it. You also can't create a constant that has the same name as an intrinsic constant.

The following examples show some of the ways you can use the Const statement to declare numeric and string constants:

Const conPI = 3.14159265                ' Pi equals this number.
Const conPI2 = conPI * 2                ' A constant used to create another.
Const conVersion = "Version 7.0"        ' Declare a string constant.

Intrinsic Constants

In addition to the constants you declare with the Const statement, Microsoft Access automatically declares a number of intrinsic constants and provides access to the Visual Basic for Applications (VBA) constants, and ActiveX Data Objects (ADO) constants. You can also use constants in other referenced object libraries. For more information on adding references see Setting References to Type Libraries.

Any intrinsic constant can be used in a macro or Visual Basic. These constants are available at all times. The specific built-in constants used with a particular function, method, or property are described in the Help topic for that function, method, or property.

Note You can use the Object Browser to view lists of intrinsic constants from all available object libraries.

Intrinsic constants have a two letter prefix identifying the object library that defines the constant. Constants from the Microsoft Access library are prefaced with "ac"; constants from the ADO library are prefaced with "ad"; and constants from the Visual Basic library are prefaced with "vb". For example:

  • acForm

  • adAddNew

  • vbCurrency

Note Because the values represented by the intrinsic constants may change in future versions of Microsoft Access, you should use the constants instead of their actual values. You can, however, display the actual value of a constant by choosing the constant in the Object Browser or by typing ?constantname in the Immediate window.

You can use intrinsic constants wherever you can use symbolic, or user-defined constants, including in expressions. The following example shows how you might use the intrinsic constant vbCurrency to determine whether the variable varNum is a Variant for which the VarType function returns 6 (Currency):

Dim varNum As Variant
If VarType(varNum) = vbCurrency Then
    Debug.Print "varNum contains Currency data."
Else
    Debug.Print "varNum doesn't contain Currency data."
End If

There are several categories of intrinsic constants. For a list of the intrinsic constants in a particular category, click the category below:

  • The action constants

  • The ADO constants

  • The DAO constants

  • The event procedure constants

  • The Keycode constants

  • The miscellaneous constants

  • The RunCommand method constants (these are a subset of the action constants)

  • The security constants

  • The Visual Basic constants

  • The VarType function constants

System-Defined Constants

You can use the system-defined constants True, False, and Null anywhere in Microsoft Access. For example, you can use True in the following macro condition expression. The condition is met if the Visible property setting for the Employees form equals True.

Forms!Employees.Visible = True

You can use the constant Null anywhere in Microsoft Access. For example, you can use Null to set the DefaultValue property for a form control by using the following expression:

=Null


 Style for Intrinsic Constants

Style for Intrinsic Constants

In Microsoft Access 2000, all intrinsic constants are contained in type libraries and are visible in the Object Browser. Microsoft Access includes type libraries for Microsoft Access, ActiveX Data Objects (ADO), Data Access Objects (DAO), and Visual Basic. Each of these type libraries includes intrinsic constants.

Additionally, intrinsic constants in Microsoft Access 2000 are a mix of lowercase and uppercase, and parts of the constant are concatenated rather than separated by underscores. For example, the constant A_NORMAL in versions 1.x and 2.0 is now acNormal.

Intrinsic constants in databases created with previous versions of Microsoft Access won't automatically be converted to the new constant format, but old constants will continue to work without errors. However, it's recommended that you use the new format when writing new code.


 Intrinsic Constants as Bit Masks

Intrinsic Constants as Bit Masks

To test for the Button or Shift arguments, use a bit mask.

The Button argument is a bit field with bits corresponding to the left mouse button (bit 0), right mouse button (bit 1), and middle mouse button (bit 2). These bits correspond to the values 1, 2, and 4, respectively. Only one of the bits is set, indicating which button triggered the event.

The intrinsic constants that Microsoft Access provides for the Button argument have the following values.

Constant | Value
acLeftButton | 1
acRightButton | 2
acMiddleButton | 4

The Shift argument is a bit field, with the least significant bits corresponding to the SHIFT key (bit 0), the CTRL key (bit 1), and the ALT key (bit 2 ). These bits correspond to the values 1, 2, and 4, respectively. The Shift argument indicates the state of these keys. Some, all, or none of the bits can be set, indicating that some, all, or none of the keys is pressed. For example, if both CTRL and ALT were pressed, the value of the Shift argument would be 6.

The intrinsic constants that Microsoft Access provides for the Shift argument have the following values.

Constant | Value
acShiftMask | 1
acCtrlMask | 2
acAltMask | 4

You can use the constants to test for any combination of buttons and keys without having to figure out the unique bit field value for each combination. A bit is set if the button or key is pressed.


Events and Event Properties Reference

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

Grouped by Task

Data Events | Keyboard Events
Error and Timing Events | Mouse Events
Filter Events | Print Events
Focus Events | Window Events

Listed Alphabetically

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


New Events

Events that were added to Visual Basic in Microsoft Access 2000 are listed in the following table.

Dirty


 Activate, Deactivate Events

Activate, Deactivate Events

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

  • 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 Activate event doesn't occur when a form receives focus back from a dialog box, popup, or another form. 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 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


 Delete, BeforeDelConfirm, AfterDelConfirm Events

Delete, BeforeDelConfirm, AfterDelConfirm Events

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

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

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

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.


 BeforeInsert, AfterInsert Events

BeforeInsert, AfterInsert Events

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

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

Event | Occurs when
BeforeInsert | User types the first character in a new record.
BeforeUpdate | User updates the record.
AfterUpdate | Record is updated.
AfterInsert | Record updated is a new record.

If the first character in a new record is typed into a text box or combo box, the BeforeInsert event occurs before the Change event.


 BeforeUpdate, AfterUpdate Events

BeforeUpdate, AfterUpdate Events

  • The BeforeUpdate event occurs before changed data in a control or record is updated.

  • The AfterUpdate event occurs after changed data in a control or record is updated.

Notes

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

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

  • These events don't apply to option buttons, check boxes, or toggle buttons in an option group. They apply only to the option group itself.

Remarks

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.

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:

  • Involve conditions for more than one value on a form.

  • Display different error messages for different data entered.

  • Can be overridden by the user.

  • Contain references to controls on other forms or contain user-defined functions.

Note To perform simple validations, or more complex validations such as requiring a value in a field or validating more than one control on a form, you can use the ValidationRule property for controls and the ValidationRule and Required properties for fields and records in tables.


 ApplyFilter Event

ApplyFilter Event

The ApplyFilter event can occur within a Microsoft Access project (.adp) or Access database (.mdb).

Within an Access database, an ApplyFilter event occurs when the user does one of the following:

  • 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 Apply Filter Filter object 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).

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

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

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

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

  • Closes the Advanced Filter/Sort window or the Filter By Form window.

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

Within an Access project, an ApplyFilter event occurs when the user does one of the following:

  • 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 Apply Filter Filter object on the toolbar. This applies the most recently created filter (created by using the Filter By Form feature).

  • Clicks Apply Server Filter on the Records menu in Form view, clicks Apply Server Filter on the Filter menu in the Filter window, or clicks Apply Server Filter [image] on the toolbar. This applies the most recently created filter (created by using the Server Filter By Form feature).

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

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

  • Clicks Filter By Selection or Filter Excluding Selection or enters a value or expression in the Filter For box on the shortcut menu when a bound control has the focus.

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:

  • 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 or ServerFilter property value to make sure this criteria is included in the WHERE clause expression.

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

  • 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, Filter By Form, or Server 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 or ServerFilter property.

Note The ApplyFilter event doesn't occur when the user does one of the following:

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

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

  • Sets the Filter or ServerFilter property or FilterOn or ServerFilterByForm property in a macro or Visual Basic (although you can set these properties in an ApplyFilter macro or event procedure).


 Change Event

Change Event

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

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

  • This 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 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:

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

  • Avoid creating two or more controls having Change events that affect each other — 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.


 Click Event

Click Event

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

Notes

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

  • This event doesn't apply to check boxes, option buttons, or toggle buttons in an option group. It applies only to the option group itself.

  • This event doesn't apply to a label attached to another control, such as the label for a text box. It applies only to "freestanding" labels. Clicking an attached label has the same effect as clicking the associated control. The normal events for the control occur, not any events for the attached label.

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

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

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

  • Selects an item in a combo box or list box, either by pressing the arrow keys and then pressing the ENTER key or by clicking the mouse button.

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

  • Presses the ENTER key on a form that has a command button whose Default property is set to Yes.

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

  • Presses a control's access key. For example, if a command button's Caption property is set to &Go, pressing ALT+G triggers the event.

Typically, you attach a Click event procedure or macro to a command button to carry out commands and 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.


 Open, Close Events

Open, Close Events

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

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


 Current Event

Current Event

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.

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


 DblClick Event

DblClick Event

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

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

  • This event doesn't apply to check boxes, option buttons, or toggle buttons in an option group. It applies only to the option group itself.

  • This event doesn't apply to a label attached to another control, such as the label for a text box. It applies only to "freestanding" labels. Double-clicking an attached label has the same effect as double-clicking the associated control. The normal events for the control occur, not any events for the attached label.

Remarks

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.


 Dirty Event

Dirty Event

The Dirty event occurs when the contents of a form 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

  • Modifying a record within a form by using a macro or Visual Basic doesn't trigger this event. You must type the data directly into the record or set the control's Text property.

  • This event applies only to bound forms, not an unbound form or report.

Remarks

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

By running a macro or event procedure when a Dirty event occurs, you can determine if the record can be changed. You can also display a message and ask for edit permission.

Changing the data in a record by using the keyboard causes keyboard events to occur in addition to control events like the Dirty 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 Þ Dirty Þ KeyUp

The BeforeUpdate and AfterUpdate events for a record occur after you have entered the new or changed data in the record and moved to another record (or clicked Save Record on the Records menu), and therefore after the Dirty event for the record.


 Enter, Exit Events

Enter, Exit Events

  • The Enter event occurs before a control actually receives the focus from a control on the same form.

  • The Exit event occurs just before a control loses the focus to another control on the same form.

Notes

  • The Enter and Exit events apply only to controls on a form, not controls on a report.

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

ß

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.


 Error Event

Error Event

The Error event occurs when a run-time error is produced in Microsoft Access when a form or report has the focus. This includes Microsoft Jet database engine errors, but not run-time errors in Visual Basic.

Remarks

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.


 Filter Event

Filter Event

The Filter event can occur within a Microsoft Access project (.adp) or Access database (.mdb).

Within an Access database, a Filter event occurs when the user does one of the following:

  • On the Records menu in Form view, points to Filter and then clicks Filter By Form, or clicks Filter By Form [image] on the toolbar. This opens the Filter By Form window, where you can create a filter based on the fields in the form.

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

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

Within an Access project, a Filter event occurs when the user does one of the following:

  • On the Records menu in Form view, points to Filter and then clicks Filter By Form, or clicks Filter By Form [image] on the toolbar. This opens the Filter By Form window, where you can create a filter based on the fields in the form.

  • On the Records menu in Form view, points to Filter and then clicks Server Filter By Form [image] on the toolbar. This opens the Server Filter By Form window, where you can quickly create a server filter based on the fields in the form.

  • The Advanced Filter/Sort window is not available in an Access project.

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:

  • Remove any previous filter for the form. To do this, set the Filter or ServerFilter 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, when you use the Filter By Selection feature, the criteria you use (the selected text in the form) is added to the Filter or ServerFilter property WHERE clause expression, and appears in both the Filter By Form window and the Advanced Filter/Sort window or the Server Filter By Form window. You can remove these old criteria by using the Filter event.

  • Enter default settings for the new filter. To do this, set the Filter or ServerFilter property to include these criteria. For example, you may want all filters for a Products form to display only current products (products for which the Discontinued control in the Products form isn't selected).

  • Use your own custom filter window instead of one of the Microsoft Access filter windows. When the Filter event occurs, you can open your own custom form and use the entries on this form to set the Filter or ServerFilter property and filter the original form. When the user closes this custom form, set the FilterOn or ServerFilterByForm property of the original form to True (–1) to apply the filter. Canceling the Filter event prevents the Microsoft Access filter window from opening.

  • Prevent certain controls on the form from appearing or being used in the Filter By Form or Server Filter By Form window. If you hide or disable a control in the Filter macro or event procedure, the control is hidden or disabled in the Filter By Form or Server Filter By Form window, and can't be used to set filter criteria. You can then use the ApplyFilter event to show or enable this control after the filter is applied, or when the filter is removed from the form.


 FirstPage, LastPage, NextPage, PrevPage Events

FirstPage, LastPage, NextPage, PrevPage Events

The FirstPage, LastPage, NextPage, PrevPage events occurs when the user clicks the Snapshot Viewer control navigation buttons or uses the control's pop-up menu.

Notes

  • These events have no arguments.

  • These events are triggered only when navigation occurs from the navigation buttons or the pop-up menu. They do not trigger when pages are navigated programmatically.


 Format Event

Format Event

The Format event occurs when Microsoft Access determines which data belongs in a report section, but before Microsoft Access formats the section for previewing or printing.

Remarks

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

A Format event occurs for each section in a report. This allows you to create complex running calculations by using data from each section, including sections that aren't printed.

For report detail sections, the Format event occurs for each record in the section just before Microsoft Access formats the data in the record. A Format macro or event procedure has access to the data in the current record.

For report group headers, the Format event occurs for each new group, and a Format macro or event procedure has access to the data in the group header and the data in the first record in the detail section. For report group footers, the Format event occurs for each new group, and a Format macro or event procedure has access to the data in the group footer and the data in the last record in the detail section.

By running a macro or an event procedure when the Format event occurs, you can use data in the current record to make changes to the report that affect page layout. For example, you can display or hide a congratulatory message next to a salesperson's monthly sales total in a sales report, depending on the sales total. After the control is displayed or hidden, Microsoft Access formats the section by using the values of format properties, such as CanGrow, CanShrink, HideDuplicates, KeepTogether, and Visible.

For changes that don't affect page layout or for event procedures or macros that should run only after the data on a page has been formatted, such as a macro that prints page totals, use the Print event for the report section.

There are times when Microsoft Access must return to previous sections on a report to perform multiple formatting passes. When this happens, the Retreat event occurs as the report returns to each previous section, and the Format event occurs more than once for each section. You can run a macro or event procedure when the Retreat event occurs to undo any changes that you made when the Format event occurred for the section. This is useful when your Format macro or event procedure carries out actions, such as calculating page totals or controlling the size of a section, that you want to perform only once for each section.


 GotFocus, LostFocus Events

GotFocus, LostFocus Events

  • The GotFocus event occurs when a form or control receives the focus.

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


 Initialize Event (Microsoft Access)

Initialize Event

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:

  • Create a new instance of a class directly by using the New keyword with the Set statement.

  • Dimension an object variable using the New keyword and creating an instance of a class indirectly by setting or returning a property or applying a method defined in the class module.


 ItemAdded Event

ItemAdded Event

The ItemAdded event occurs when a reference is added to the project from Visual Basic.

Notes

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

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


 ItemRemoved Event

ItemRemoved Event

The ItemRemoved event occurs when a reference is removed from the project.

Notes

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

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


 KeyDown, KeyUp Events

KeyDown, KeyUp Events

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

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

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:

  • Extended character keys, such as function keys.

  • Navigation keys, such as HOME, END, PAGE UP, PAGE DOWN, UP ARROW, DOWN ARROW, RIGHT ARROW, LEFT ARROW, and TAB.

  • Combinations of keys and standard keyboard modifiers (SHIFT, CTRL, or ALT keys).

  • The numeric keypad and keyboard number keys.

The KeyDown and KeyUp events don't occur when you press:

  • The ENTER key if the form has a command button for which the Default property is set to Yes.

  • The ESC key if the form has a command button for which the Cancel property is set to Yes.

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.

For more information, see Order of events for keystrokes and mouse clicks.

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.


 KeyPress Event

KeyPress Event

The KeyPress event occurs when the user presses and releases a key or key combination that corresponds to an ANSI code while a form or control has the focus. This event also occurs if you send an ANSI keystroke to a form or control 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.

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)

ß

KeyUp (for the control)

For more information, see Order of events for keystrokes and mouse clicks.


 Load, UnLoad Events

Load, Unload Events

  • The Load event occurs when a form is opened and its records are displayed.

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

  • Starting an application.

  • Opening a form by clicking Open in the Database window.

  • Running the OpenForm action in a macro.

The Unload event is caused by user actions such as:

  • Clicking a Form window's Close button or clicking Close on the File menu or a form's Control menu.

  • Running the Close action in a macro.

  • Quitting an application by right-clicking the application's taskbar button and then clicking Close.

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

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.


 MouseDown, MouseUp Events

MouseDown, MouseUp Events

  • The MouseDown event occurs when the user presses a mouse button.

  • The MouseUp event occurs when the user releases a mouse button.

Notes

  • The MouseDown and MouseUp events apply only to forms, form sections, and controls on a form, not controls on a report.

  • 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].

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:

  • If a mouse button is pressed while the pointer is over a form or control, that object receives all mouse events up to and including the last MouseUp event.

  • If mouse buttons are pressed in succession, the object that receives the mouse event after the first press receives all mouse events until all buttons are released.

To respond to an event caused by moving the mouse, you use a MouseMove event.


 MouseMove Event

MouseMove Event

The MouseMove event occurs when the user moves the mouse.

Notes

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

  • This event doesn't apply to a label attached to another control, such as the label for a text box. It applies only to "freestanding" labels. Moving the mouse pointer over an attached label has the same effect as moving the pointer over the associated control. The normal events for the control occur; no separate events occur for the attached label.

Remarks

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

  • Moving a form can trigger a MouseMove event even if the mouse is stationary. MouseMove events are generated when the form moves underneath the pointer. If a macro or event procedure moves a form in response to a MouseMove event, the event can cascade (that is, continually generate MouseMove events).

  • If two controls are very close together, and you move the mouse pointer quickly over the space between them, the MouseMove event may not occur for the space (for example, this might be the MouseMove event for the form section). In such cases, you may need to respond to the MouseMove event in the contiguous control, as well as in the form section.

To run a macro or event procedure in response to pressing and releasing the mouse buttons, you use the MouseDown and MouseUp events.


 NoData Event

NoData Event

The NoData event occurs after Microsoft Access formats a report for printing that has no data (the report is bound to an empty recordset), but before the report is printed. You can use this event to cancel printing of a blank report.

Remarks

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.


 NotInList Event

NotInList Event

The NotInList event occurs when the user enters a value in the text box portion of a combo box that isn't in the combo box list.

Note The NotInList event applies only to controls on a form, not controls on a report.

Remarks

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


 Page Event

Page Event

The Page event occurs after Microsoft Access formats a page of a report for printing, but before the page is printed. You can use this event to draw a border around the page, or add other graphic elements to the page.

Remarks

To run a macro or event procedure when this event occurs, set the OnPage property to the 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.


 Print Event

Print Event

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


 Progress Event

Progress Event

The Progress event occurs while a snapshot file is being loaded.

Syntax

Sub controlname_Progress(ByVal amount As Long)

The Progress event has the following arguments.

Argument | Description
controlname | The name of the Snapshot control object.
amount | An Integer value between 0 and 100 representing the percentage of the snapshot file that has been loaded.

Remarks

The SnapshotPath property can point to a snapshot file with an HTTP or FTP address. Depending on the size of the file and the speed of your Internet or intranet connection, it may take some time to download the complete file.

You can use the Amount argument of the Progress event to display a progress meter showing the status of the file download operation.

You can use the ReadyState propety to determine when a snapshot file has been completely loaded into the Snapshot Viewer control.


 ReadyStateChange Event

ReadyStateChange Event

The ReadyStateChange event occurs whenever a snapshot control's ReadyState property changes.

Syntax

Sub controlname_ReadyStateChange(ByVal readystate As Long)

The ReadyStateChange event has the following arguments.

Argument | Description
controlname | The name of the Snapshot control object.
readystate | An Integer value between 0 and 4 representing the current value of the ReadyState property.

Remarks

This event can by used to capture changes to the ReadyState property.


 Resize Event

Resize Event

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

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.


 Retreat Event

Retreat Event

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

Under certain circumstances, Microsoft Access must return to a previous report section to determine where certain controls and sections are on a report and whether they will fit in a given space. Examples include:

  • Groups (except for page headers and footers) for which the KeepTogether property is set to either Whole Group or With First Detail.

  • Subreports or subforms for which the CanGrow and/or CanShrink property is set to Yes.

  • Sections on the last page of a report.

In these situations, the Format event occurs as Microsoft Access determines how the sections will fit on the printed page (however, a Print event doesn't occur because the sections aren't being printed yet). If the sections can't be printed, Microsoft Access backs up to the necessary location so that the sections can actually be printed on the following page. The Retreat event occurs for each section past which Microsoft Access retreats. The Format event for each section then occurs again as Microsoft Access prepares to 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).


 Terminate Event (Microsoft Access)

Terminate Event

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.


 Timer Event

Timer Event

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.


 Updated Event

Updated Event

The Updated event occurs when an OLE object's data has been modified.

Note The Updated event applies only to controls on a form, not controls on a report.

Remarks

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

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

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


Functions Reference

The following reference lists all the functions alphabetically.

Note Functions marked with an (*) should not be used within a data access page against a stored query.

A–C

Abs (VBA) | Cos (VBA)
Array (VBA) | Count (DAO)
Asc (VBA) | Atn (VBA)
Avg (DAO) | CBool (VBA)
CreateObject (VBA) | CByte (VBA)
CCur (VBA) | CDate (VBA)
CSng (VBA) | CDbl (VBA)
CStr (VBA) | CDec (VBA)
CurDir (VBA) | Choose (VBA)
Chr (VBA) | CInt (VBA)
CVar (VBA) | CLng (VBA)
CVDate (VBA) | CVErr (VBA)
Command* |

D–H

Date (VBA) | DVar
DateAdd (VBA) | DVarP
DateDiff (VBA) | Environ* (VBA)
DatePart (VBA) | EOF (VBA)
DateSerial (VBA) | Error (VBA)
DateValue (VBA) | EuroConvert
DAvg | Eval
Day (VBA) | Exp (VBA)
Dcount | FileAttr (VBA)
DDB (VBA) | FileDateTime* (VBA)
DDE | FileLen* (VBA)
DDEInitiate | First (DAO)
DDERequest | Fix (VBA)
DDESend | Format (VBA)
DFirst | FreeFile (VBA)
Dir* (VBA) | FV (VBA)
DLast | GetAllSettings (VBA)
DLookup | GetAttr* (VBA)
DMax | GetObject (VBA)
DMin | GetSetting* (VBA)
DoEvents (VBA) | GUIDFromString
DStDev | Hex (VBA)
DStDevP | Hour (VBA)
DSum | HyperlinkPart

I–R

IIf (VBA) | Log (VBA)
IMEStatus (VBA) | LTrim (VBA)
Input* (VBA) | Max (DAO)
InputBox (VBA) | Mid (VBA)
InStr (VBA) | Min (DAO)
Int (VBA) | Minute (VBA)
IPmt (VBA) | MIRR (VBA)
IRR (VBA) | Month (VBA)
IsArray (VBA) | MsgBox (VBA)
IsDate (VBA) | Now (VBA)
IsEmpty (VBA) | NPer (VBA)
IsError (VBA) | NPV (VBA)
IsMissing (VBA) | Nz
IsNull (VBA) | Oct (VBA)
IsNumeric (VBA) | Partition (VBA)
IsObject (VBA) | Pmt (VBA)
Last (DAO) | PPmt (VBA)
LBound (VBA) | PV (VBA)
LCase (VBA) | QBColor (VBA)
Left (VBA) | Rate (VBA)
Len (VBA) | RGB (VBA)
Right (VBA) | Loc (VBA)
Rnd (VBA) | LOF (VBA)
RTrim (VBA) |

S–Z

Second (VBA) | SYD (VBA)
Seek (VBA) | Tab (VBA)
Sgn (VBA) | Tan (VBA)
Shell* (VBA) | Time (VBA)
Sin (VBA) | Timer (VBA)
SLN (VBA) | TimeSerial (VBA)
Space (VBA) | TimeValue (VBA)
Spc (VBA) | Trim (VBA)
Sqr (VBA) | TypeName (VBA)
StDev (DAO) | UBound (VBA)
StDevP (DAO) | UCase (VBA)
Str (VBA) | Val (VBA)
StrComp (VBA) | Var (DAO)
StrConv (VBA) | VarP (DAO)
String (VBA) | VarType (VBA)
StringFromGUID | Weekday (VBA)
Sum (DAO) | Year (VBA)
Switch (VBA) |


 Command Function

Command Function

You can use the Command function to return the argument portion of the command line used to launch Microsoft Access.

Syntax

Command

Remarks

When Microsoft Access is launched from the command line, any portion of the command line that follows the /cmd option is passed to the program as the command-line argument. You can use the Command function to return the argument that has been passed.

To change a command-line argument once a database has been opened, click Options on the Tools menu. On the 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()


 DAvg Function

DAvg Function

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

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

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

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

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


 DCount Function

DCount Function

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.

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.

Remarks

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.

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.


 DDE Function

DDE Function

You can use the DDE function to initiate a dynamic data exchange (DDE) conversation with another application, request an item of information from that application, and display that information in a control on a form or report.

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.

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.

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.

Microsoft Windows and your computer's memory and resources determine the maximum number of DDE conversations that can be open simultaneously. 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 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.

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


 DDEInitiate Function

DDEInitiate Function

You can use the DDEInitiate function to begin a dynamic data exchange (DDE) conversation with another application. The DDEInitiate function opens a DDE channel for transfer of data between a DDE server and client application.

For example, if you wish to transfer data from a Microsoft Excel spreadsheet to a Microsoft Access database, you can use the DDEInitiate function to open a channel between the two applications. In this example, Microsoft Access acts as the client application, and Microsoft Excel acts as the server application.

Syntax

DDEInitiate(application, topic)

The DDEInitiate function has the following arguments.

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.

Remarks

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.


 DDERequest Function

DDERequest Function

You can use the DDERequest function over an open dynamic data exchange (DDE) channel to request an item of information from a DDE server application.

For example, if you have an open DDE channel between Microsoft Access and Microsoft Excel, you can use the DDERequest function to transfer text from a Microsoft Excel spreadsheet to a Microsoft Access database. In this example, Microsoft Access acts as the client application, and Microsoft Excel acts as the server application.

Syntax

DDERequest(channum, item)

The DDERequest function has the following arguments.

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.

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.


 DDESend Function

DDESend Function

You can use the DDESend function to initiate a dynamic data exchange (DDE) conversation with another application and send an item of information to that application from a control on a form or report.

For example, you can use the DDESend function in the ControlSource property of a text box to send the data displayed in that text box to a specified cell in a Microsoft Excel spreadsheet.

Syntax

DDESend(application, topic, item, data)

The DDESend function has the following arguments.

Argument | Description
application | 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.
data | A string or expression containing the data to send to application.

Remarks

The DDESend function initiates a DDE conversation with application and topic, and identifies item as the data item that 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.

Microsoft Windows and your computer's memory and resources determine the maximum number of DDE conversations that can be open simultaneously. 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.
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.


 DFirst, DLast Functions

DFirst, DLast Functions

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

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 topic. From Visual Basic, you can also create a Recordset object, and use the MoveFirst or MoveLast method to return the first or last record in a set of records.


 DLookup Function

DLookup Function

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.

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.

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 Variant
varX = DLookup("[LastName]", "Employees", "[EmployeeID] = 1")

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

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

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


 DMin, DMax Functions

DMin, DMax Functions

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

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


 Domain Aggregate Functions

Domain Aggregate Functions

Aggregate functions provide statistical information about sets of records (a domain). For example, you can use an aggregate function to count the number of records in a particular set of records, or to determine the average of values in a particular field.

The two types of aggregate functions, domain aggregate functions and SQL aggregate functions, provide similar functionality but are used in different situations. The SQL aggregate functions can be included in the syntax of an SQL statement, but can't be called directly from Visual Basic. Conversely, the domain aggregate functions can be called directly from Visual Basic code. They can also be included in an SQL statement, but an SQL aggregate function is generally more efficient.

If you are performing statistical calculations from within code, you must use the domain aggregate functions. You can also use the domain aggregate functions to specify criteria, update values, or create calculated fields in a query expression. You can use either the SQL aggregate or domain aggregate functions in a calculated control on a form or report.

The domain aggregate functions include:

DAvg Function

DCount Function

DLookup Function

DFirst, DLast Functions

DMin, DMax Functions

DStDev, DStDevP Functions

DSum Function

DVar, DVarP Functions


 DStDev, DStDevP Functions

DStDev, DStDevP Functions

You can use the DStDev and DStDevP functions to estimate the standard deviation across a set of values in a specified set of records (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
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.

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:

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


 DSum Function

DSum Function

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.

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.


 DVar, DVarP Functions

DVar, DVarP Functions

You can use the DVar and DVarP functions to estimate variance across a set of values in a specified set of records (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.
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.

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.


 EuroConvert Function

EuroConvert Function

You can use the EuroConvert function to convert a number to euro or from euro to a participating currency. You can also use it to convert a number from one participating currency to another by using the euro as an intermediary (triangulation). The EuroConvert function uses fixed conversion rates established by the European Union.

Syntax

EuroConvert(number, sourcecurrency, targetcurrency[, fullprecision, triangulationprecision])

Argument | Description
number | The number you want to convert, or a reference to a field containing the number.
sourcecurrency | A string expression, or reference to a field containing the string, corresponding to the International Standards Organization (ISO) acronym for the currency you want to convert. Can be one of the ISO codes listed in the following table.
 | Currency | ISO Code |  | Calculation Precision | Display Precision
 | Belgian franc | BEF |  | 0 | 0
 | Luxembourg franc | LUF |  | 0 | 0
 | Deutsche mark | DEM |  | 2 | 2
 | Spanish peseta | ESP |  | 0 | 0
 | French franc | FRF |  | 2 | 2
 | Irish punt | IEP |  | 2 | 2
 | Italian lira | ITL |  | 0 | 0
 | Netherlands guilder | NLG |  | 2 | 2
 | Austrian schilling | ATS |  | 2 | 2
 | Portuguese escudo | PTE |  | 1 | 2
 | finish Markka | FIM |  | 2 | 2
 | euro | EUR |  | 2 | 2
 | In the preceding table, the calculation precision determines what currency unit to round the result to based on the conversion currency. For example, when converting to Deutsche marks, the calculation precision is 2, and the result is rounded to the nearest pfennig, 100 pfennigs to a mark. The display precision determines how many decimal places appear in the field containing the result.
 | Later versions of the EuroConvert function may support additional currencies. For information about new participating currencies and updates to the EuroConvert function, Learn about euro currency support for Microsoft Windows 95 and Windows NT 4.0.
 | Currency |  | ISO Code
 | Danish Krone |  | DKK
 | Drachma |  | GRD
 | Swedish Krona |  | SEK
 | Pound Sterling |  | GBP
targetcurrency | A string expression, or reference to a field containing the string, corresponding to the ISO code of the currency to which you want to convert the number. For a list of ISO codes, see the sourcecurrency argument description.
fullprecision | Optional. A Boolean value where True (1) ignores the currency-specific rounding rules (called display precision in sourcecurrency argument description) and uses the 6-significant-digit conversion factor with no follow-up rounding. False (0) uses the currency-specific rounding rules to display the result. If the parameter is omitted, the default value is False.
triangulationprecision | Optional. An Integer value greater than or equal to 3 that specifies the number of significant digits in the calculation precision used for the intermediate euro value when converting between two national currencies.

Remarks

Any trailing zeros are truncated and invalid parameters return #Error.

If the source ISO code is the same as the target ISO code, the original value of the number is active.

This function does not apply a format.

The EuroConvert function uses the current rates established by the European Union. If the rates change, Microsoft will update the function. To get full information about the rules and the rates currently in effect, see the European Commission publications about the euro. For information about obtaining these publications, see the Microsoft Office Euro Currency Web site, Learn about euro currency support for Microsoft Windows 95 and Windows NT 4.0.

Examples

The first example converts 1.20 Deutsche marks to a euro dollar value (answer = 0.61). The second example converts 1.47 French francs to Deutsche marks (answer = 0.44 DM). They assume conversion rates of 1 euro = 6.55858 French francs and 1.92974 Deutsche marks.

EuroConvert(1.20,"DEM","EUR")
EuroConvert(1.47,"FRF","DEM",TRUE,3)


 Eval Function

Eval Function

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

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

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

Syntax

Eval(stringexpr)

The stringexpr argument is an expression that evaluates to an alphanumeric text string. For example, stringexpr can be a function that returns a string or a numeric value. Or it can be a reference to a control on a form. The stringexpr 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:

' ShowNames is user-defined function.
Debug.Print Eval("ShowNames()")
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 String
Set ctl = Forms!Employees!LastName
strCtl = "Forms!Employees!LastName"
MsgBox ("The current value of " & ctl.Name & " is " & Eval(strCtl))

You can use the Eval function to access expression operators that aren't ordinarily available in Visual Basic. For example, you 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 Integer
intState = Eval("Forms!Orders!ShipRegion In " _
    & "('AK', 'CA', 'ID', 'WA', 'MT', 'NM', 'OR')")


 GUIDFromString Function

GUIDFromString Function

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.

Argument | Description
stringexpression | A string expression which evaluates to a GUID in string form.

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.


 Nz Function

Nz Function

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

Nz(variant[, valueifnull])

The Nz function has the following arguments.

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. Note If you use the Nz function in an expression in a query without using the valueifnull argument, the results will be a zero-length string in the fields that contain null values.

If the value of the variant argument is Null, the Nz function returns the number zero or a zero-length string (always returns a zero-length string when used in a query expression), 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. When used in a query expression, the NZ function should always include the valueifnull argument,

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

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


 StringFromGUID Function

StringFromGUID Function

The StringFromGUID function converts a GUID, which is an array of type Byte, to a string.

Syntax

StringFromGUID(guid)

The StringFromGUID function has the following argument.

Argument | Description
guid | An array of Byte data used to uniquely identify an application, component, or item of data to the operating system.

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.


Methods Reference

The following reference groups all methods by object or collection and lists them alphabetically. A double asterisk (**) indicates that the method was added for Microsoft Access 2000.

Grouped by Object or Collection

AccessObject | AccessObjectProperties
AccessObjectProperty | AllDataAccessPages
AllDatabaseDiagrams | AllForms
AllMacros | AllModules
AllQueries | AllReports
AllStoredProcedures | AllTables
AllViews | Application
Assistant (Office) | CodeData
CodeProject | Collection (VBA)
ComAddIns (Office) | Command (ADO)
Connection (ADO) | Connection (ADO)
Container, Containers (DAO) | Connection, Connections (DAO)
Controls | Control
CurrentProject | CurrentData
DataAccessPages | DataAccessPage
DBEngine (DAO) | Database, Databases (DAO)
DefaultWebOptions | Debug (VBA)
Document, Documents (DAO) | DoCmd
Error (ADO) | Err (VBA)
Errors (ADO) | Error, Errors (DAO)
Field, Fields (DAO) | Field (ADO)
FileSearch (Office) | Fields (ADO)
Group, Groups (DAO) | Form
Module | Index, Indexes (DAO)
Page | Modules
Pages | Page
Parameter (ADO) | Pages
Parameters (ADO) | Parameter, Parameters (DAO)
Property, Properties (DAO) | Property (ADO)
QueryDef, QueryDefs (DAO) | Properties (ADO)
Recordset, Recordsets (DAO) | Recordset (ADO)
References | Reference
Report | Relation, Relations (DAO)
TableDef, TableDefs (DAO) | Screen
VBE (VBA) | User, Users (DAO)
Workspace, Workspaces (DAO) | WebOptions

Listed Alphabetically

A–C

AccessError | Close (ADO)
Add (AccessObjectProperties Collection)** | Close (DAO)
Add (FormatConditions Collection)** | Close
Add (VBA) | CloseConnection**
Add (Pages collection) | CloseCurrentDatabase
AddFromFile (Module object) | CodeDb
AddFromFile (References collection) | CommitTrans (ADO)
AddFromGUID | CommitTrans (DAO)
AddFromString | CompactDatabase (DAO)
AddMenu** | CompareBookmarks (ADO)
AddNew (ADO) | CopyObject
AddNew (DAO) | CopyQueryDef (DAO)
AddToFavorites | CreateControl
Append (ADO) | CreateDataAccessPage**
Append (DAO) | CreateDatabase (DAO)
AppendChunk (ADO) | CreateEventProc
AppendChunk (DAO) | CreateField (DAO)
ApplyFilter | CreateForm
ApplyTheme** | CreateGroup (DAO)
Beep | CreateGroupLevel
BeginTrans (ADO) | CreateIndex (DAO)
BeginTrans (DAO) | CreateNewDocument**
BuildCriteria | CreateParameter (ADO)
Cancel (ADO) | CreateProperty (DAO)
Cancel (DAO) | CreateQueryDef (DAO)
CancelBatch (ADO) | CreateRelation (DAO)
CancelEvent | CreateReport
CancelUpdate (ADO) | CreateReportControl
CancelUpdate (DAO) | CreateTableDef (DAO)
Circle | CreateUser (DAO)
Clear (ADO) | CreateWorkspace (DAO)
Clear (VBA) | CurrentDb
Clone (ADO) | CurrentUser
Clone (DAO) |

D–F

DefaultControl | Execute (ADO Command Object)
DefaultWorkspaceClone | Execute (ADO Connection Object)
Delete (ADO Fields Collection) | Execute (DAO)
Delete (ADO Parameters Collection) | FillCache (DAO)
Delete (ADO Recordset Collection) | Find
Delete (DAO) | Find (ADO)
Delete (FormatCondition Object)** | FindFirst (DAO)
Delete (FormatConditions Collection)** | FindLast (DAO)
DeleteLines | FindNext (DAO)
DeleteObject | FindNext
DoMenuItem | FindPrevious (DAO)
Dropdown | FindRecord
Echo (DoCmd object) | Follow
Echo (Application object) | FollowHyperlink
Edit (DAO) |

G–M

GetChunk (ADO) | LoadPicture
GetChunk (DAO) | MakeReplica (DAO)
GetHiddenAttribute** | Maximize
GetOption | Minimize
GetRows (ADO) | Modify (FormatCondition Object)**
GetRows (DAO) | Move (ADO)
GoToControl | Move (DAO)
GoToPage (DoCmd object) | MoveFirst (ADO)
GoToPage (Form object) | MoveFirst (DAO)
GoToRecord | MoveLast (ADO)
GetString (ADO) | MoveLast (DAO)
Hourglass | MoveNext (ADO)
Idle (DAO) | MoveNext (DAO)
InsertLines | MovePrevious (ADO)
InsertText | MovePrevious (DAO)
Item (VBA) | MoveSize
Line |

N–Q

NewAccessProject** | OpenQuery
NewCurrentDatabase | OpenRecordset (DAO)
NewPassword (DAO) | OpenReport
NextRecordset (ADO) | OpenSchema (ADO)
NextRecordset (DAO) | OpenStoredProcedure**
Open (ADO Connection Object) | OpenTable
Open (ADO Recordset Object) | OpenView**
OpenAccessProject** | OutputTo
OpenConnection** | PopulatePartial (DAO)
OpenConnection (DAO) | Print (VBA)
OpenCurrentDatabase | Print
OpenDataAccessPage** | PrintOut
OpenDatabase (DAO) | PSet
OpenDiagram** | Quit (DoCmd object)
OpenForm | Quit(Application object)
OpenModule |

R

Raise (VBA) | RepaintObject
Recalc | RepairDatabase (DAO)
Refresh | ReplaceLine
Refresh (ADO) | Requery (ADO)
Refresh (DAO) | Requery (DAO)
RefreshDatabaseWindow | Requery (DoCmd object)
RefreshLink (DAO) | Requery (Control or Form object)
RefreshTitleBar | Restore
RegisterDatabase (DAO) | Resync (ADO)
Remove (AccessObjectProperties Collection)** | RollbackTrans (ADO)
Remove (VBA) | Rollback (DAO)
Remove (Pages collection) | Run
Remove (References collection) | RunCommand
Rename | RunMacro
Repaint | RunSQL

S–Z

Save | SizeToFit
Save (ADO) | Supports (ADO)
Scale | Synchronize (DAO)
Seek (ADO) | SysCmd
Seek (DAO) | TextHeight
SelectObject | TextWidth
SendObject | TransferDatabase
SetFocus | TransferSpreadsheet
SetHiddenAttribute** | TransferText
SetMenuItem | Undo
SetOption (DAO) | Update (ADO)
SetOption | Update (DAO)
SetWarnings | UpdateBatch (ADO)
ShowAllRecords | UseDefaultFolderSuffix**
ShowToolbar |


 New Methods (Alphabetic List)

New Methods (Alphabetic List)

Methods that were added to Microsoft Access 2000 are listed in the following table.

A–H

Add (AccessObjectProperties Collection)

Add (FormatConditions Collection)

AddMenu

ApplyTheme

CloseConnection

CreateAccessProject

 CreateDataAccessPage

CreateNewDocument

Delete (FormatCondition Object)

Delete (FormatConditions Collection)

GetHiddenAttribute

I–Q

Modify (FormatCondition Object)

NewAccessProject

OpenAccessProject

OpenConnection

 OpenDataAccessPage

OpenDiagram

OpenStoredProcedure

OpenView

R–Z

Remove (AccessObjectProperties Collection)

SetHiddenAttribute

 UseDefaultFolderSuffix

Microsoft Office methods

To see a list of the new methods available in the Microsoft Office 9.0 Object Library, open the Microsoft Office Visual Basic Reference in the Help contents.

To use the objects supplied by Microsoft Office, you must set a reference to the Microsoft Office 9.0 Object Library when the Visual Basic Editor is open by clicking References on the Tools Menu and selecting the check box next to this library.

Microsoft Visual Basic Editor methods

To see a list of the new methods available in the Microsoft Visual Basic for Applications Extensibility 5.3 Object Library, open the Microsoft Visual Basic Reference in the Help contents.

To use the objects supplied by the Microsoft Visual Basic Editor, you must set a reference to the Microsoft Visual Basic for Applications Extensibility 5.3 Object Library. To set this reference, open the Visual Basic Editor and click References on the Tools Menu and select the check box next to this library.


 AboutBox Method (Snapshot Viewer)

AboutBox Method (Snapshot Viewer)

The AboutBox method displays the About dialog box for the Microsoft Snapshot Viewer control.

Syntax

object.AboutBox

The AboutBox method has the following arguments.

Argument | Description
object | An object representing a Snapshot Viewer control.

Remarks

When you use the AboutBox method, the Microsoft Snapshot Viewer control About box is displayed.


AccessError Method

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

Syntax

[application.]AccessError(errornumber)

The AccessError method has the following arguments.

Argument | Description
application | Optional. The Application object.
errornumber | The number of the error for which you wish to return a descriptive string.

Remarks

You can use the AccessError method to return the descriptive string associated with a Microsoft Access error or an ADO 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 an ADO 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.


 Add Method (AccessObjectProperties Collection)

Add Method (AccessObjectProperties Collection)

You can use the Add method to add a new property as an AccessObjectProperty object to the AccessObjectProperties collection of an AccessObject object.

Syntax

object.Add propertyname, value

The Add method has the following arguments.

Argument | Description
object | A string expression that evaluates to the AccessObjectProperties collection of an AccessObject object.
propertyname | A string expression that's the name of the new property.
value | A Variant value corresponding to the option setting. The setting of the value argument depends on the possible settings for a particular option. Can be a constant value or a string value.

Remarks

You can use the Remove method of the AccessObjectProperties collection to delete an existing property.


 Add Method (FormatConditions Collection)

Add Method (FormatConditions Collection)

You can use the Add method to add a conditional format as a FormatCondition object to the FormatConditions collection of a combo box or text box control.

Syntax

object.Add type [, operator][, expression1][, expression2]

The Add method has the following arguments.

Argument | Description
object | A string expression that evaluates to the FormatConditions collection of a combo box or text box control.
type | One of the following intrinsic constants: acExpression acFieldHasFocus acFieldValue
operator | One of the following intrinsic constants: acBetween (default) acEqual acGreaterThan acGreaterThanOrEqual acLessThan acLessThanOrEqual acNotBetween acNotEqual
 | If the type argument is acExpression, the operator argument is ignored. If you leave this argument blank, the default constant (acBetween) is assumed.
expression1 | A Variant value or expression associated with the first part of the conditional format. Can be a constant value or a string value.
expression2 | A Variant value or expression associated with the second part of the conditional format when the operator argument is acBetween or acNotBetween (otherwise, this argument is ignored). Can be a constant value or a string value.

Remarks

You can use the Delete method of the FormatConditions collection to delete an existing FormatConditions collection from a combo box or text box control.


 Add Method (Pages Collection)

Add Method (Pages Collection)

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.

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.

Remarks

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.


 AddFromFile Method (Module Object)

AddFromFile Method (Module Object)

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.

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.

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.


 AddFromFile Method (References Collection)

AddFromFile Method (References Collection)

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.

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.

Remarks

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

File extension | Type of file
.olb, .tlb | Type library file
.mdb, .mda, .mde | Database
.exe, .dll | Executable file
.ocx | ActiveX control


 AddFromGUID Method

AddFromGUID Method

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.
guid | A GUID that identifies a type library.

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.


 AddFromString Method

AddFromString Method

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.

Argument | Description
object | A Module object.
stringexpression | A string expression.

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.


 AddMenu Method

AddMenu Method

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

Syntax

DoCmd.AddMenu menuname, menumacroname, statusbartext

The AddMenu method has the following arguments.

Argument | Description
menuname | A string expression that's the valid name of a drop-down menu to add to the custom menu bar or global menu bar.
 | 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.
menumacroname | A string expression that's the valid name of the macro group that contains the macros for the menu's commands. This is a required argument.
statusbartext | A string expression that's the text to display in the status bar when the menu is selected.

Remarks

You must include the menuname and menumacroname arguments in the AddMenu method for custom menu bars and global menu bars. The menuname argument is not required and will be ignored for custom shortcut menus and global shortcut menus.

The statusbartext argument is optional, this argument is ignored for custom shortcut menus and global shortcut menus.


 AddToFavorites Method

AddToFavorites Method

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

Syntax

object.hyperlink.AddToFavorites

The AddToFavorites method has the following arguments.

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.

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.

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.


 ApplyFilter Method

ApplyFilter Method

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

Syntax

DoCmd.ApplyFilter [filtername][, wherecondition][, filtertype]

The ApplyFilter method has the following arguments.

Argument | Description
filtername | A string expression that's the valid name of a filter or query in the current database.
 | Note When using this method to apply a server filter, the filtername argument must be blank.
wherecondition | A string expression that's a valid SQL WHERE clause without the word WHERE.
filtertype | One of the following intrinsic constants:
 | acFilterNormal (default) acServerFilter

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

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.


 ApplyTheme Method

ApplyTheme Method

You can use the ApplyTheme method to specify the Microsoft Office theme for a specified data access page.

Syntax

object.ApplyTheme themename

The ApplyTheme method has the following arguments.

Argument | Description
object | Optional. A string expression that evaluates to the DataAccessPage object.
themename | A string expression that's the name of the Office theme.

Remarks

The ApplyTheme method provides a means of changing environment options from Visual Basic code.


Beep Method

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

Syntax

DoCmd.Beep

This method has no arguments.

Remarks

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


 BuildCriteria Method

BuildCriteria Method

The BuildCriteria method returns a parsed criteria string as it would appear in the query design grid, in Filter By Form or Server Filter By Form mode. For example, you may want to set a form's Filter or ServerFilter property based on varying criteria from the user. You can use the BuildCriteria method to construct the string expression argument for the Filter or ServerFilter 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 ADO Type property.
expression | A string expression identifying the criteria to be parsed.

The BuildCriteria method returns a string.

Remarks

The BuildCriteria method enables you to easily construct criteria for a filter based on user input. It parses the expression argument in the same way that the expression would be parsed had it been entered in the query design grid, in Filter By Form or Server 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 String
strCriteria = BuildCriteria("OrderDate", dbDate, ">1-1-95")

Since you need to supply criteria for the Filter property in correctly parsed form, you can use the BuildCriteria method to construct a correctly parsed string.

You can use the BuildCriteria method to construct a string with multiple criteria if those criteria refer to the same field. For example, you can use the BuildCriteria method with the following arguments to construct a string with multiple criteria relating to the OrderDate field:

strCriteria = BuildCriteria("OrderDate", dbDate, ">1-1-95 and <5-1-95")

This example returns the following criteria string:

OrderDate>#1/1/95# And OrderDate<#5/1/95#

However, if you wish to construct a criteria string 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.


 CancelEvent Method

CancelEvent Method

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

Syntax

DoCmd.CancelEvent

This method 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.


 Circle Method

Circle Method

The Circle method draws a circle, an ellipse, or an arc on a Report object when the Print event occurs.

Syntax

object.Circle [Step](x, y), radius[, [color][, [start][, [end][, aspect]]]]

You can use this method only in an event procedure or a macro specified by the event properties 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.
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.

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.


 Close Method (Microsoft Access)

Close Method

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

Syntax

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

The Close method has the following arguments.

Argument | Description
objecttype | One of the following intrinsic constants:
 | acDataAccessPage acDefault (default) acDiagram acForm acMacro acModule acQuery acReport acServerView acStoredProcedure acTable
 | Note If closing a module in the Visual Basic Editor (VBE), you must use acModule in the objecttype argument.
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:
 | acSaveNo acSavePrompt (default) acSaveYes
 | If you leave this argument blank, the default constant (acSavePrompt) is assumed.

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.

Note If a form has a control bound to a field that has its Required property set to 'Yes,' and the form is closed using the Close method without entering any data for that field, an error message is not displayed. Any changes made to the record will be aborted. When the form is closed using the Windows Close button, the Close action in a macro, or selecting Close from the File menu, Microsoft Access displays an alert. The following code will display an error message when attempting to close a form with a Null field, using the Close method.

If IsNull(Me![Field1]) Then
    If MsgBox("'Field1' must contain a value." _
        & Chr(13) & Chr(10) _
    & "Press 'OK' to return and enter a value." _
    & Chr(13) & Chr(10) _
    & "Press 'Cancel' to abort the record.", _
        vbOKCancel, "A Required field is Null") = _
        vbCancel Then
        DoCmd.Close
    End If
End If


 CloseCurrentDatabase Method

CloseCurrentDatabase Method

You can use the CloseCurrentDatabase method to close the current database (either a Microsoft Access database (.mdb) or an Access project (.adp) 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.

Argument | Description
application | The Application object.

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.


 CodeDb Method

CodeDb Method

You can use the CodeDb method 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 method to access Data Access Objects (DAO) that are part of a library database.

For example, you can use the CodeDb method 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 method has the following argument.

Argument | Description
database | A Database object variable.

Remarks

The CodeDb method returns a Database object for which the Name property is the full path and name of the database from which it is called. This method can be useful when you need to manipulate the Data Access Objects in your library database.

When you call a method in a library database, the database from which you have called the method 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 method to determine the name of the Database object that refers to the library database that contains the table.

If the CodeDb method is run from the current database, it returns the name of the current database, which is the same value returned by the CurrentDb method.


 CopyObject Method

CopyObject Method

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

Syntax

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

The CopyObject method has the following arguments.

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.
 | Note In a Microsoft Access project (.adp) you must leave the destinationdatabase 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:
 | acDataAccessPage acDefault (default) acDiagram acForm acMacro acModule acQuery acReport acServerView acStoredProcedure acTable
 | Note When using the CopyObject method with a data access page, a copy of the HTML file for the data access page is created in the Default database folder and a link to it is created in the destination database.
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.

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.


 CreateAccessProject Method

CreateAccessProject Method

You can use the CreateAccessProject method to create a new Microsoft Access project (.adp) on disk.

Syntax

object.CreateAccessProject projname [, connection ]

The CreateAccessProject method has the following arguments.

Argument | Description
object | A string expression that evaluates to the Application object.
projname | A string expression that is the name of the new Access project, 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.adp
connection | A string expression that's the valid connection string for the Access project. See the ADO ConnectionString property for details about this string.

Remarks

The CreateAccessProject method enables you to create a new Access project from within Microsoft Access or another application through Automation, formally called OLE Automation. For example, you can use the CreateAccessProject method from Microsoft Excel to create a new Access project on disk. Once you have created an instance of Microsoft Access from another application, you must also create a new Access project.

If the Access project identified by projname already exists, an error occurs.

Notes

  • To create and open a new Access project as the current Access project in the Access window, use the NewAccessProject method of the Application object.

  • To open an existing Access project as the current Access project in the Access window, use the OpenAccessProject method of the Application object.


 CreateControl, CreateReportControl Methods

CreateControl, CreateReportControl Methods

  • The CreateControl method creates a control on a specified open form.

  • The CreateReportControl method 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 method 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 methods 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 Object Browser [image] on the Visual Basic toolbar, then click Access in the Project/Library box, and click AcControlType 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
 | 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. To view these constants and paste them into your code from the Object Browser, click Object Browser [image] on the Visual Basic toolbar, then click Access in the Project/Library box, and click AcSection in the Classes box.
 | Constant | Section
 | acDetail | (Default) Detail section
 | acHeader | Form or report header
 | acFooter | Form or report footer
 | acPageHeader | Page header
 | acPageFooter | Page footer
 | acGroupLevel1Header | Group-level 1 header (reports only)
 | acGroupLevel1Footer | Group-level 1 footer (reports only)
 | acGroupLevel2Header | Group-level 2 header (reports only)
 | acGroupLevel2Footer | Group-level 2 footer (reports only)
 | If a report has additional group levels, the header/footer pairs are numbered consecutively, beginning with 9.
parent | 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.

Remarks

You can use the CreateControl and CreateReportControl methods in a custom wizard to create controls on a form or report. Both methods return a Control object.

You can use the CreateControl and CreateReportControl methods only in form Design view or report Design view, respectively.

You use the parent argument to identify the relationship between a main control and a subordinate control. For example, if a text box has an attached label, the text box is the main (or parent) control and the label is the subordinate (or child) control. When you create the label control, set its parent argument to a string identifying the name of the parent control. When you create the text box, set its parent argument to a zero-length string.

You also set the parent argument when you create check boxes, option buttons, or toggle buttons. An option group is the parent control of any check boxes, option buttons, or toggle buttons that it contains. The only controls that can have a parent control are a label, check box, option button, or toggle button. All of these controls can also be created independently, without a parent control.

Set the columnname argument according to the type of control you are creating and whether or not it will be bound to a field in a table. The controls that may be bound to a field include the text box, list box, combo box, option group, and bound object frame. Additionally, the toggle button, option button, and check box controls may be bound to a field if they are not contained in an option group.

If you specify the name of a field for the columnname argument, you create a control that is bound to that field. All of the control's properties are then automatically set to the settings of any corresponding field properties. For example, the value of the control's ValidationRule property will be the same as the value of that property for the field.

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.


 CreateDataAccessPage Method

CreateDataAccessPage Method

The CreateDataAccessPage method can create a new, blank data access page or open an existing HTML page as a data access page.

Syntax

object.CreateDataAccessPage filename [, createnewfile]

The CreateDataAccessPage method has the following arguments.

Argument | Description
object | The Application object.
filename | A string expression identifying the name and path of the data access page.
createnewfile | A Boolean value where True (-1) creates a new html page and link and False creates a new link to an existing html file. The default is True.

The following table shows the four possible setting combinations for the CreateDataAccessPage method and the results of those settings.

Filename | Createnewfile | Result
blank or new name and path | True (-1) | A new, minimized data access page is created and opened in Design view. A link to that page is created in the Pages object list of the Database window.
blank or new name and path | False (0) | An error occurs.
name of existing file and path | False (0) | A new uniquely named link is created that points to the existing data access page
name of existing file and path | True (-1) | An error occurs.

Remarks

You can use the CreateDataAccessPage method when designing a wizard that creates a new data access page.

The data access page you specify for filename can be a data access page that you have created specifically to be used as a template, or any other data access page in the database identified by the filename argument, and a setting of False for the createnewfile argument.

The CreateDataAccessPage method creates a minimized data access page. If you want to display the new data access page when created, you must use the Restore method.


 CreateEventProc Method

CreateEventProc Method

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.

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.

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.


 CreateForm, CreateReport Methods

CreateForm, CreateReport Methods

  • The CreateForm method creates a form and returns a Form object.

  • The CreateReport method 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 method 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 methods have the following arguments.

Argument | Description
database | A string expression identifying the name of the database that contains the form or report template you want to use to create a form or report. If you want the current database, omit this argument. If you want to use an open library database, specify the library database with this argument.
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.

Remarks

You can use the CreateForm and CreateReport methods when designing a wizard that creates a new form or report.

The CreateForm and CreateReport methods 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 10, "The Windows API and Other Dynamic-Link Libraries," in the Microsoft Office 2000/Visual Basic Programmer's Guide. For information about how to obtain the Microsoft Office 2000/Visual Basic Programmer's Guide, click [image] .

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 method 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 method, 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.

The CreateForm and CreateReport methods create minimized forms and reports.


 CreateGroupLevel Method

CreateGroupLevel Method

You can use the CreateGroupLevel method 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 method from your wizard to create the appropriate groups according to the user's choice.

Syntax

CreateGroupLevel(report, expression, header, footer)

The CreateGroupLevel method has the following arguments.

Argument | Description
report | A string expression identifying the name of the report that will contain the new group level.
expression | A string expression identifying the field or expression to sort or group on.
header, footer | An Integer value that indicates whether a field or expression will have an associated group header and/or 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.

Remarks

You can use the CreateGroupLevel method when designing a wizard that creates a report with groups or totals. The CreateGroupLevel method groups or sorts data on the specified field or expression and creates a header and/or footer for the group level.

The CreateGroupLevel method 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 method adds a new group level to the array, based on the expression argument. The CreateGroupLevel method 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 Sorting And Grouping [image] 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.


 CreateNewDocument Method

CreateNewDocument Method

You can use the CreateNewDocument method to create a new document associated with a specified hyperlink.

Syntax

object.CreateNewDocument filename, editnow, overwrite

The CreateNewDocument method has the following arguments.

Argument | Description
object | The Hyperlink object within a control.
filename | A string expression identifying the name and path of the document. The type of document format you want used can be determine by the extension used with the filename. to output the data. You can create HTML (*.htm), Microsoft Active Server Pages (*.asp), Microsoft Excel (*.xls), Microsoft IIS (*.htx, *.idc), MS-DOS Text (*.txt), Rich Text Format (*.rtf), or Microsoft Data Access Pages (*.html). Modules can be output only to MS-DOS text format. Data access pages can only be output in HTML format. Microsoft Internet Information Server and Microsoft Active Server formats are available only for tables, queries, and forms.
 | Note If an extension is not provided then the data access page format (.html) is assumed. If a directory is not specfied, the default database directory is used. This directory is determined by the setting in Options dialog box.
editnow | A Boolean value where True (-1) opens the document in design view and False stores the new document in the specified database directory. The default is True.
overwrite | A Boolean value where True (-1) overwrites an existing document if the filename argument identifies an existing document and False requires that the filename argument specifies a new filename. The default is False.

Remarks

The CreateNewDocument method provides a way to programatically create a document associated with a hyperlink within a control.


 CurrentDb Method

CurrentDb Method

The CurrentDb method returns an object variable of type Database that represents the database currently open in the Microsoft Access window.

Note In Microsoft Access 2000 the CurrentDb method establishes a hidden reference to the Microsoft DAO 3.6 Object Library in a Microsoft Access database (.mdb). If you want to use the CurrentDb method in an Access project (.adp) you must set a permanent reference to the DAO 3.6 Object library in the Microsoft Visual Basic Editor.

Syntax

CurrentDb

Remarks

In order to manipulate the structure of your database and its data from Visual Basic, you must use Data Access Objects (DAO). The CurrentDb method 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 method to create multiple object variables that refer to the current database. In the following example, the variables dbsA and dbsB both refer to the current database:

Dim dbsA As Database, dbsB As Database
Set dbsA = CurrentDb
Set dbsB = CurrentDb

Note In previous versions of Microsoft Access, you may have used the syntax DBEngine.Workspaces(0).Databases(0) or DBEngine(0)(0) to return a pointer to the current database. In Microsoft Access 2000, you should use the CurrentDb method instead. The CurrentDb method creates another instance of the current database, while the DBEngine(0)(0) syntax refers to the open copy of the current database. The CurrentDb method 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 Database
Set dbsCurrent = CurrentDb
Set dbsContacts = DBEngine.Workspaces(0).OpenDatabase("Contacts.mdb")


 CurrentUser Method

CurrentUser Method

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

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

Syntax

CurrentUser

Remarks

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

If you haven't established a secure workgroup, the CurrentUser method 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 method 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)


 DefaultControl Method

DefaultControl Method

The DefaultControl method returns a Control object with which you can set the default properties for a particular type of control on a particular form or report. 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.
object | A Form or Report object on which controls are to be created. The default property settings defined for a type of control apply only to controls of the same type created on this form or report.
controltype | An intrinsic constant indicating the type of control for which default property settings are to be set.

Remarks

The DefaultControl method enables you to set a control's default properties from code. Once you have set the default properties for a particular type of control, each subsequently created control of that type will have the same default values.

For example, if you set the FontSize property of the default command button to 12, each new command button will have a font size of 12 points.

Not all of a control's properties are available as default properties. The default properties available for a control depend on the type of control.

The DefaultControl method returns a Control object of the type specified by the controltype argument. This Control object doesn't represent an actual control on a form, but rather a default control that is a template for all subsequently created controls of that type. You set the default control properties for the Control object returned by the DefaultControl method in the same manner that you would set properties for an individual control on a form.

For a list of intrinsic constants that can be passed as the controltype argument, see the CreateControl function. These constants are also listed in the Constants module of the Microsoft Access library in the Object Browser.

The DefaultControl method 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.


 DefaultWorkspaceClone Method

DefaultWorkspaceClone Method

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.

Note In Microsoft Access 2000, the DefaultWorkspaceClone method is included in this version of Microsoft Access only for compatibility with previous versions using Data Access Object (DAO) language.

Syntax

application.DefaultWorkspaceClone

The DefaultWorkspaceClone method has the following argument.

Argument | Description
application | The Application object.

Remarks

The DefaultWorkspaceClone method creates a clone of the default Workspace object in Microsoft Access. The properties of the Workspace object clone have settings identical to those of the default Workspace object, except for the Name property setting. For the default Workspace object, the value of the Name property is always #Default Workspace#. For the cloned Workspace object, it is #CloneAccess#.

The UserName property of the default Workspace object indicates the name under which the current user logged 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.


 Delete Method (FormatCondition Object)

Delete Method (FormatCondition Object)

You can use the Delete method to remove a FormatCondition object from the FormatConditions collection of a combo box or text box control.

Syntax

object.Delete

The Delete method has the following arguments.

Argument | Description
object | A string expression that evaluates to a FormatCondition object of a combo box or text box control.

Remarks

You can use the Add to add a format condition to the FormatConditions collection of a combo box or text box.


 Delete Method (FormatConditions Collection)

Delete Method (FormatConditions Collection)

You can use the Delete method to remove all format conditions in the FormatConditions collection of a combo box or text box control.

Syntax

object.Delete

The Delete method has the following arguments.

Argument | Description
object | A string expression that evaluates to the FormatConditions collection of the combo box or text box control.

Remarks

You can use the Add method to add format conditions to the FormatConditions collection of a combo box or text box.


 DeleteControl, DeleteReportControl Methods

DeleteControl, DeleteReportControl Methods

  • The DeleteControl method deletes a specified control from a form.

  • The DeleteReportControl method 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 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 method to dynamically remove the command button from the form.

Syntax

DeleteControl formname, controlname

DeleteReportControl reportname, controlname

The DeleteControl and DeleteReportControl methods have the following arguments.

Argument | Description
formname, reportname | A string expression identifying the name of the form or report containing the control you want to delete.
controlname | A string expression identifying the name of the control you want to delete.

Remarks

The DeleteControl and DeleteReportControl methods 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.


 DeleteLines Method

DeleteLines Method

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.

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.

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.


 DeleteObject Method

DeleteObject Method

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

Syntax

DoCmd.DeleteObject [objecttype][, objectname]

The DeleteObject method has the following arguments.

Argument | Description
objecttype | One of the following intrinsic constants:
 | acDataAccessPage acDefault (default) acDiagram acForm acMacro acModule acQuery acReport acServerView acStoredProcdure acTable
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.

Remarks

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


 DoMenuItem Method

DoMenuItem Method

Note In Microsoft Access 97, the DoMenuItem method was 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 2000. 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 2000, 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).
menuname | You can use one of the following intrinsic constants:
 | acFile acEditMenu acRecordsMenu
 | You can use acRecordsMenu only for the Form view menu bar in Microsoft Access version 2.0 and Microsoft Access 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:
 | acNew acSaveForm acSaveFormAs acSaveRecord acUndo acCut acCopy acPaste acDelete acSelectRecord acSelectAllRecords acObject acRefresh
 | 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).
subcommand | You can use one of the following intrinsic constants:
 | acObjectVerb acObjectUpdate
 | The acObjectVerb constant represents the first command on the submenu of the Object command on the Edit menu. The type of object determines the first command on the submenu. For example, this command is Edit for a Paintbrush object that can be edited.
 | For other commands on submenus, 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.
 | 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 or Microsoft Access 2000 commands (although existing DoMenuItem methods in Visual Basic code will still work). Use the RunCommand method instead.

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.


 Dropdown Method

Dropdown Method

You can use the Dropdown method to force the list in the specified combo box to drop down. For example, you can use this method to cause a combo box listing vendor codes to drop down when the vendor code control receives the focus during data entry.

Syntax

combobox.Dropdown

The Dropdown method has the following argument.

Argument | Description
combobox | A combo box control on a form.

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.


 Echo Method (Application Object)

Echo Method (Application Object)

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.
statusbartext | A string expression that specifies the text to display in the status bar when repainting is turned on or off.

Remarks

If you are running Visual Basic code that makes a number of changes to objects displayed on the screen, your code may be faster if you turn off screen repainting until the procedure has finished running. You may also want to turn repainting off if your code makes changes that the user shouldn't see or doesn't need to see.

The Echo method doesn't suppress the display of modal dialog boxes, such as error messages, or pop-up forms, such as property sheets.

If you turn screen repainting off, the screen 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.


 Echo Method (DoCmd Object)

Echo Method (DoCmd Object)

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

Syntax

DoCmd.Echo echoon[, statusbartext]

The Echo method has the following arguments.

Argument | Description
echoon | Use True (–1) to turn echo on and False (0) to turn it off.
statusbartext | A string expression.

Remarks

If you leave the statusbartext argument blank, don't use a comma following the echoon argument.

If you turn echo off in Visual Basic, you must turn it back on, or it will remain off, even if the user presses CTRL+BREAK or Visual Basic encounters a breakpoint. You may want to create a macro that turns echo on and then assign that macro to a key combination or a custom menu command. You could then use the key combination or menu command to turn echo on if it has been turned off in Visual Basic.

The Echo method of the DoCmd object was added to provide backward 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.


Exporting Report Snapshots

There are two ways to programmatically export a report snapshot object from a Microsoft Access database.

  • You can use the SendObject method to embed a report snapshot in a mail message.

  • You can use the OutputTo method to save a report snapshot to disk.

The following table contains information about the first three arguments of the SendObject method used to send a report snapshot in a mail message. Note, only the first three arguments of the SendObject method are dicussed here as they are how you specify a report as a snapshot file. For information on the other arguments to the SendObject method, see that topic in the Microsoft Access on-line help.

Argument | Description
Object Type | A constant representing the type of object you want to send. For report snapshots the constant is acSendReport.
Object Name | A string value representing the name of the report to include in the mail message as a snapshot file.
Output Format | To output a report snapshot, set this argument to the string value: "Snapshot Format".

The following table contains information about the first four arguments of the OutputTo method used to save a report snapshot to a snapshot file on disk. Note, only the first four arguments of the OutputTo method are described here because they are how you specify that a report be saved to disk as a snapshot file. For information on the other arguments to the OutputTo method, see that topic in the Microsoft Access on-line help.

Argument | Description
Object Type | A constant representing the type of object you want to save to disk. For report snapshots the constant is acOutputReport.
Object Name | A string value representing the name of the report to be saved to disk.
Output Format | To save a report snapshot, set this argument to the string value: "Snapshot Format".
Output File | A string value representing the full path and file name of the snapshot file you want to save to disk. For example: "c:\my documents\mysnapshot.snp"


 Find Method

Find Method

The Find method finds specified text in a standard module or class module.

Syntax

object.Find(target, startline, startcolumn, endline, endcolumn[, wholeword, matchcase, patternsearch])

The Find method has the following arguments.

Argument | Description
object | A Module object.
target | A string expression that evaluates to the text that you want to find.
startline | A Long value that specifies the line on which to begin searching. If a match is found, the value of the startline argument is set to the line on which the beginning character of the matching text is found.
startcolumn | A Long value that specifies the column on which to begin searching. Each character in a line is in a separate column, beginning with zero on the left side of the module. If a match is found, the value of the startcolumn argument is set to the column on which the beginning character of the matching text is found.
endline | A Long value that specifies the line on which to stop searching. If a match is found, the value of the endline argument is set to the line on which the ending character of the matching text is found.
endcolumn | A Long value that specifies the column on which to stop searching. If a match is found, the value of the endcolumn argument is set to the column on which the beginning character of the matching text is found.
wholeword | Optional. A Boolean value where True (–1) results in a search for whole words only and False (0) results in a search for portions of words. The default is False.
matchcase | Optional. A Boolean value where True results in a search for words with case matching the target argument and False results in a search for words regardless of case. The default is False.
patternsearch | Optional. A Boolean value where True results in a search in which the target argument may contain wildcard characters such as an asterisk (*) or a question mark (?), and False results in a search without considering question marks or asterisks as wildcard characters. The default is False.

Remarks

The Find method searches for the specified text string in a Module object. If the string is found, the Find method returns True; otherwise it returns False.

To determine the position in the module at which the search text was found, pass empty variables to the Find method for the startline, startcolumn, endline, and endcolumn arguments. If a match is found, these arguments will contain the line number and column position at which the search text begins (startline, startcolumn) and ends (endline, endcolumn).

For example, if the search text is found on line 5, begins on column 10, and ends at column 20, the values of these arguments will be: startline = 5, startcolumn = 10, endline = 5, endcolumn = 20.


FindNext Method

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

Syntax

DoCmd.FindNext

This method has no arguments.


 FindRecord Method

FindRecord Method

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

Syntax

DoCmd.FindRecord findwhat[, match][, matchcase][, search][, searchasformatted][, onlycurrentfield][, findfirst]

The FindRecord method has the following arguments.

Argument | Description
findwhat | An expression that evaluates to text, a number, or a date. The expression contains the data to search for.
match | One of the following intrinsic constants:
 | acAnywhere acEntire (default) acStart
 | If you leave this argument blank, the default constant (acEntire) is assumed.
matchcase | Use True (–1) for a case-sensitive search and False (0) for a search that's not case-sensitive. If you leave this argument blank, the default (False) is assumed.
search | One of the following intrinsic constants:
 | acDown acSearchAll (default) acUp
 | If you leave this argument blank, the default constant (acSearchAll) is assumed.
searchasformatted | Use True to search for data as it's formatted and False to search for data as it's stored in the database. If you leave this argument blank, the default (False) is assumed.
onlycurrentfield | One of the following intrinsic constants:
 | acAll acCurrent (default)
 | If you leave this argument blank, the default constant (acCurrent) is assumed.
findfirst | Use True to start the search at the first record. Use False to start the search at the record following the current record. If you leave this argument blank, the default (True) is assumed.

Remarks

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave one or more trailing arguments blank, don't use a comma following the last argument you specify.


 FirstPage, LastPage, NextPage, PreviousPage Methods

FirstPage, LastPage, NextPage, PreviousPage Methods

The FirstPage, LastPage, NextPage, PreviousPage methods are used to navigate through the pages in a snapshot file.

Syntax

object.FirstPage

object.LastPage

object.NextPage

object.PreviousPage

These methods have the following arguments.

Argument | Description
object | An object representing a Snapshot Viewer control.

Remarks

These methods are used to move through the pages in a snapshot file. With one exception, executing these methods has the same effect as clicking the navigation buttons that are a part of the Snapshot Viewer control. The exception is that clicking the navigation buttons on the control will trigger the related FirstPage, LastPage, NextPage, or PreviousPage events, while navigating through pages programmatically does not trigger these events.

If the SnapshotPath property has no value or has an invalid value, using one of these methods will generate an error. You can use the ReadyState property to make sure the SnapshotPath is valid.

If you use the NextPage method while on the last page in a snapshot file, the last page in the file is displayed and no error occurs. If you use the PreviousPage method while on the first page in a snapshot file, the first page in the file is displayed and no error occurs.


 Follow Method

Follow Method

The Follow method opens the document or Web page specified by a hyperlink address associated with a control on a form or report.

Syntax

object.hyperlink.Follow[([newwindow], [addhistory], [extrainfo], [method], [headerinfo])]

The Follow method has the following arguments.

Argument | Description
object | A Control object that contains a hyperlink. The combo box, label, list box, text box, command button, and image controls can contain hyperlinks.
hyperlink | The hyperlink of the Control object.
newwindow | A Boolean value where True (–1) opens the document in a new window and False (0) opens the document in the current window. The default is False.
addhistory | A Boolean value where True adds the hyperlink to the History folder and False doesn't add the hyperlink to the History folder. The default is True.
extrainfo | A string or an array of Byte data that specifies additional information for navigating to a hyperlink. For example, this argument may be used to specify a search parameter for an .ASP or .IDC file. In your Web browser, the extrainfo argument may appear after the hyperlink address, separated from the address by a question mark (?). You don't need to include the question mark when you specify the extrainfo argument.
method | An Integer value that specifies how the extrainfo argument is attached. The method argument may be one of the following intrinsic constants.
 | Constant | Description
 | msoMethodGet | The extrainfo argument is appended to the hyperlink address and can only be a string. This value is passed by default.
 | msoMethodPost | The extrainfo argument is posted, either as a string or as an array of type Byte.
headerinfo | A string that specifies header information. By default the headerinfo argument is a zero-length string (" ").

Remarks

The Follow method has the same effect as clicking a hyperlink.

You can include the Follow method in an event procedure if you want to open a hyperlink in response to a user action. For example, you may want to open a web page with reference information when a user opens a particular form.

When you use the Follow method, you don't need to know the address specified by a control's HyperlinkAddress property. You only need to know the name of the control that contains the hyperlink. Conversely, when you use the FollowHyperlink method, you need to specify the address for the particular hyperlink you wish to follow.


 FollowHyperlink Method

FollowHyperlink Method

The FollowHyperlink method opens the document or Web page specified by a hyperlink address.

Syntax

[application.]FollowHyperlink address, [subaddress], [newwindow], [addhistory], [extrainfo], [method], [headerinfo]

The FollowHyperlink method has the following arguments.

Argument | Description
application | The Application object.
address | A string expression that evaluates to a valid hyperlink address.
subaddress | A string expression that evaluates to a named location in the document specified by the address argument. The default is a zero-length string (" ").
newwindow | A Boolean value where True (–1) opens the document in a new window and False (0) opens the document in the current window. The default is False.
addhistory | A Boolean value where True adds the hyperlink to the History folder and False doesn't add the hyperlink to the History folder. The default is True.
extrainfo | A string or an array of Byte data that specifies additional information for navigating to a hyperlink. For example, this argument may be used to specify a search parameter for an .asp or .idc file. In your Web browser, the extrainfo argument may appear after the hyperlink address, separated from the address by a question mark (?). You don't need to include the question mark when you specify the extrainfo argument.
method | An Integer value that specifies how the extrainfo argument is attached. The method argument may be one of the following intrinsic constants.
 | Constant | Description
 | msoMethodGet | The extrainfo argument is appended to the hyperlink address and can only be a string. This value is passed by default.
 | msoMethodPost | The extrainfo argument is posted, either as a string or as an array of type Byte.
headerinfo | A string that specifies header information. By default the headerinfo argument is a zero-length string.

Remarks

By using the FollowHyperlink method, you can follow a hyperlink that doesn't exist in a control. This hyperlink may be supplied by you or by the user. For example, you can prompt a user to enter a hyperlink address in a dialog box, then use the FollowHyperlink method to follow that hyperlink.

You can use the extrainfo and method arguments to supply additional information when navigating to a hyperlink. For example, you can supply parameters to a search engine. To search the Yahoo site for information on Microsoft, you might call the FollowHyperlink method as follows:

Application.FollowHyperlink "http://search.yahoo.com/bin/search", _
    , , , "p=Microsoft", msoMethodGet

You can use the Follow method to follow a hyperlink associated with a control.


 GetHiddenAttribute, SetHiddenAttribute Methods

GetHiddenAttribute, SetHiddenAttribute Methods

  • The GetHiddenAttribute method returns the value of hidden attribute of a Microsoft Access object in the object's Properties dialog box, available by selecting the object in the Database window and clicking Properties on the View menu.

  • The SetHiddenAttribute method sets the hidden attribute of an Access object.

Syntax

object.GetHiddenAttribute(objecttype, objectname)

object.SetHiddenAttribute objecttype, objectname, setting

The GetHiddenAttribute and SetHiddenAttribute methods have the following arguments.

Argument | Description
object | Optional. The Application object.
objecttype | One of the following intrinsic constants: acDataAccessPage acDiagram acForm acMacro acModule acQuery acReport acServerView acStoredProcedure acTable
 | You must enter a constant for the objecttype argument, acDefault is not a valid entry.
objectname | A string expression identifying the name of the Access object.
setting | A Boolean value where True (-1) sets the hidden attribute and False (0) clears the attribute.

Remarks

The GetHiddenAttribute and SetHiddenAttribute methods provide a means of changing an object's hidden attribute from Visual Basic code. With these methods, you can set or read the hidden option available in the object's Properties dialog box.

Since the hidden attributes that the user can set by selecting or clearing a check box, the GetHiddenAttribute method returns True (–1) if the option setting is Yes (the check box is selected) or False (0) if the option setting is No (the check box is cleared). To set an option of this kind by using the SetHiddenAttribute method, specify True or False for the setting argument, as in the following example:

Application.SetHiddenAttribute acTable,"Customers", True


 GetOption, SetOption Methods

GetOption, SetOption Methods

  • The GetOption method returns the current value of an option in the Options dialog box, available by clicking Options on the Tools menu.

  • The SetOption method sets the current value of an option in the Options dialog box.

Syntax

object.GetOption(optionname)

object.SetOption optionname, setting

The GetOption and SetOption methods have the following arguments.

Argument | Description
object | Optional The Application object.
optionname | The name of the option. For a list of optionname argument strings, see Set Options from Visual Basic.
setting | A Variant value corresponding to the option setting. The value of the setting argument depends on the possible settings for a particular option.

Remarks

The GetOption and SetOption methods provide a means of changing environment options from Visual Basic code. With these methods, you can set or read any option available in the Options dialog box, except for options on the Modules tab.

The available option settings depend on the type of option being set. There are three general types of options:

  • Yes/No options that can be set by selecting or clearing a check box.

  • Options that can be set by entering a string or numeric value.

  • Predefined options that can be chosen from a list box, combo box, or option group.

For options that the user sets by selecting or clearing a check box, the GetOption method returns True (–1) if the option setting is Yes (the check box is selected) or False (0) if the option setting is No (the check box is cleared). To set an option of this kind by using the SetOption method, specify True or False for the setting argument, as in the following example:

Application.SetOption "Show Status Bar", True

For options that the user sets by typing a string or numeric value, the GetOption method returns the setting as it's displayed in the dialog box. The following example returns a string containing the left margin setting:

Dim varSetting As Variant
varSetting = Application.GetOption("Left Margin")

To set this type of option by using the SetOption method, specify the string or numeric value that would be typed in the dialog box. The following example sets the default form template to OrderTemplate:

Application.SetOption "Form Template", "OrderTemplate"

For options with settings that are choices in list boxes or combo boxes, the GetOption method returns a number corresponding to the position of the setting in the list. Indexing begins with zero, so the GetOption method returns zero for the first item, 1 for the second item, and so on. For example, if the Default Field Type option on the Tables/Queries tab is set to AutoNumber, the sixth item in the list, the GetOption method returns 5.

To set this type of option, specify the option's numeric position within the list as the setting argument for the SetOption method. The following example sets the Default Field Type option to AutoNumber:

Application.SetOption "Default Field Type", 5

Other options are set by clicking on an option button in an option group in the Options dialog box. In Visual Basic, these options are also set by specifying a particular option's position within the option group. The first option in the group is numbered zero, the second, 1, and so on. For example, if the Selection Behavior option on the Forms/Reports tab is set to Partially Enclosed, the GetOption method returns zero, as in the following example:

Debug.Print Application.GetOption("Selection Behavior")

To set an option that's a member of an option group, specify the index number of the option within the group. The following example sets Selection Behavior to Fully Enclosed:

Application.SetOption "Selection Behavior", 1

Notes

  • When you use the GetOption method or the SetOption method to set an option in the Options dialog box, you don't need to specify the individual tab on which the option is found.

  • You can't use the GetOption method or the SetOption method to read or set any of the options found on the Module tab of the Options dialog box.

  • If the return value of the GetOption method is assigned to a variable, the variable must be declared as a Variant.

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


 GoToControl Method

GoToControl Method

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

Syntax

DoCmd.GoToControl controlname

The GoToControl method has the following argument.

Argument | Description
controlname | A string expression that's the name of a control on the active form or datasheet.

Remarks

Use only the name of the control for the controlname argument, not the full syntax.

You can also use a variable declared as a Control data type for this argument.

Dim ctl As Control
Set ctl = Forms!Form1!Field3
DoCmd.GoToControl ctl.Name

You can also use the SetFocus method to move the focus to a control on a form or any of its subforms, or to a field in an open table, query, or form datasheet. This is the preferred method for moving the focus in Visual Basic, especially to controls on subforms and nested subforms, because you can use the full syntax to specify the control you want to move to.


 GoToPage Method (DoCmd Object)

GoToPage Method (DoCmd Object)

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

Syntax

DoCmd.GoToPage [pagenumber][, right, down]

The GoToPage method has the following arguments.

Argument | Description
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.

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.


 GoToPage Method (Form Object)

GoToPage Method (Form Object)

The GoToPage method moves the focus to the first control on a specified page in the active form.

Syntax

form.GoToPage pagenumber[, right, down]

The GoToPage method has the following arguments.

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.

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.


 GoToRecord Method

GoToRecord Method

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

Syntax

DoCmd.GoToRecord [objecttype, objectname][, record][, offset]

The GoToRecord method has the following arguments.

Argument | Description
objecttype | One of the following intrinsic constants:
 | acActiveDataObject (default) acDataForm acDataQuery acDataTable
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:
 | acFirst acGoTo acLast acNewRec acNext (default) acPrevious
 | 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.

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.


Hourglass Method

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

Syntax

DoCmd.Hourglass hourglasson

The Hourglass method 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.


 hWndAccessApp Method

hWndAccessApp Method

You can use the hWndAccessApp method to determine the handle assigned by Microsoft Windows 98 to the main Microsoft Access window.

Setting

The hWndAccessApp method returns a Long Integer value set by Microsoft Access and is read-only.

Remarks

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


 HyperlinkPart Method

HyperlinkPart Method

The HyperlinkPart method returns information about data stored as a Hyperlink data type. The data in a Hyperlink field can contain up to four parts in the following format:

displaytext#address#subaddress#screentip

Syntax

object.HyperlinkPart(hyperlink As Variant [, part As Integer])

The HyperlinkPart method has the following arguments.

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 method:
 | Constant | Value | Description
 | acDisplayedValue | 0 | (Default) The underlined text displayed in a hyperlink.
 | acDisplayText | 1 | The displaytext part of a Hyperlink field.
 | acAddress | 2 | The address part of a Hyperlink field.
 | acSubAddress | 3 | The subaddress part of a Hyperlink field.
 | acScreenTip | 4 | The tooltip part of a Hyperlink field.
 | acFullAddress | 5 | The address and subaddress parts of a Hyperlink field delimited by a "#" character.

Remarks

You use the HyperlinkPart method 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 four parts of the Hyperlink field (displaytext, address, subaddress, or screentip), the full address, address#subaddress, or the value Microsoft Access displays for the hyperlink.

Note If you use the HyperlinkPart method 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 method for data stored in a Hyperlink field.

Hyperlink field data | HyperlinkPart method returned values
#http://www.microsoft.com# | acDisplayedValue: http://www.microsoft.com acDisplayText: acAddress: http://www.microsoft.com acSubAddress: acScreenTip: acFullAddress: http://www.microsoft.com
Microsoft#http://www.microsoft.com# | acDisplayedValue: Microsoft acDisplayText: Microsoft acAddress: http://www.microsoft.com acSubAddress: acScreenTip: acFullAddress: http://www.microsoft.com
Customers#http://www.microsoft.com#Form Customers | acDisplayedValue: Customers acDisplayText: Customers acAddress: http://www.microsoft.com acSubAddress: Form Customers acScreenTip: acFullAddress: http://www.microsoft.com#Form Customer
##Form Customers#Enter Information | acDisplayedValue: Form Customers acDisplayText: acAddress: acSubAddress: Form Customers acScreenTip: Enter Information acFullAddress: #FormCustomer

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, form, or report, pointing to Hyperlink on the shortcut menu, and then typing the display text in the Text to display box.

When you add data to a Hyperlink field directly, you must include the two # symbols to delimit the parts of the hyperlink data.


 InsertLines Method

InsertLines Method

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.

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.

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.


 InsertText Method

InsertText Method

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.

Argument | Description
object | A Module object.
text | The text to be inserted into the module.

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.


 Item Method

Item Method

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.

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.

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


 Line Method

Line Method

The Line method draws lines and rectangles on a Report object when the Print event occurs.

Syntax

object.Line [[Step](x1, y1)] – [Step](x2, y2)[, [color][, B[F]]]

You can use this method only in an event procedure or a macro specified by the 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.
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.

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.


 LoadPicture Method

LoadPicture Method

The LoadPicture method loads a graphic into an ActiveX control.

Syntax

LoadPicture(stringexpression)

The LoadPicture method has the following argument.

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

Remarks

Assign the return value of the LoadPicture method 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 method 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 method to set the Picture property of an image control. This method 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.


Maximize Method

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

Note This method cannot be applied to module windows in the Visual Basic Editor (VBE). For information about how to affect module windows see the WindowState property topic.

Syntax

DoCmd.Maximize

This method has no arguments.


Minimize Method

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

Note This method cannot be applied to module windows in the Visual Basic Editor (VBE). For information about how to affect module windows see the WindowState property topic.

Syntax

DoCmd.Minimize

This method has no arguments.


 Modify Method (FormatCondition Object)

Modify Method (FormatCondition Object)

You can use the Modify method to change the format conditions of a FormatCondition object in the FormatConditions collection of a combo box or text box control.

Syntax

object.Modify type [, operator][, expression1][, expression2]

The Modify method has the following arguments.

Argument | Description
object | A string expression that evaluates to the FormatCondition object of a combo box or text box control.
type | One of the following intrinsic constants: acExpression acFieldHasFocus acFieldValue
operator | One of the following intrinsic constants: acBetween (default) acEqual acGreaterThan acGreaterThanOrEqual acLessThan acLessThanOrEqual acNotBetween acNotEqual
 | If the type argument is acExpression, the operator argument is ignored. If you leave this argument blank, the default constant (acBetween) is assumed.
expression1 | A Variant value or expression associated with the first part of the conditional format. Can be a constant value or a string value.
expression2 | A Variant value or expression associated with the second part of the conditional format when the operator argument is acBetween or acNotBetween (otherwise, this argument is ignored). Can be a constant value or a string value.

Remarks


 MoveSize Method

MoveSize Method

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

Syntax

DoCmd.MoveSize [right][, down][, width][, height]

The MoveSize method has the following arguments.

Argument | Description
right | A numeric expression.
down | A numeric expression.
width | A numeric expression.
height | A numeric expression.

Remarks

You must include at least one argument for the MoveSize method. If you leave an argument blank, the current setting for the window is used.

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave one or more trailing arguments blank, don't use a comma following the last argument you specify.

The units for the arguments are twips.


 NewAccessProject Method

NewAccessProject Method

You can use the NewAccessProject method to create and open a new Microsoft Access project (.adp) as the current Access project in the Microsoft Access window.

Syntax

object.NewAccessProject projname [, connection]

The NewAccessProject method has the following arguments.

Argument | Description
object | The Application object.
projname | A string expression that is the name of the new Access project, 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.adp
connection | A string expression that's the valid connection string for the Access project. See the ADO ConnectionString property for details about this string.

Remarks

The NewAccessProject method enables you to create a new Access project from within Microsoft Access or another application through Automation, formally called OLE Automation. For example, you can use the NewAccessProject method from Microsoft Excel to create a new Access project in the Access window. Once you have created an instance of Microsoft Access from another application, you must also create a new Access project. This Access project opens in the Microsoft Access window.

If the Access project identified by projname already exists, an error occurs.

The new Access project is opened under the Admin user account.

Note To open an Access database (.mdb), use the NewCurrentDatabase method of the Application object.


 NewCurrentDatabase Method

NewCurrentDatabase Method

You can use the NewCurrentDatabase method to create a new Microsoft Access database (.mdb) 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.

Note You can use the NewAccessProject method to create a new Microsoft Access project (.adp) in the Access window.

Syntax

application.NewCurrentDatabase dbname

The NewCurrentDatabase method has the following arguments.

Argument | Description
application | The Application object.
dbname | A string expression that is the name of a new database file, including the path name and the file name extension. If your network supports it, you can also specify a network path in the following form: \\Server\Share\Folder\Filename
 | Note If you don't supply the filename extension, .mdb is appended to the filename.

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.


 OpenAccessProject Method

OpenAccessProject Method

You can use the OpenAccessProject method to open an existing Microsoft Access project (.adp) as the current Access project in the Microsoft Access window.

Syntax

object.OpenAccessProject projname

The OpenAccessProject method has the following arguments.

Argument | Description
object | The Application object.
projname | A string expression that is the name of the existing Access project, 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.adp
 | Note If you don't supply the filename extension, .adp is appended to the filename. You can use this method or the OpenCurrentDatabase method to open .adp files.

Remarks

The OpenAccessProject method enables you to open an existing project from within Microsoft Access or another application through Automation, formally called OLE Automation. For example, you can use the OpenAccessProject method from Microsoft Excel to open the Northwind.adp sample database in the Microsoft Access window. Once you have created an instance of Microsoft Access from another application, you must also create a new Access project or specify a particular Access project to open. This Access project opens in the Microsoft Access window.

If you have already opened a project and wish to open another project in the Microsoft Access window, you can use the CloseCurrentDatabase method to close the first Access project before opening another.

Note To open an Access database (.mdb), use the OpenCurrentDatabase method of the Application object.


 OpenCurrentDatabase Method

OpenCurrentDatabase Method

You can use the OpenCurrentDatabase method to open an existing Microsoft Access database (.mdb) as the current database. You can use this method to open a database from another application that is controlling Microsoft Access through Automation, formerly called OLE Automation. For example, you can use the OpenCurrentDatabase method from Microsoft Excel to open the Northwind.mdb sample database in the Microsoft Access window.

Note Use the OpenAccessProject method to open an existing Microsoft Access project (.adp) as the current database.

Syntax

application.OpenCurrentDatabase dbname[, exclusive]

The OpenCurrentDatabase method has the following arguments.

Argument | Description
application | The Application object.
dbname | A string expression that is the name of an existing database file, including the path name and the file name extension. If your network supports it, you can also specify a network path in the following form: \\Server\Share\Folder\Filename
 | Note If you don't supply the filename extension, .mdb is appended to the filename.
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.

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 ActiveX Data Objects (ADO) Open method or the Data Access Object (DAO) OpenDatabase method. The OpenCurrentDatabase method opens a database in the Microsoft Access window. The ADO Open method returns a Connection object variable, the DAO OpenDatabase method returns a Database object variable, both of which represent a particular database, but don't actually open that database in the Microsoft Access window.


 OpenDataAccessPage Method

OpenDataAccessPage Method

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

Syntax

DoCmd.OpenDataAccessPage datapagename [, datapageview]

The OpenDataAccessPage method has the following arguments.

Argument | Description
datapagename | A string expression that's the valid name of a data access page in the current database.
 | If you execute Visual Basic code containing the OpenDataAccessPage method in a library database, Microsoft Access looks for the form with this name first in the library database, then in the current database.
datapageview | One of the following intrinsic constants:
 | acDataPageBrowse (default) acDataPageDesign
 | acDataPageBrowse opens the form in Page view.
 | If you leave this argument blank, the default constant (acDataPageBrowse) is assumed.

Remarks

If the connection password was not contained in the connection information for the data access page when it was created, the user is prompted to provide a password when the OpenDataAccessPage method is used.


 OpenDiagram Method

OpenDiagram Method

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

Syntax

DoCmd.OpenDiagram diagramname

The OpenDiagram method has the following argument.

Argument | Description
datapagename | A string expression that's the valid name of a database diagram in the current database.
 | If you execute Visual Basic code containing the OpenDiagram method in a library database, Microsoft Access looks for the database diagram with this name first in the library database, then in the current database.


 OpenForm Method

OpenForm Method

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

Syntax

DoCmd.OpenForm formname[, view][, filtername][, wherecondition][, datamode][, windowmode][, openargs]

The OpenForm method has the following arguments.

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.
view | One of the following intrinsic constants:
 | acDesign acFormDS acNormal (default) acPreview
 | acNormal opens the form in Form view.
 | 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:
 | acFormAdd acFormEdit acFormPropertySettings (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:
 | acDialog acHidden acIcon acWindowNormal (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.
 | 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.

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.


 OpenModule Method

OpenModule Method

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

Syntax

DoCmd.OpenModule [modulename][, procedurename]

The OpenModule method has the following arguments.

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

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.


 OpenQuery Method

OpenQuery Method

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

Note This method is only available in the Microsoft Access database environment (.mdb). See the OpenView or OpenStoredProcedure methods if using the Microsoft Access Project environment (.adp).

Syntax

DoCmd.OpenQuery queryname[, view][, datamode]

The OpenQuery method has the following arguments.

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:
 | acViewDesign acViewNormal (default) acViewPreview
 | 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:
 | acAdd acEdit (default) acReadOnly
 | If you leave this argument blank, the default constant (acEdit) is assumed.

Remarks

If you specify the datamode argument and leave the view argument blank, you must include the view argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.


 OpenReport Method

OpenReport Method

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

Syntax

DoCmd.OpenReport reportname[, view][, filtername][, wherecondition]

The OpenReport method 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:
 | acViewDesign acViewNormal (default) acViewPreview
 | 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.

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.


 OpenStoredProcedure Method

OpenStoredProcedure Method

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

Syntax

DoCmd.OpenStoredProcedure procedurename [, viewmode] [, datamode]

The OpenStoredProcedure method has the following arguments.

Argument | Description
procedurename | A string expression that's the valid name of a stored procedure in the current database.
 | If you execute Visual Basic code containing the OpenStoredProcedure method in a library database, Microsoft Access looks for the stored procedure with this name first in the library database, then in the current database.
viewmode | One of the following intrinsic constants:
 | acViewNormal (default) acViewDesign acViewPreview
 | If you leave this argument blank, the default constant (acViewNormal) is assumed.
datamode | One of the following intrinsic constants:
 | acAdd acEdit (default) acReadOnly
 | If you leave this argument blank, the default constant (acEdit) is assumed.


 OpenTable Method

OpenTable Method

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

Syntax

DoCmd.OpenTable tablename[, view][, datamode]

The OpenTable method 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:
 | acViewDesign acViewNormal (default) acViewPreview
 | acViewNormal opens the table in Datasheet view.
 | If you leave this argument blank, the default constant (acViewNormal) is assumed.
datamode | One of the following intrinsic constants:
 | acAdd acEdit (default) acReadOnly
 | If you leave this argument blank, the default constant (acEdit) is assumed.

Remarks

If you specify the datamode argument and leave the view argument blank, you must include the view argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.


 OpenView Method

OpenView Method

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

Syntax

DoCmd.OpenView viewname [, viewmode] [, datamode]

The OpenView method has the following arguments.

Argument | Description
viewname | A string expression that's the valid name of a view in the current database.
 | If you execute Visual Basic code containing the OpenView method in a library database, Microsoft Access looks for the view with this name first in the library database, then in the current database.
viewmode | One of the following intrinsic constants:
 | acViewNormal (default) acViewDesign acPreview
 | If you leave this argument blank, the default constant (acViewNormal) is assumed.
datamode | One of the following intrinsic constants.
 | acEdit (default) acAdd acReadOnly
 | If you leave this argument blank, the default constant (acEdit) is assumed.


 OutputTo Method

OutputTo Method

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

Syntax

DoCmd.OutputTo objecttype[, objectname][, outputformat][, outputfile][, autostart][, templatefile]

The OutputTo method has the following arguments.

Argument | Description
objecttype | One of the following intrinsic constants:
 | acOutputDataAccessPage acOutputForm acOutputModule acOutputQuery acOutputReport acOutputServerView acOutputStoredProcedure acOutputTable
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.
 | 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.
outputformat | One of the following intrinsic constants:
 | acFormatASP acFormatDAP acFormatHTML acFormatIIS acFormatRTF acFormatSNP acFormatTXT acFormatXLS
 | 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.
 | 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.

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


 Print Method (Microsoft Access)

Print Method

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

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.

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.


 PrintOut Method

PrintOut Method

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

Syntax

DoCmd.PrintOut [printrange][, pagefrom, pageto][, printquality][, copies][, collatecopies]

The PrintOut method has the following arguments.

Argument | Description
printrange | One of the following intrinsic constants:
 | acPrintAll (default) acSelection acPages
 | 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.
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:
 | acDraft acHigh (default) acLow acMedium
 | 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.

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.


 PrintSnapshot Method

PrintSnapshot Method

The PrintSnapshot method is used to print the current snapshot file.

Syntax

object.PrintSnapshot([ShowPrintDialog As Boolean])

The PrintSnapshot method has the following arguments.

Argument | Description
object | An object representing a Snapshot Viewer control.
ShowPrintDialog | (Optional) A Boolean value specifying whether to show the Print dialog box. The default value is True.

Remarks

If you do not specify the optional ShowPrintDialog argument, then the Print dialog box is displayed. If the user clicks the Cancel button in the Print dialog box, an error (2504) occurs. If you use the PrintSnapshot method without having a snapshot file displayed in the control, an error (2502) occurs. You can use the SnapshotPath and ReadyState properties to make sure a valid snapshot is displayed in the control.

You can print one or more pages in a snapshot file by specifying the pages to print in the Print dialog box.

The PrintSnapshot method displays an hourglass while printing the snapshot file.


 PSet Method

PSet Method

The PSet method sets a point on a Report object to a specified color when the Print event occurs.

Syntax

object.PSet [Step](x, y)[, color]

You can use this method only in an event procedure or a macro specified by the 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.
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.

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.


 Quit Method (Application Object)

Quit Method (Application Object)

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.
 | acPrompt | Displays a dialog box that asks whether you want to save any database objects that have been changed but not saved.
 | acExit | Quits Microsoft Access without saving any objects.

Remarks

The Quit method has the same effect as clicking Exit on the File menu. You can create a custom menu command or a 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.


 Quit Method (DoCmd Object)

Quit Method (DoCmd Object)

The Quit method of the DoCmd object carries out the Quit action in Visual Basic. For more information on how the action and its argument work, see the action topic.

Syntax

DoCmd.Quit [options]

The Quit method has the following argument.

Argument | Description
options | One of the following intrinsic constants:
 | acQuitPrompt acQuitSaveAll (default) acQuitSaveNone
 | If you leave this argument blank, the default constant (acQuitSaveAll) is assumed.

Remarks

The Quit method of the DoCmd object was added to provide backward compatibility for running the Quit action in Visual Basic code in Microsoft Access 95. It's recommended that you use the existing Quit method of the Application object instead.


 Recalc Method

Recalc Method

The Recalc method immediately updates all calculated controls on a form.

Syntax

form.Recalc

The Recalc method has the following argument.

Argument | Description
form | A Form object representing the form that contains the controls for which you want to recalculate the values.

Remarks

Using this method is equivalent to pressing the F9 key when a form has the focus. You can use this method to recalculate the values of controls that depend on other fields for which the contents may have changed.


 Refresh Method (Microsoft Access)

Refresh Method

The Refresh method immediately updates the records in the underlying record source for a specified form or datasheet to reflect changes made to the data by you and other users in a multiuser environment.

Syntax

form.Refresh

The Refresh method has the following argument.

Argument | Description
form | A Form object that represents the form to refresh.

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

  • It's often faster to refresh a form or datasheet than to requery it. This is especially true if the initial query was slow to run.

  • Don't confuse the Refresh method with the Repaint method, which repaints the screen with any pending visual changes.


 RefreshDatabaseWindow Method

RefreshDatabaseWindow Method

The RefreshDatabaseWindow method updates the Database window after a database object has been created, deleted, or renamed.

Syntax

[application.]RefreshDatabaseWindow

The RefreshDatabaseWindow method has the following argument.

Argument | Description
application | The Microsoft Access Application object.

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.


 RefreshTitleBar Method

RefreshTitleBar Method

The RefreshTitleBar method refreshes the Microsoft Access title bar after the AppTitle or AppIcon property has been set in Visual Basic. For example, you can change the caption in the Microsoft Access title bar to "Contacts Database" by setting the AppTitle property.

Syntax

application.RefreshTitleBar

The RefreshTitleBar method uses the following argument.

Argument | Description
application | The Application object.

Remarks

The AppTitle and AppIcon properties enable you to customize your application by changing the title and icon that appear in the Microsoft Access title bar. The title bar is not automatically updated after you have set these properties. In order for the change to the title bar to appear, you must use the RefreshTitleBar method.

Note In a Microsoft Access database (.mdb), you can reset the AppTitle and AppIcon properties to their default value by deleting them from the Properties collection 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.


 Remove Method (AccessObjectProperties Collection)

Remove Method (AccessObjectProperties Collection)

You can use the Remove method to remove an AccessObjectProperty object from the AccessObjectProperties collection of an AccessObject object.

Syntax

object.Remove item

The Delete method has the following arguments.

Argument | Description
object | A string expression that evaluates to the AccessObjectProperties collection of an AccessObject object.
item | 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.


 Remove Method (Pages Collection)

Remove Method (Pages Collection)

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.

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.

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.


 Remove Method (References Collection)

Remove Method (References Collection)

The Remove method removes a Reference object from the References collection.

Syntax

object.Remove reference

The Remove method has the following arguments.

Argument | Description
object | A string expression that evaluates to the References collection.
reference | The Reference object that represents the reference you wish to remove.

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.


 Rename Method

Rename Method

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

Syntax

DoCmd.Rename newname[, objecttype, oldname]

The Rename method has the following arguments.

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:
 | acDataAccessPage acDefault (default) acDiagram acForm acMacro acModule acQuery acReport acServerView acStoredProcedure acTable
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.

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


 Repaint Method

Repaint Method

The Repaint method completes any pending screen updates for a specified form. When performed on a form, the Repaint method also completes any pending recalculations of the form's controls.

Syntax

form.Repaint

The Repaint method has the following argument.

Argument | Description
form | A Form object that represents the form to repaint.

Remarks

Microsoft Access sometimes waits to complete pending screen updates until it finishes other tasks. With the Repaint method, you can force immediate repainting of the controls on the specified form. You can use the Repaint method:

  • When you change values in a number of fields. Unless you force a repaint, Microsoft Access might not display the changes immediately, especially if other fields, such as those in an expression in a calculated control, depend on values in the changed fields.

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

This method doesn't cause a requery of the database, nor does it show new or changed records in the form's underlying record source. You can use the Requery method to requery the source of data for the form or one of its controls.

Notes

  • Don't confuse the Repaint method with the Refresh method, or with the Refresh command on the Records menu. The Refresh method and Refresh command show changes you or other users have made to the underlying record source for any of the currently displayed records in forms and datasheets. The Repaint method simply updates the screen when repainting has been delayed while Microsoft Access completes other tasks.

  • The Repaint method differs from the Echo method in that the Repaint method forces a single immediate repaint, while the Echo method turns repainting on or off.


 RepaintObject Method

RepaintObject Method

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

Syntax

DoCmd.RepaintObject [objecttype, objectname]

The RepaintObject method has the following arguments.

Argument | Description
objecttype | One of the following intrinsic constants:
 | acDataAccessPage acDefault (default) acDiagramacForm acMacro acModule acQuery acReport acServerView acStoredProcedure acTable
objectname | A string expression that's the valid name of an object of the type selected by the objecttype argument.

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


 ReplaceLine Method

ReplaceLine Method

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.

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.

Remarks

Lines in a module are numbered beginning with one. To determine the number of lines in a module, use the CountOfLines property.


 Requery Method (Control or Form Object)

Requery Method (Control or Form Object)

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.

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:

  • Reruns the query on which the form or control is based.

  • Displays any new or changed records or removes deleted records from the table on which the form or control is based.

  • Updates records displayed based on any changes to the Filter property of the form.

Controls based on a query or table include:

  • List boxes and combo boxes.

  • Subform controls.

  • OLE objects, such as charts.

  • Controls for which the ControlSource property setting includes domain aggregate functions or SQL aggregate function.

If you specify any other type of control for 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

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

  • The Requery method doesn't pass control to the operating system to allow Windows to continue processing messages. Use the DoEvents function if you need to relinquish temporary control to the operating system.

  • The Requery method is faster than the Requery action. When you use the Requery action, Microsoft Access closes the query and reloads it from the database. When you use the Requery method, Microsoft Access reruns the query without closing and reloading it.


 Requery Method (DoCmd Object)

Requery Method (DoCmd Object)

The Requery method of the DoCmd object carries out the Requery action in Visual Basic. For more information on how the action and its argument work, see the action topic.

Syntax

DoCmd.Requery [controlname]

The Requery method has the following arguments.

Argument | Description
controlname | A string expression that's the name of a control on the active object.

Remarks

Use only the name of the control for the controlname argument, not the full syntax.

You can also use a variable declared as a Control data type for this argument:

Dim ctlLstBox As Control
Set ctlLstBox = Forms!Form1!Field3
DoCmd.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 Requery action or its corresponding Requery method of the DoCmd object. The Requery method of a form or control 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 in ActiveX Data Objects (ADO) can also be used to reun the query.


Restore Method

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

Note This method cannot be applied to module windows in the Visual Basic Editor (VBE). For information about how to affect module windows see the WindowState property topic.

Syntax

DoCmd.Restore

This method has no arguments.


 Run Method

Run Method

You can use the Run method to carry out a specified Microsoft Access or user-defined Function or Sub procedure. This method is useful when you are controlling Microsoft Access from another application through 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.

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.

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.Application
appAccess.OpenCurrentDatabase ("C:\My Documents\WizCode.mdb")
appAccess.Run "WizCode.NewForm", "Some String"

If another procedure with the same name may reside in a different database, qualify 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.


RunCommand Method

The RunCommand method runs a built-in menu or toolbar command.

Syntax

[object.]RunCommand command

The RunCommand method has the following arguments.

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.

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


 RunMacro Method

RunMacro Method

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

Syntax

DoCmd.RunMacro macroname[, repeatcount][, repeatexpression]

The RunMacro method has the following arguments.

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.

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.


 RunSQL Method

RunSQL Method

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

This method only applies to Microsoft Access databases (.mdb).

Syntax

DoCmd.RunSQL sqlstatement[, usetransaction]

The RunSQL method has the following arguments.

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.

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.


 Save Method

Save Method

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

Syntax

DoCmd.Save [objecttype, objectname]

The Save method has the following arguments.

Argument | Description
objecttype | One of the following intrinsic constants:
 | acDataAccessPage acDefault (default) acDiagram acForm acMacro acModule acQuery acReport acServerView acStoredProcedure acTable
 | Note If closing a module in the Visual Basic Editor (VBE), you must use acModule in the objecttype argument.
objectname | A string expression that's the valid name of an object of the type selected by the objecttype argument.

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:

  • A form in Form view or Datasheet view.

  • A report in Print Preview.

  • A module.

  • A data access page in Page view.

  • A server view in Datasheet view or Print Preview.

  • A table in Datasheet view or Print Preview.

  • A query in Datasheet view or Print Preview.

  • A stored procedure in Datasheet view or Print Preview.

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.


 Scale Method

Scale Method

The Scale method defines the coordinate system for a Report object.

Syntax

object.Scale[(x1, y1) – (x2, y2)]

You can use this method only in an event procedure or a macro specified by the OnPrint or OnFormat event property for a report section, or the OnPage event property for a report.

The Scale method has the following arguments.

Argument | Description
object | The Report object to which the coordinate system is applied.
x1, y1 | Single values for the horizontal and vertical coordinates that define the position of the upper-left corner of the object.
x2, y2 | Single values for the horizontal and vertical coordinates that define the position of the lower-right corner of the object.

Remarks

You can use the Scale method to reset the coordinate system to any scale you choose. Using the Scale method with no arguments resets the coordinate system to twips. The Scale method affects the coordinate system for the Print method and the report graphics methods, which include the Circle, Line, and PSet methods.


 SelectObject Method

SelectObject Method

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

Syntax

DoCmd.SelectObject objecttype[, objectname][, indatabasewindow]

The SelectObject method has the following arguments.

Argument | Description
objecttype | One of the following intrinsic constants:
 | acDataAccessPage acDiagram acForm acMacro acModule acQuery acReport acServerView acStoredProcedure acTable
 | 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.

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.


 SendObject Method

SendObject Method

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

Syntax

DoCmd.SendObject [objecttype][, objectname][, outputformat][, to][, cc][, bcc][, subject][, messagetext][, editmessage][, templatefile]

The SendObject method has the following arguments.

Argument | Description
objecttype | One of the following intrinsic constants:
 | acSendDataAccessPage acSendForm acSendModule acSendNoObject (default) acSendQuery acSendReport acSendTable
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:
 | acFormatDAP acFormatHTML acFormatRTF acFormatTXT acFormatXLS
 | If you leave this argument blank, Microsoft Access prompts you for the output format.
to | A string expression that lists the recipients whose names you want to put on the To line in the mail message.
 | Separate the recipient names you specify in this argument and in the cc and bcc arguments with a semicolon (;) or with the list separator set 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 and an error occurs.
 | 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.
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.

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.


 SetFocus Method (Microsoft Access)

SetFocus Method

The SetFocus method moves the focus to the specified form, the specified control on the active form, or the specified field on the active datasheet.

Syntax

object.SetFocus

The SetFocus method has the following argument.

Argument | Description
object | A Form object that represents a form, or a Control object that represents a control on the active form or datasheet.

Remarks

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.


 SetMenuItem Method

SetMenuItem Method

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

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 versions prior to Microsoft Access 97. It doesn't work with the new command bars functionality. In Microsoft Access 2000, you must use the properties and methods of the CommandBars collection object to enable or disable top level menu items.

Syntax

DoCmd.SetMenuItem menuindex[, commandindex][, subcommandindex][, flag]

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:
 | acMenuCheck acMenuGray acMenuUncheck acMenuUngray (default)
 | If you leave this argument blank, the default constant (acMenuUngray) is assumed.

Remarks

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.


 SetWarnings Method

SetWarnings Method

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

Syntax

DoCmd.SetWarnings warningson

The SetWarnings method has the following argument.

Argument | Description
warningson | Use True (–1) to turn on the display of system messages and False (0) to turn it off.

Remarks

If you turn the display of system messages off in Visual Basic, you must turn it back on, or it will remain off, even if the user presses CTRL+BREAK or Visual Basic encounters a breakpoint. You may want to create a macro that turns the display of system messages on and then assign that macro to a key combination or a custom menu command. You could then use the key combination or menu command to turn the display of system messages on if it has been turned off in Visual Basic.


ShowAllRecords Method

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

Note This method only applies to tables, queries, and forms within a Microsoft database (.mdb).

Syntax

DoCmd.ShowAllRecords

This method has no arguments.


 ShowToolbar Method

ShowToolbar Method

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

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.

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.
show | One of the following intrinsic constants:
 | acToolbarNo acToolbarWhereApprop acToolbarYes (default)
 | If you leave this argument blank, the default constant (acToolbarYes) is assumed.

Remarks

If you leave the show argument blank, don't use a comma following the toolbarname argument.


 SizeToFit Method

SizeToFit Method

You can use the SizeToFit method to size a control so it fits the text or image that it contains. For example, you can apply the SizeToFit method to a command button that is too small to display all the text in its Caption property.

Syntax

control.SizeToFit

The SizeToFit method has the following argument.

Argument | Description
control | A control that displays text or an image, including the label, toggle button, command button, image, unbound object frame, and subform/subreport controls.

Remarks

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. The SizeToFit method does not apply to controls on data access pages.


 SysCmd Method

SysCmd Method

You can use the SysCmd method to perform one of the following functions:

  • Display a progress meter or optional specified text in the status bar.

  • Return information about Microsoft Access and its associated files.

  • Return the state of a specified database object to indicate whether the object is open, is a new object, or has been changed but not saved.

For example, if you are building a custom wizard that creates a new form, you can use the SysCmd method 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 method 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 method returns a Null if these actions are successful. Otherwise, Microsoft Access generates a run-time error.
 | acSysCmdInitMeter | Initializes the progress meter. You must specify the text and value arguments when you use this action.
 | acSysCmdUpdateMeter | Updates the progress meter with the specified value. You must specify the text argument when you use this action.
 | acSysCmdRemoveMeter | Removes the progress meter.
 | acSysCmdSetStatus | Sets the status bar text to 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.
 | 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).
 | acSysCmdClearHelpTopic |
 | 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:
 | acTable acQuery acForm acReport acMacro acModule acDataAccessPage acDefault acDiagram acServerView acStoreProcedure
 | 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.

Remarks

By calling the SysCmd method 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 method 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 method with the acSysCmdUpdateMeter action argument and the value argument. When the action argument is acSysCmdUpdateMeter, the SysCmd method 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 method 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.

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 method 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 method 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 method with the acSysCmdSetStatus action argument, the SysCmd method automatically removes the meter.

Call the SysCmd method 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 method 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 method to determine the state of the table.

The SysCmd method with the acSysCmdGetObjectState action argument can return any combination of the following constants.

Constant | State of database object | Value
acObjStateOpen | Open | 1
acObjStateDirty | Changed but not saved | 2
acObjStateNew | New | 4

Note If the object referred to by the objectname argument is either not open or doesn't exist, the SysCmd method returns a value of zero.


 TextHeight Method

TextHeight Method

The TextHeight method returns the height of a text string as it would be printed in the current font of a Report object.

Syntax

object.TextHeight(strexpr)

The TextHeight method has the following arguments.

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.

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.


 TextWidth Method

TextWidth Method

The TextWidth method returns the width of a text string as it would be printed in the current font of a Report object.

Syntax

object.TextWidth(strexpr)

The TextWidth method has the following arguments.

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.

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


 TransferDatabase Method

TransferDatabase Method

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

Syntax

DoCmd.TransferDatabase [transfertype], databasetype, databasename[, objecttype], source, destination[, structureonly][, saveloginid]

The TransferDatabase method has the following arguments.

Argument | Description
transfertype | One of the following intrinsic constants:
 | acExport acImport (default) acLink
 | If you leave this argument blank, the default constant (acImport) is assumed.
 | Note The acLink transfer type is not supported for Microsoft Access projects (.adp).
databasetype | A string expression that's the name of one of the types of databases you can use to import, export, or link data. Microsoft Access (default) Jet 2.x Jet 3.x dBase III dBbase IV dBase 5 Paradox 3.x Paradox 4.x Paradox 5.x Paradox 7.x ODBC Databases
 | 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:
 | acTable (default) acQuery acForm acReport acMacro acModule acDataAccessPage acServerView acDiagram acStoredProcedure
 | This is the type of object whose data you want to import, export, or link. You can specify an object other than acTable only if you are importing or exporting data between two Microsoft Access databases. If you are exporting the results of a Microsoft Access select query to another type of database, specify acTable for this argument.
 | If you leave this argument blank, the default 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.
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.
 | This argument is available only in Visual Basic.

Remarks

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.

The administrator of an ODBC database can disable the feature provided by the saveloginid argument, requiring all users to enter the login ID and password each time they connect to the ODBC database.

Note You can also use ActiveX Data Objects (ADO) to create a link by using the ActiveConnection property for the Recordset object.


 TransferSpreadsheet Method

TransferSpreadsheet Method

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

Syntax

DoCmd.TransferSpreadsheet [transfertype][, spreadsheettype], tablename, filename[, hasfieldnames][, range]

The TransferSpreadsheet method has the following arguments.

Argument | Description
transfertype | One of the following intrinsic constants:
 | acImport (default) acExport acLink
 | If you leave this argument blank, the default constant (acImport) is assumed.
spreadsheettype | One of the following intrinsic constants, or equivalent numeric settings:
 | 0 acSpreadsheetTypeExcel3 (default) 6 acSpreadsheetTypeExcel4 5 acSpreadsheetTypeExcel5 5 acSpreadsheetTypeExcel7 8 acSpreadsheetTypeExcel8 8 acSpreadsheetTypeExcel9 2 acSpreadsheetTypeLotusWK1 3 acSpreadsheetTypeLotusWK3 7 acSpreadsheetTypeLotusWK4 4 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 (acSpreadsheetTypeExcel8) is assumed.
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.

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 You can also use ActiveX Data Objects (ADO) to create a link by using the ActiveConnection property for the Recordset object.


 TransferText Method

TransferText Method

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

Syntax

DoCmd.TransferText [transfertype][, specificationname], tablename, filename[, hasfieldnames][, HTMLtablename][, codepage]

The TransferText method has the following arguments.

Argument | Description
transfertype | One of the following intrinsic constants:
 | acExportDelim acExportFixed acExportHTML acExportMerge acImportDelim (default) acImportFixed acImportHTML acLinkDelim acLinkFixed acLinkHTML
 | If you leave this argument blank, the default constant (acImportDelim) is assumed.
 | Notes You can link to data in a text file or HTML file, but this data is read-only in Microsoft Access. Only acImportDelim, acImportFixed, acExportDelim, acExportFixed, or acExportMerge transfer types are supported in a Microsoft Access project (.adp).
specificationname | A string expression that's the name of an import or export specification you've created and saved in the current database.
 | For a fixed-width text file, you must either specify an argument or use a schema.ini file, which must be stored in the same folder as the imported, linked, or exported text file. To create a schema file, you can use the text import/export wizard to create the file. 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 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.
 | 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.
codepage | A Long value indicating the character set of the code page.

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 You can also use ActiveX Data Objects (ADO) to create a link by using ActiveConnection property for the Recordset object.


 Undo Method

Undo Method

You can use the Undo method to reset a control or form when its value has been changed. For example, you can use the Undo method to clear a change to a record that contains an invalid entry.

Syntax

object.Undo

The Undo method has the following argument.

Argument | Description
object | A Form object or a Control object.

Remarks

If the Undo method is applied to a form, all changes to the current record are lost. If the Undo method is applied to a control, only the control itself is affected.

This method must be applied before the form or control is updated. You may want to include this method in a form's BeforeUpdate event or in a control's Change event.

The Undo method offers an alternative to using the SendKeys statement to send the value of the ESC key in an event procedure.


 UseDefaultFolderSuffix Method

UseDefaultFolderSuffix Method

You can use the UseDefaultFolderSuffix method to set the folder suffix for the specified data access page to the default suffix for the language support you have selected or installed.

Syntax

object.UseDefaultFolderSuffix

The UseDefaultFolderSuffix method has the following arguments.

Argument | Description
object | A string expression that evaluates to a specific data access page and it's WebOptions object.

Remarks

Microsoft Access uses the folder suffix when you save a document as a Web page, use long file names, and choose to save supporting files in a separate folder (that is, if the UseLongFileNames and OrganizeInFolder properties are set to True).

The suffix appears in the folder name after the data access page name. For example, if the data access page is called "Book1" and the language is English, the folder name is Book1_files. The available folder suffixes are listed in the FolderSuffix property topic.


 New Objects

New Objects

Objects that were added to Visual Basic in Microsoft Access 2000 are listed in the following table.

Objects | Description
AccessObject | New object representing all database objects within the CodeData, CodeProject, CurrentData, and CurrentProject object functionality.
AccessObjectProperty, AccessObjectProperties | New collections and properties of the AccessObject object within the CodeData, CodeProject, CurrentData, and CurrentProject object functionality.
AllDataAccessPages, AllForms, AllMacros, AllModules, AllReports | New collections of the new CurrentData and CurrentProject object functionality
AllDatabaseDiagrams, AllQueries, AllStoredProcedures, AllTables, AllViews | New collections of the new CodeData and CodeProject object functionality
CodeData, CodeProject | New objects for code database functionality
ComAddIns | New COM add-ins functionality
CurrentData, CurrentProject | New objects for current data functionality
DataAccessPage, DataAccessPages | New data access page feature
DefaultWebOptions | Default web options for the application
FileSearch | New File Search functionality
FormatCondition, FormatConditions | New conditional format feature
VBE | New Visual Basic Editor functionality
WebOptions | Web options for data access pages

ADO objects

To see a list of the new objects available in the Microsoft ActiveX Data Objects 2.0 Library, open the Microsoft ActiveX Data Objects Reference in the Help contents.

You can use the objects supplied by Microsoft ActiveX Data Objects 2.0, a reference to the Microsoft Office 9.0 Object Library is automatically set when the Visual Basic Editor is open.

Microsoft Office objects

To see a list of the new objects available in the Microsoft Office 9.0 Object Library, open the Microsoft Office Visual Basic Reference in the Help contents.

To use the objects supplied by Microsoft Office, you must set a reference to the Microsoft Office 9.0 Object Library when the Visual Basic Editor is open by clicking References on the Tools Menu and selecting the check box next to this library.

Microsoft Visual Basic Editor objects

To see a list of the new objects available in the Microsoft Visual Basic for Applications Extensibility 5.3 Object Library, open the Microsoft Visual Basic Reference in the Help contents.

To use the objects supplied by the Microsoft Visual Basic Editor, you must set a reference to the Microsoft Visual Basic for Applications Extensibility 5.3 Object Library. To set this reference, open the Visual Basic Editor and click References on the Tools Menu and select the check box next to this library.


 AccessObject Object

AccessObject Object

An AccessObject object refers to a particular Microsoft Access object within the following collections.

AllForms | AllTables
AllReports | AllQueries
AllMacros | AllViews
AllModules | AllStoredProcedures
AllDataAccessPages | AllDatabaseDiagrams

Remarks

An AccessObject object includes information about one instance of an object. The following table list the types of objects each AccessObject describes, the name of its collection, and what type of information AccessObject contains.

AccessObject | Collection | Contains information about
Form | AllForms | Saved forms
Report | AllReports | Saved reports
Macro | AllMacros | Saved macros
Module | AllModules | Saved modules
Data access page | AllDataAccessPages | Saved data access pages
Table | AllTables | Saved tables
Query | AllQueries | Saved queries
View | AllViews | Saved views
Stored procedure | AllStoredProcedures | Saved stored procedures
Database diagram | AllDatabaseDiagrams | Saved database diagrams

Because an AccessObject object corresponds to an existing object, you can't create new AccessObject objects or delete existing ones. To refer to an AccessObject object in a collection by its ordinal number or by its Name property setting, use any of the following syntax forms:

AllForms(0)
AllForms("name")
AllForms![name]


 AccessObjectProperty Object

AccessObjectProperty Object

AccessObjectProperties collection (AccessObjectProperty object)

AccessObjectProperties collection (AccessObjectProperty object)

AccessObjectProperties collection (AccessObjectProperty object)

An AccessObjectProperty object represents a built-in or user-defined characteristic of an AccessObject object.

Remarks

Every AccessObject object contains an AccessObjectProperties collection that has AccessObjectProperty objects corresponding to the properties of that AccessObject object. The user can also define AccessObjectProperty objects and append them to the AccessObjectProperties collection of some AccessObject objects.

You can create user-defined properties for the following objects:

  • CodeData, CodeProject, CurrentProject, and CurrentData objects

  • AccessObject objects in the following collections.

    CurrentProject and CodeProject object collections Code data and CodeProject object collections
    AllForms AllTables
    AllReports AllQueries
    AllDataAccessPages AllViews
    AllMacros AllStoredProcedures
    AllModules AllDatabaseDiagrams

To add a user-defined property, use the Add method to create and add an AccessObjectProperty object with a unique Name property setting and Value property of the new AccessObjectProperty object to the AccessObjectProperties collection of the appropriate object. The object to which you are adding the user-defined property must already be appended to a collection. Referencing a user-defined AccessObjectProperty object that has not yet been appended to an AccessObjectProperties collection will cause an error, as will appending a user-defined AccessObjectProperty object to an AccessObjectProperties collection containing an AccessObjectProperty object of the same name.

You can delete user-defined properties from the AccessObjectProperties collection.

Note A user-defined AccessObjectProperty object is associated only with the specific instance of an object. The property isn't defined for all instances of objects of the selected type.

The AccessObjectProperty object has two built-in properties:

  • The Name property, a String that uniquely identifies the property.

  • The Value property, a Variant that contains the property setting.

To refer to a built-in or user-defined AccessObjectProperty object in a collection by its ordinal number or by its Name property setting, use any of the following syntax forms:

CurrentProject.AllForms("Form1").Properties(0)
CurrentProject.AllForms("Form1").Properties("name")
CurrentProject.AllForms("Form1").Properties![name]

With the same syntax forms, you can also refer to the Value property of a AccessObjectProperty object. The context of the reference will determine whether you are referring to the AccessObjectProperty object itself or the Value property of the AccessObjectProperty object.

Note Properties in the AccessObjectProperties collection are not stored and can be lost when when the object they are associated with is checked in or out using the Source Code Control add-in.


 AccessObjectProperties Collection

AccessObjectProperties Collection

AccessObjectProperties collection (AccessObjectProperty object)

AccessObjectProperties collection (AccessObjectProperty object)

AccessObjectProperties collection (AccessObjectProperty object)

The AccessObjectProperties collection contains all of the custom AccessObjectProperty objects of a specific instance of an object. These AccessObjectProperty objects (which are often just called properties) uniquely characterize that instance of the object.

Remarks

Use the AccessObjectProperties collection in Visual Basic or in an expression to refer to properties of the CurrentProject, CodeProject, or AccessObject object. For example, you can enumerate the AccessObjectProperties collection to set or return the values of properties of an individual report.

To add a user-defined property to an existing instance of an object, first define its characteristics and add it to the collection with the Add method. Referencing a user-defined AccessObjectProperty object that has not yet been appended to an AccessObjectProperties collection will cause an error, as will appending a user-defined AccessObjectProperty object to an AccessObjectProperties collection containing an AccessObjectProperty object of the same name.

You can use the Remove method to remove user-defined properties from the AccessObjectProperties collection.

Note A built-in or user-defined AccessObjectProperty object is associated only with the specific instance of an object. The property isn't defined for all instances of objects of the selected type.

To refer to a built-in or user-defined AccessObjectProperty object in a collection by its ordinal number or by its Name property setting, use any of the following syntax forms:

CurrentProject.AllForms("Form1").Properties(0)
CurrentProject.AllForms("Form1").Properties("name")
CurrentProject.AllForms("Form1").Properties![name]

With the same syntax forms, you can also refer to the Value property of a AccessObjectProperty object. The context of the reference will determine whether you are referring to the AccessObjectProperty object itself or the Value property of the AccessObjectProperty object.

Note Properties in the AccessObjectProperties collection are not stored and can be lost when when the object they are associated with is checked in or out using the Source Code Control add-in.


 AllDataAccessPages Collection

AllDataAccessPages Collection
AllDataAccessPages collection (AccessObject object)

The AllDataAccessPages collection contains an AccessObject object for each data access page in the CurrentProject or CodeProject object.

NoteAlthough a Microsoft Access project (.adp) or Microsoft Access database (.mdb) can appear to contain data access pages, these pages are actually stored in files that are external to the project or database.

Remarks

The CurrentProject or CodeProject object has an AllDataAccessPages collection containing AccessObject objects that describe instances of all data access pages. For example, you can enumerate the AllDataAccessPages collection in Visual Basic to set or return the values of properties of individual AccessObject objects in the collection.

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

You can refer to an individual AccessObject object in the AllDataAccessPages collection either by referring to the item by name, or by referring to its index within the collection. If you want to refer to a specific data access page in the AllDataAccessPages collection, it's better to refer to the item by name because the index may change.

The AllDataAccessPages collection is indexed beginning with zero. If you refer to a data access page by its index, the first data access page is AllDataAccessPages(0), the second data access page is AllDataAccessPages(1), and so on.

Note To list all open data access pages in the database, use the IsLoaded property of each AccessObject object in the AllDataAccessPages collection. You can then use the Name property of each individual AccessObject object to return the name of a data access page.

You can't add or delete an AccessObject object from the AllDataAccessPages collection.


 AllDatabaseDiagrams Collection

AllDatabaseDiagrams Collection
AllDatabaseDiagrams collection (AccessObject object)

The AllDatabaseDiagrams collection contains an AccessObject for each database diagram in the CurrentData or CodeData object.

Remarks

The CurrentData or CodeData object has an AllDatabaseDiagrams collection containing AccessObject objects that describe instances of all database diagrams specified by CurrentData or CodeData. For example, you can enumerate the AllDatabaseDiagrams collection in Visual Basic to set or return the values of properties of individual AccessObject objects in the collection.

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

You can refer to an individual AccessObject object in the AllDatabaseDiagrams collection either by referring to the object by name, or by referring to its index within the collection. If you want to refer to a specific object in the AllDatabaseDiagrams collection, it's better to refer to the database diagram by name because a database diagram's collection index may change.

The AllDatabaseDiagrams collection is indexed beginning with zero. If you refer to a database diagram by its index, the first database diagram is AllDatabaseDiagrams(0), the second database diagram is AllDatabaseDiagrams(1), and so on.

Notes

  • The AllDatabaseDiagrams collection only contains AccessObject objects within a Microsoft Access project (.adp). A Microsoft Access database (.mdb) does not contain any database diagrams.

  • To list all open database diagrams in the project, use the IsLoaded property of each AccessObject object in the AllDatabaseDiagrams collection. You can then use the Name property of each individual AccessObject object to return the name of a database diagram.

You can't add or delete an AccessObject object from the AllDatabaseDiagrams collection.


 AllForms Collection

AllForms Collection
AllForms collection (AccessObject object)

The AllForms collection contains an AccessObject object for each form in the CurrentProject or CodeProject object.

Remarks

The CurrentProject and CodeProject object has an AllForms collection containing AccessObject objects that describe instances of all the forms in the database. For example, you can enumerate the AllForms collection in Visual Basic to set or return the values of properties of individual AccessObject objects in the collection.

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

You can refer to an individual AccessObject object in the AllForms collection either by referring to the object by name, or by referring to its index within the collection. If you want to refer to a specific object in the AllForms collection, it's better to refer to the form by name because a form's collection index may change.

The AllForms collection is indexed beginning with zero. If you refer to a form by its index, the first form is AllForms(0), the second form is AllForms(1), and so on.

Note To list all open forms in the database, use the IsLoaded property of each AccessObject object in the AllForms collection. You can then use the Name property of each individual AccessObject object to return the name of a form.

You can't add or delete an AccessObject object from the AllForms collection.


 AllMacros Collection

AllMacros Collection
AllMacros collection (AccessObject object)

The AllMacros collection contains an AccessObject for each macro in the CurrentProject or CodeProject object

Remarks

The CurrentProject or CodeProject object has an AllMacros collection containing AccessObject objects that describe instances of all the macros specified by CurrentProject or CodeProject. For example, you can enumerate the AllMacros collection in Visual Basic to set or return the values of properties of individual AccessObject objects in the collection.

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

You can refer to an individual AccessObject object in the AllMacros collection either by referring to the object by name, or by referring to its index within the collection. If you want to refer to a specific object in the AllMacros collection, it's better to refer to the macro by name because a macro's collection index may change.

The AllMacros collection is indexed beginning with zero. If you refer to a macro by its index, the first macro is AllMacros(0), the second macro is AllMacros(1), and so on.

Note To list all open macros in the database, use the IsLoaded property of each AccessObject object in the AllMacros collection. You can then use the Name property of each individual AccessObject object to return the name of a macro.

You can't add or delete an AccessObject object from the AllMacros collection.


 AllModules Collection

AllModules Collection
AllModules collection (AccessObject object)

The AllModules collection contains an AccessObject of each module in the CurrentProject or CodeProject object.

Remarks

The CurrentProject or CodeProject object has an AllModules collection containing AccessObject objects that describe instances of all the Module objects specified by CurrentProject or CodeProject. For example, you can enumerate the AllModules collection in Visual Basic to set or return the values of properties of individual AccessObject objects in the collection.

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

You can refer to an individual AccessObject object in the AllModules collection either by referring to the object by name, or by referring to its index within the collection. If you want to refer to a specific object in the AllModules collection, it's better to refer to the module by name because a module's collection index may change.

The AllModules collection is indexed beginning with zero. If you refer to a module by its index, the first module is AllModules(0), the second module is AllModules(1), and so on.

Note To list all open modules in the database, use the IsLoaded property of each AccessObject object in the AllModules collection. You can then use the Name property of each individual AccessObject object to return the name of a module.

You can't add or delete an AccessObject object from the AllModules collection.


 AllQueries Collection

AllQueries Collection
AllQueries collection (AccessObject object)

The AllQueries collection contains an AccessObject for each query in the CurrentData or CodeData object.

Remarks

The CurrentData or CodeData object has an AllQueries collection containing AccessObject objects that describe instances of all queries specified by CurrentData or CodeData. For example, you can enumerate the AllQueries collection in Visual Basic to set or return the values of properties of individual AccessObject objects in the collection.

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

You can refer to an individual AccessObject object in the AllQueries collection either by referring to the object by name, or by referring to its index within the collection. If you want to refer to a specific object in the AllQueries collection, it's better to refer to the query by name because a query's collection index may change.

The AllQueries collection is indexed beginning with zero. If you refer to a query by its index, the first query is AllQueries(0), the second query is AllQueries(1), and so on.

Notes

  • The AllQueries collection only contains AccessObject objects within a Microsoft Access database (.mdb). A Microsoft Access project (.adp) does not contain any macros, see the AllViews collection.

  • To list all open queries in the database, use the IsLoaded property of each AccessObject object in the AllQueries collection. You can then use the Name property of each individual AccessObject object to return the name of a query.

  • You can't add or delete an AccessObject object from the AllQueries collection.


 AllReports Collection

AllReports Collection
AllReports collection (AccessObject object)

The AllReports collection contains an AccessObject for each report in the CurrentProject or CodeProject object.

Remarks

The CurrentProject or CodeProject object has an AllReports collection containing AccessObject objects that describe instances of all the reports in the database. For example, you can enumerate the AllReports collection in Visual Basic to set or return the values of properties of individual AccessObject objects in the collection.

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

You can refer to an individual AccessObject object in the AllReports collection either by referring to the item by name, or by referring to its index within the collection. If you want to refer to a specific report in the AllReports collection, it's better to refer to the item by name because the index may change.

The AllReports collection is indexed beginning with zero. If you refer to a report by its index, the first report is AllReports(0), the second report is AllReports(1), and so on.

Note To list all open reports in the database, use the IsLoaded property of each AccessObject object in the AllReports collection. You can then use the Name property of each individual AccessObject object to return the name of a report.

You can't add or delete an AccessObject object from the AllReports collection.


 AllStoredProcedures Collection

AllStoredProcedures Collection
AllStoredProcedures collection (AccessObject object)

The AllStoredProcedures collection contains an AccessObject for each stored procedure in the CurrentData or CodeData object.

Remarks

The CurrentData or CodeData object has an AllStoredProcedures collection containing AccessObject objects that describe instances of all stored procedures specified by CurrentData or CodeData. For example, you can enumerate the AllStoredProcedures collection in Visual Basic to set or return the values of properties of individual AccessObject objects in the collection.

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

You can refer to an individual AccessObject object in the AllStoredProcedures collection either by referring to the object by name, or by referring to its index within the collection. If you want to refer to a specific object in the AllStoredProcedures collection, it's better to refer to the stored procedures by name because a stored procedure's collection index may change.

The AllStoredProcedures collection is indexed beginning with zero. If you refer to a stored procedure by its index, the first stored procedure is AllStoredProcedures(0), the second stored procedure is AllStoredProcedures(1), and so on.

Notes

  • The AllStoredProcedures collection only contains AccessObject objects within a Microsoft Access project (.adp). A Microsoft Access database (.mdb) does not contain any stored procedures, see the AllMacros collection.

  • To list all open stored procedures in the project, use the IsLoaded property of each AccessObject object in the AllStoredProcedures collection. You can then use the Name property of each individual AccessObject object to return the name of a stored procedure.

  • You can't add or delete an AccessObject object from the AllStoredProcedures collection.


 AllTables Collection

AllTables Collection
AllTables collection (AccessObject object)

The AllTables collection contains an AccessObject for each tables in the CurrentData or CodeData object.

Remarks

The CurrentData or CodeData object has an AllTables collection containing AccessObject objects that describe instances of all tables specified by CurrentData or CodeData. For example, you can enumerate the AllTables collection in Visual Basic to set or return the values of properties of individual AccessObject objects in the collection.

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

You can refer to an individual AccessObject object in the AllTables collection either by referring to the object by name, or by referring to its index within the collection. If you want to refer to a specific object in the AllTables collection, it's better to refer to the table by name because a table's collection index may change.

The AllTables collection is indexed beginning with zero. If you refer to a table by its index, the first table is AllTables(0), the second table is AllTables(1), and so on.

Note To list all open tables in the database, use the IsLoaded property of each AccessObject object in the AllTables collection. You can then use the Name property of each individual AccessObject object to return the name of a table.

You can't add or delete an AccessObject object from the AllTables collection.


 AllViews Collection

AllViews Collection
AllViews collection (AccessObject object)

The AllViews collection contains an AccessObject for each view in the CurrentData or CodeData object.

Remarks

The CurrentData or CodeData object has an AllViews collection containing AccessObject objects that describe instances of all views specified by CurrentData or CodeData. For example, you can enumerate the AllViews collection in Visual Basic to set or return the values of properties of individual AccessObject objects in the collection.

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

You can refer to an individual AccessObject object in the AllViews collection either by referring to the object by name, or by referring to its index within the collection. If you want to refer to a specific object in the AllViews collection, it's better to refer to the view by name because a view's collection index may change.

The AllViews collection is indexed beginning with zero. If you refer to a view by its index, the first view is AllViews(0), the second table is AllViews(1), and so on.

Notes

  • The AllViews collection only contains AccessObject objects within a Microsoft Access project (.adp). A Microsoft Access database (.mdb) does not contain any views, see the AllQueries collection.

  • To list all open views in the project, use the IsLoaded property of each AccessObject object in the AllViews collection. You can then use the Name property of each individual AccessObject object to return the name of a view.

  • You can't add or delete an AccessObject object from the AllViews collection.


 Application Object

Application Object

The Application object refers to the active Microsoft Access application.

Remarks

The Application object contains all Microsoft Access objects and collections.

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 a COM 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 a COM 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 9.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 Object
Set appAccess = CreateObject("Access.Application.9")

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 CommandBars object by using the CommandBars property of the Application object, you can access all OFF9TBD command bar 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 COM component.


 CodeData Object

CodeData Object

The CodeData object refers to objects stored within the code database by the source (server) application (Jet or SQL).

Remarks

The CodeData object has several collections that contain specific object types within the code database. The following table lists the name of each collection defined by the database and the types of objects it contains.

Collections | Object type
AllTables | All tables
AllQueries | All queries (the count of queries in a Microsoft Access project (.adp) will be zero).
AllViews | All views (the count of views in an Access database (.mdb) database will be zero).
AllStoredProcedures | All stored procedures (the count of stored procedures in a .mdb database will be zero).
AllDatabaseDiagrams | All database diagrams (the count of database diagrams in a .mdb database will be zero).

NoteThe collections in the preceding table contain all of the respective objects in the database regardless if they are opened or closed.

For example, an AccessObject representing a table is a member of the AllTables collection, which is a collection of AccessObject objects within the current database. Within the AllTables collection, individual tables are indexed beginning with zero. You can refer to an individual AccessObject object in the AllTables collection either by referring to the table by name, or by referring to its index within the collection. If you want to refer to a specific item in the AllTables collection, it's better to refer to it by name because the item's index may change. If the object name includes a space, the name must be surrounded by brackets ([ ]).

Syntax | Example
AllTables!tablename | AllTables!OrderTable
AllTables![table name] | AllTables![Order Table]
AllTables("tablename") | AllTables("OrderTable")
AllTables(index) | AllTables(0)


 Control Object

Control Object
Controls collection (Control object)

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.

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 TextBox
Set 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 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.


 Controls Collection

Controls Collection
Controls collection (Control object)

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.

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.


 CurrentData Object

CurrentData Object

The CurrentData object refers to the objects stored in the current database by the source (server) application (Jet or SQL).

Remarks

The CurrentData object has several collections that contain specific AccessObject objects within the current database. The following table lists the name of each collection defined by the database and the types of objects it contains.

Collections | Object type
AllTables | All tables
AllQueries | All queries (the count of queries in a Microsoft Access project (.adp) will be zero).
AllViews | All views (the count of views in an Access database (.mdb) database will be zero).
AllStoredProcedures | All stored procedures (the count of stored procedures in a .mdb database will be zero).
AllDatabaseDiagrams | All database diagrams (the count of database diagrams in a .mdb database will be zero).

NoteThe collections in the preceding table contain all of the respective objects in the database regardless if they are opened or closed.

For example, an AccessObject representing a table is a member of the AllTables collection, which is a collection of AccessObject objects within the current database. Within the AllTables collection, individual tables are indexed beginning with zero. You can refer to an individual AccessObject object in the AllTables collection either by referring to the table by name, or by referring to its index within the collection. If you want to refer to a specific item in the AllTables collection, it's better to refer to it by name because the item's index may change. If the object name includes a space, the name must be surrounded by brackets ([ ]).

Syntax | Example
AllTables!tablename | AllTables!OrderTable
AllTables![table name] | AllTables![Order Table]
AllTables("tablename") | AllTables("OrderTable")
AllTables(index) | AllTables(5)


 CurrentProject Object

CurrentProject Object

The CurrentProject object refers to the project for the current Microsoft Access project (.adp) or Access database (.mdb).

Remarks

The CurrentProject object has several collections that contain specific AccessObject objects within the current database. The following table lists the name of each collection and the types of objects it contains.

Collections | Object type
AllForms | All forms
AllReports | All reports
AllMacros | All macros
AllModules | All modules
AllDataAccessPages | All data access pages

NoteThe collections in the preceding table contain all of the respective objects in the database regardless if they are opened or closed.

For example, an AccessObject object representing a form is a member of the AllForms collection, which is a collection of AccessObject objects within the current database. Within the AllForms collection, individual members of the collection are indexed beginning with zero. You can refer to an individual AccessObject object in the AllForms collection either by referring to the form by name, or by referring to its index within the collection. If you want to refer to a specific object in the AllForms collection, it's better to refer to it by name because a item's collection index may change. If the object name includes a space, the name must be surrounded by brackets ([ ]).

Syntax | Example
AllForms!formname | AllForms!OrderForm
AllForms![form name] | AllForms![Order Form]
AllForms("formname") | AllForms("OrderForm")
AllForms(index) | AllForms(0)


DefaultWebOptions Object

The DefaultWebOptions object contains global application-level attributes used by Microsoft Access when you save a data access page as a Web page or open a Web page. You can return or set attributes either at the application (global) level or at the data access page level. (Note that attribute values can be different from one data access page to another, depending on the attribute value at the time the data access page was saved.) Data access page-level attributes override application-level attributes. Data access page attributes are contained in the WebOptions object.

Remarks

Use the DefaultWebOptions property to return the DefaultWebOptions object.


 DoCmd Object

DoCmd Object

You can use the methods of the DoCmd object to run Microsoft Access actions from Visual Basic. An action performs tasks such as closing windows, opening forms, and setting the value of controls. For example, you can use the OpenForm method of the DoCmd object to open a form, or use the Hourglass method to change the mouse pointer to an hourglass icon.

Syntax

[application.]DoCmd.method [arg1, arg2, ...]

The DoCmd object has the following arguments.

Argument | Description
application | Optional. The Application object.
method | One of the methods supported by this object.
arg1, arg2, ... | The arguments for the selected method. These arguments are the same as the action arguments for the corresponding action.

Remarks

Most of the methods of the DoCmd object have arguments — 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:

  • AddMenu.

  • MsgBox. Use the MsgBox function.

  • RunApp. Use the Shell function to run another application.

  • RunCode. Run the function directly in Visual Basic.

  • SendKeys. Use the SendKeys statement.

  • SetValue. Set the value directly in Visual Basic.

  • StopAllMacros.

  • StopMacro.

For more information on the Microsoft Access action corresponding to a DoCmd method, search the Help index for the name of the action.


 Hyperlink Object

Hyperlink Object

The Hyperlink object represents a hyperlink associated with a control on a form, report, or data access page.

Remarks

Use the Hyperlink property to return a reference to a hyperlink object.


 FormatCondition Object

FormatCondition Object

The FormatCondition object represents a conditional format of a combo box or text box control and is a member of the FormatConditions collection.

Remarks

You can use the FormatConditions(index), where index is the index number of the conditional format, to return a FormatCondition object.

Use the Add method to create a new conditional format. You can use the Modify method to change one of the formats, or the Delete method to delete a format.

Conditional formatting can also be set on a combo box or text box from the Conditional Formatting dialog box. The Conditional Formatting dialog box is available by clicking Conditional Formatting on the Format menu when a form is in Design view.

Use the BackColor, Enabled, FontBold, FontItalic, FontUnderline, and ForeColor properties of the FormatCondition object to control the appearance of formatted combo box and text box controls.


 FormatConditions Collection

FormatConditions Collection

The FormatConditions collection represents the collection of conditional formats for a combo box or text box control. Each format is represented by a FormatCondition object.

Remarks

Use the FormatConditions property of a combo box or text box in Visual Basic or in an expression to return a FormatConditions collection. Use the Add method to create a new conditional format, and use the Modify method to change an existing conditional format.

You can use the Modify method to change one of the formats, or the Delete method to delete a format.

Conditional formatting can also be set on a combo box or text box from the Conditional Formatting dialog box. The Conditional Formatting dialog box is available by clicking Conditional Formatting on the Format menu when a form is in Design view.


 Form Object

Form Object

 Forms collection (Form object)

A Form object refers to a particular Microsoft Access form.

Remarks

A Form object is a member of the Forms collection, which is a collection of all currently open forms. Within the Forms collection, individual forms are indexed beginning with zero. You can refer to an individual Form object in the Forms collection either by referring to the form by name, or by referring to its index within the collection. If you want to refer to a specific form in the Forms collection, it's better to refer to the form by name because a form's collection index may change. If the form name includes a space, the name must be surrounded by brackets ([ ]).

Syntax | Example
Forms!formname | Forms!OrderForm
Forms![form name] | Forms![Order Form]
Forms("formname") | Forms("OrderForm")
Forms(index) | Forms(0)

Each Form object has a Controls collection, which contains all controls on the form. You can refer to a control on a form either by implicitly or explicitly referring to the Controls collection. Your code will be faster if you refer to the Controls collection implicitly. The following examples show two of the ways you might refer to a control named NewData on the form called OrderForm:

' Implicit reference.
Forms!OrderForm!NewData
' Explicit reference.
Forms!OrderForm.Controls!NewData

The next two examples show how you might refer to a control named NewData on a subform ctlSubForm contained in the form called OrderForm:

Forms!OrderForm.ctlSubForm.Form!Controls.NewData
Forms!OrderForm.ctlSubForm!NewData

Each Form object has a Controls collection, which contains all controls on the form. You can refer to a control on a form either by implicitly or explicitly referring to the Controls collection. Your code will be faster if you refer to the Controls collection implicitly. The following examples show two of the ways you might refer to a control named NewData on the form called OrderForm:

' Implicit reference.
Forms!OrderForm!NewData
' Explicit reference.
Forms!OrderForm.Controls!NewData

The next two examples show how you might refer to a control named NewData on a subform ctlSubForm contained in the form called OrderForm:

Forms!OrderForm.ctlSubForm.Form!Controls.NewData
Forms!OrderForm.ctlSubForm!NewData


 Forms Collection

Forms Collection

 Forms collection (Form object)

The Forms collection contains all of the currently open forms in a Microsoft Access database.

Remarks

Use the Forms collection in Visual Basic or in an expression to refer to forms that are currently open. For example, you can enumerate the Forms collection to set or return the values of properties of individual forms in the collection.

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

You can refer to an individual Form object in the Forms collection either by referring to the form by name, or by referring to its index within the collection. If you want to refer to a specific form in the Forms collection, it's better to refer to the form by name because a form's collection index may change.

The Forms collection is indexed beginning with zero. If you refer to a form by its index, the first form opened is Forms(0), the second form opened is Forms(1), and so on. If you opened Form1 and then opened Form2, Form2 would be referenced in the Forms collection by its index as Forms(1). If you then closed Form1, Form2 would be referenced in the Forms collection by its index as Forms(0).

Note To list all forms in the database, whether open or closed, enumerate the AllForms collection of the CurrentProject object. You can then use the Name property of each individual AccessObject object to return the name of a form.

You can't add or delete a Form object from the Forms collection.


 Module Object

Module Object

A Module object refers to a standard module or a class module.

Remarks

Microsoft Access includes class modules that are not associated with any object, and form modules and report modules, which are associated with a form or report.

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.

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.

The following example returns a reference to a standard Module object and assigns it to an object variable:

Dim mdl As Module
Set 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 Module
Set 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 Module
Set mdl = Forms!Employees.Module

Once you've returned a reference to a Module object, you can set or read its properties and apply its methods.


 Modules Collection

Modules Collection

Modules collection (Module object)

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.

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.


 Page Object

Page Object

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.

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.

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


 Pages Collection

Pages Collection

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 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 Collection (Microsoft Access)

Properties Collection
Properties collection (Control object)
Properties collection (Form object)
Properties collection (Report object)

The Properties collection contains all of the built-in properties in an instance of an open Form, Report, or Control object. These properties uniquely characterize that instance of the object.

Remarks

Use the Properties collection in Visual Basic or in an expression to refer to form, report, or control properties on forms or reports that are currently open.

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

You can use the Properties collection of an object to enumerate the object's built-in properties. You don't need to know beforehand exactly which properties exist or what their characteristics (Name and Value properties) are to manipulate them.

Note In addition to the built-in properties, you can also create and add your own user-defined properties. To add a user-defined property to an existing instance of an object, see the AccessObjectProperties collection and Add method topics.


 Reference Object

Reference Object

References collection (Reference object)

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.

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.

The following example refers to the Reference object that represents the reference to the Microsoft Access type library:

Dim ref As Reference
Set ref = References!Access


References Collection

References collection (Reference object)

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.

The References collection belongs to the Microsoft Access Application object.

Individual Reference objects in the References collection are indexed beginning with 1.


 Report Object

Report Object

 Reports collection (Report object)

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 ([ ]).

Syntax | Example
Reports!reportname | Reports!OrderReport
Reports![report name] | Reports![Order Report]
Reports("reportname") | Reports("OrderReport")
Reports(index) | Reports(0)

Each Report object has a Controls collection, which contains all controls on the report. You can refer to a control on a report either by implicitly or explicitly referring to the Controls collection. Your code will be faster if you refer to the Controls collection implicitly. The following examples show two of the ways you might refer to a control named NewData on a report called OrderReport.

' Implicit reference.
Reports!OrderReport!NewData
' Explicit reference.
Reports!OrderReport.Controls!NewData


 Reports Collection

Reports Collection

 Reports collection (Report object)

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 AllReports collection of the CurrentProject object. You can then use the Name property of each individual AccessObject object to return the name of a report.

You can't add or delete a Report object from the Reports collection.


 Screen Object

Screen Object

The Screen object refers to the particular form, report, or control that currently has the focus.

Remarks

You can use the Screen object together with its properties to refer to a particular form, report, or control that has the focus. For example, you can use the Screen object with the ActiveForm property to refer to the form in the active window without knowing the form's name. The following example displays the name of the form in the active window:

MsgBox Screen.ActiveForm.Name

Referring to the Screen object doesn't make a form, report, or control active. To make a form, report, or control active, you must use the SelectObject method of the DoCmd object.

If you refer to the Screen object when there'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.


 WebOptions Object

WebOptions Object

 DataAccessPages collection (DataAccessPage object)

A WebOptions object refers to a specific Microsoft Access data access page's web option properties.

Remarks

Contains data access page attributes used by Microsoft Access when you save a data access page as a Web page or open a Web page. You can return or set attributes either at the application (global) level or at the data access page level. (Note that attribute values can be different from one data access page to another, depending on the attribute value at the time the data access page was saved.) Data access page-level attributes override application-level attributes. Application-level attributes are contained in the DefaultWebOptions object.

Remarks

Use the WebOptions property to return the WebOptions object.

Remember that if you change the value of a data access page-level attribute, the corresponding application-level attribute is automatically set to the same value. Therefore, you should restore and save the application-level values for a given data access page during each session in that data access page.


Properties Reference

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

Grouped by Object or Collection

AccessObject* | Err (VBA)
AccessObjectProperties* | Error (ADO)
AccessObjectProperty* | Errors (ADO)
AllDataAccessPages* | Error, Errors (DAO)
AllDatabaseDiagrams* | Field (ADO)
AllForms* | Field, Fields (DAO)
AllMacros* | Fields (ADO)
AllModules* | FileSearch*
AllQueries* | Form
AllReports* | Forms
AllStoredProcedures* | Group, Groups (DAO)
AllTables* | Index
AllViews* | Index, Indexes (DAO)
AnswerWizard | LanguageSettings*
Application | Module
Assistant | Modules
CodeData* | Parameter, Parameters (DAO)
CodeProject* | Parameters (ADO)
Collection (VBA) | Properties
ComAddIns* | Property, Properties (DAO)
Command (ADO) | Query
CommandBars | QueryDef, QueryDefs (DAO)
Connection (ADO) | Recordset (ADO)
Connection, Connections (DAO) | Recordset, Recordsets (DAO)
Container, Containers (DAO) | Reference
Control | References
Controls | Relation, Relations (DAO)
CurrentData* | Report
CurrentProject* | Reports
DataAccessPages* | Screen
DataAccessPage* | Table
Database, Databases (DAO) | TableDef, TableDefs (DAO)
DBEngine (DAO) | User, Users (DAO)
Debug (VBA) | VBE * (VBA)
DefaultWebOptions* | WebOptions*
DoCmd | Workspace, Workspaces (DAO)
Document, Documents (DAO) |

Listed Alphabetically

A

AbsolutePage (ADO) | AllowEdits
AbsolutePosition (ADO) | AllowFilters
AbsolutePosition (DAO) | AllowFullMenus
Action | AllowShortcutMenus
ActiveCommand (ADO) | AllowSpecialKeys
ActiveConnection (ADO) | AllowToolbarChanges
ActiveControl | AllowZeroLength (DAO)
ActiveDatasheet | AllowZeroLength
ActiveForm | AllPermissions (DAO)
ActiveReport | AppIcon
ActualSize (ADO) | Application
AddColon | AppTitle
AfterDelConfirm | Assistant
AfterInsert | Attributes (ADO)
AfterUpdate | Attributes (DAO)
Alias | AutoActivate
AllowAdditions | AutoCenter
AllowAutoCorrect | AutoExpand
AllowBreakIntoCode | AutoLabel
AllowBuiltInToolbars | AutoRepeat
AllowBypassKey | AutoResize
AllowDeletions | AutoTab

B

BackColor | Bookmark
BackStyle | Bookmark (ADO)
BatchCollisionCount (DAO) | Bookmark (DAO)
BatchCollisions (DAO) | Bookmarkable (DAO)
BatchSize (DAO) | BorderColor
BeforeDelConfirm | BorderStyle
BeforeInsert | BorderWidth
BeforeUpdate | BoundColumn
BOF (ADO) | BuiltIn
BOF (DAO) |

C

CacheSize (ADO) | Connection (DAO)
CacheSize (DAO) | ConnectionString (ADO)
CacheStart (DAO) | ConnectionTimeout (ADO)
Cancel | Container (DAO)
CanGrow | ControlBox
CanShrink | ControlSource
Caption | ControlTipText
Class | ControlType
CloseButton | Count (ADO)
Clustered (DAO) | Count (DAO)
CodeContextObject | Count (VBA)
CollatingOrder (DAO) | Count
Column | CountOfDeclarationLines
ColumnCount | CountOfLines
ColumnHeadings | CurrentObjectName
ColumnHeads | CurrentObjectType
ColumnHidden | CurrentRecord
ColumnOrder | CurrentSectionLeft
ColumnWidth | CurrentSectionTop
ColumnWidths | CurrentView
CommandBars | CurrentX
CommandText (ADO) | CurrentY
CommandTimeout (ADO) | CursorLocation (ADO)
CommandType (ADO) | CursorType (ADO)
ConflictTable (DAO) | Cycle
Connect (DAO) |

D

Database Properties | DefaultUser (DAO)
Database (DAO) | DefaultValue (DAO)
DataEntry | DefaultValue
DataMember (ADO) | DefaultView
DatasheetBackColor | DefinedSize (ADO)
DatasheetCellsEffect | Description
DatasheetFontHeight | Description (ADO)
DatasheetFontItalic | Description (DAO)
DatasheetFontName | Description (VBA)
DatasheetFontUnderline | DesignMasterID (DAO)
DatasheetFontWeight | DestConnectStr
DatasheetForeColor | DestinationDB
DatasheetGridLinesBehavior | DestinationTable
DatasheetGridLinesColor | Direction (ADO)
DataSource (ADO) | Direction (DAO)
DataType | Dirty
DataUpdatable (DAO) | DisplayControl
DateCreated (DAO) | DisplayType
DateGrouping | DisplayWhen
DBEngine | DistinctCount (DAO)
DecimalPlaces | DividingLines
Default | DrawMode
DefaultCursorDriver (DAO) | DrawStyle
DefaultDatabase (ADO) | DrawWidth
DefaultType (DAO) |

E–F

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

G–H

GridX | HelpContext (ADO)
GridY | HelpContext (DAO)
GroupFooter | HelpContext (VBA)
GroupHeader | HelpContextID
GroupInterval | HelpFile (ADO)
GroupLevel | HelpFile (DAO)
GroupOn | HelpFile
GrpKeepTogether | HideDuplicates
GUID | HWnd
HasContinued | Hyperlink
HasData | HyperlinkAddress
HasModule | HyperlinkSubAddress
Height |

I–K

IgnoreNulls (DAO) | IsBroken
IgnoreNulls | IsolateODBCTrans (DAO)
ImageHeight | IsolationLevel (ADO)
ImageWidth | IsVisible
Index (ADO) | Item (ObjectFrame Control)
Index (DAO) | Item (Collections)
Indexed | ItemData
Inherit (DAO) | KeepLocal (DAO)
Inherited (DAO) | KeepTogether — Groups
IniPath (DAO) | KeepTogether — Sections
InputMask | KeyPreview
InSelection | Kind
InsideHeight |
InsideWidth |

L

LabelAlign | LinkMasterFields
LabelX | ListCount
LabelY | ListIndex
LastDLLError (VBA) | ListRows
LastModified (DAO) | ListWidth
LastUpdated (DAO) | Locked
LayoutForPrint | LockEdits (DAO)
Left | LockType (ADO)
LimitToList | LoginTimeout (DAO)
Lines | LogMessages (DAO)
LineSlant | LogMessages
LinkChildFields | LpOLEObject

M–N

Major | MultiRow
MarshalOptions (ADO) | MultiSelect
MaxRecords | Name (ADO)
MaxRecords (ADO) | Name (DAO)
MaxRecords (DAO) | Name
MDE | NativeError (ADO)
Me | NavigationButtons
MenuBar | NewRecord
MinMaxButtons | NewRowOrCol
Minor | NewValues
Modal | NoMatch (DAO)
Mode (ADO) | Number (ADO)
Module | Number (DAO)
MousePointer | Number (VBA)
MoveLayout | NumericScale (ADO)

O

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

P

Page | PictureType
PageCount (ADO) | PID (DAO)
PageFooter | PopUp
PageHeader | Precision (ADO)
PageIndex | Prepare (DAO)
Pages | Prepared (ADO)
PageSize (ADO) | PreviousControl
Painting | Primary (DAO)
PaintPalette | Primary
PaletteSource | PrintCount
Parent | PrintSection
PartialReplica (DAO) | ProcBodyLine
Password (DAO) | ProcCountLines
PercentPosition (DAO) | ProcOfLine
Permissions (DAO) | ProcStartLine
Picture | ProjectName
PictureAlignment | Properties
PictureData | Provider (ADO)
PicturePages | PrtDevMode
PictureSizeMode | PrtDevNames
PictureTiling | PrtMip

Q–R

QueryTimeout (DAO) | ReplicationConflictFunction
RecordCount (ADO) | Report
RecordCount (DAO) | Required (DAO)
RecordLocks | Required
RecordsAffected (DAO) | Restartable (DAO)
RecordSelectors | ReturnsRecords (DAO)
RecordsetClone | ReturnsRecords
RecordsetType | RowHeight
RecordSource | RowSource
RepeatSection | RowSourceType
Replicable (DAO) | RunningSum
ReplicaFilter (DAO) | RunPermissions
ReplicaID (DAO) |

S

ScaleHeight | Source
ScaleLeft | SourceConnectStr
ScaleMode | SourceDatabase
ScaleTop | SourceDoc
ScaleWidth | SourceField (DAO)
ScrollBars | SourceItem
Section | SourceObject
Selected | SourceTable (DAO)
SelHeight | SourceTableName (DAO)
SelLeft | SpecialEffect
SelLength | SQL (DAO)
SelStart | SQLState (ADO)
SelText | StartupForm
SelTop | StartupMenuBar
SelWidth | StartupShortcutMenuBar
ShortcutMenu | StartupShowDBWindow
ShortcutMenuBar | StartupShowStatusBar
Size (DAO) | State (ADO)
SizeMode | Status (ADO)
Sort (ADO) | StatusBarText
Sort (DAO) | StayInSync (ADO)
SortOrder | StillExecuting (DAO)
Source (ADO Error Object) | Style
Source (ADO Recordset Object) | SystemDB (DAO)
Source (DAO) |
Source (VBA) |

T–U

TabFixedHeight | Type (ADO)
TabFixedWidth | Type (DAO)
TabIndex | Type
Table (DAO) | UnderlyingValue (ADO)
TabStop | Unique (DAO)
Tag | Unique
Text | UniqueRecords
TextAlign | UniqueValues
TimerInterval | Updatable (DAO)
Toolbar | UpdateOptions (DAO)
Top | UpdateOptions
TopValues | UserControl
Transactions (DAO) | UserName (DAO)
Transparent | UseTransaction
TripleState |

V–Z

V1xNullBehavior (DAO) | Version (DAO)
ValidateOnSet (DAO) | ViewsAllowed
ValidationRule (DAO) | Visible
ValidationRule | Visible (Application object)
ValidationText (DAO) | VisibleValue (DAO)
ValidationText | WhatsThisButton (VBA)
Value (ADO) | WhatsThisButton
Value (DAO) | Width
Value | WillContinue
Verb | WindowHeight
Version (ADO) | WindowWidth


 New Properties (Alphabetic List)

New Properties (Alphabetic List)

Properties that were added to existing objects in Microsoft Access 2000 are listed in the following table (sorted alphabetically).

A–G

ActiveDataAccessPage

Address

AllDataAccessPages

AllDatabaseDiagrams

AllForms

AllMacros

AllModules

AllowDesignChanges

AllQueries

AllReports

AllStoredProcedures

AllTables

AllViews

AlwaysSaveInDefaultEncoding

AnswerWizard

BaseConnectionString

BottomMargin

CheckIfOfficeHTMLEditor

CodeData

CodeProject

 COMAddIns

Connection

ConnectionString

CurrentData

CurrentProject

DataAccessPages

DefaultWebOptions

Document

DownloadComponents

EmailSubject

Enabled (FormatCondition Object)

Encoding

Expression1

Expression2

FeatureInstall

FolderSuffix

FileSearch

FollowedHyperlinkColor

FormatConditions

FullName

H–P

HyperlinkColor

InputParameters

IsConnected

IsHyperlink

IsLoaded

ItemsSelected

LanguageSettings

LeftMargin

LineSpacing

LocationOfComponents

 MaxRecButton

Operator (FormatCondition Object)

OrganizeInFolder

Path

ProductCode

ProjectType

Properties Property (AccessObjectProperties Collection)

Properties Property (Properties Collection)

Q–Z

Recordset

ResyncCommand

RightMargin

ScreenTip

ServerFilter

ServerFilterByForm

SubAddress

SubdatasheetExpanded

SubdatasheetHeight

SubdatasheetName

 TextToDisplay

TopMargin

Type (AccessObject Object)

Type (FormatCondition Object)

UnderlineHyperlinks

UniqueTable

UseLongFileNames

VBE

Vertical

WebOptions

Microsoft Office properties

To see a list of the new properties available in the Microsoft Office 9.0 Object Library, open the Microsoft Office Visual Basic Reference in the Help contents.

To use the objects supplied by Microsoft Office, you must set a reference to the Microsoft Office 9.0 Object Library when the Visual Basic Editor is open by clicking References on the Tools Menu and selecting the check box next to this library.

Microsoft Visual Basic Editor properties

To see a list of the new properties available in the Microsoft Visual Basic for Applications Extensibility 5.3 Object Library, open the Microsoft Visual Basic Reference in the Help contents.

To use the objects supplied by the Microsoft Visual Basic Editor, you must set a reference to the Microsoft Visual Basic for Applications Extensibility 5.3 Object Library. To set this reference, open the Visual Basic Editor and click References on the Tools Menu and select the check box next to this library.


ActiveX Control Properties

The following list identifies the properties you can set for an ActiveX control.

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

BorderColor | Object
BorderStyle | OLEClass
BorderWidth | OnEnter (forms)
Class | OnExit (forms)
ControlSource | OnGotFocus (forms)
ControlTipText | OnLostFocus (forms)
ControlType | OnUpdated (forms)
Custom | SpecialEffect
DisplayWhen (forms) | TabIndex (forms)
Enabled (forms) | TabStop (forms)
Height | Tag
HelpContextID (forms) | Top
InSelection (forms) | Verb
Left | Visible
Locked (forms) | Width
Name |


Bound Object Frame Control Properties

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

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

A-O

AddColon | LabelAlign
AfterUpdate (forms) | LabelX
AutoActivate (forms) | LabelY
AutoLabel | Left
BackColor | Locked (forms)
BackStyle | Name
BeforeUpdate (forms) | OLETypeAllowed
BorderColor | OnClick (forms)
BorderStyle | OnDblClick (forms)
BorderWidth | OnEnter (forms)
Class | OnExit (forms)
ControlSource | OnGotFocus (forms)
ControlTipText | OnKeyDown (forms)
ControlType | OnKeyPress (forms)
DisplayType | OnKeyUp (forms)
DisplayWhen (forms) | OnLostFocus (forms)
Enabled (forms) | OnMouseDown (forms)
Height | OnMouseMove (forms)
HelpContextID (forms) | OnMouseUp (forms)
InSelection (forms) | OnUpdated (forms)

P-Z

ShortcutMenuBar | TabStop (forms)
SizeMode | Tag
SourceDoc | Top
SourceItem | UpdateOptions
SpecialEffect | Verb
StatusBarText (forms) | Visible
TabIndex (forms) | Width


Chart Control Properties (Forms and Reports)

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

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

AddColon | OnClick (forms)
AfterUpdate (forms) | OnDblClick (forms)
AutoActivate (forms) | OnEnter (forms)
AutoLabel | OnExit (forms)
BackColor | OnGotFocus (forms)
BackStyle | OnKeyDown (forms)
BeforeUpdate (forms) | OnKeyPress (forms)
BorderColor | OnKeyUp (forms)
BorderStyle | OnLostFocus (forms)
BorderWidth | OnMouseDown (forms)
Class | OnMouseMove (forms)
ColumnCount | OnMouseUp (forms)
ColumnHeads | OnUpdated (forms)
ControlSource | RowSource
ControlTipText | RowSourceType
ControlType | ShortcutMenuBar
DisplayType | SizeMode
DisplayWhen (forms) | SourceDoc
Enabled (forms) | SourceItem
Height | SpecialEffect
HelpContextID (forms) | StatusBarText (forms)
InSelection (forms) | TabIndex (forms)
LabelAlign | TabStop (forms)
LabelX | Tag
LabelY | Top
Left | UpdateOptions
LinkChildFields | Verb
LinkMasterFields | Visible
Locked (forms) | Width
Name |
OLETypeAllowed |


Check Box Control Properties

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

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

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


Combo Box Control Properties

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

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

A–M

AddColon | Enabled (forms)
AfterUpdate (forms) | FontItalic
AllowAutoCorrect | FontName
AutoExpand | FontSize
AutoLabel | FontUnderline
BackColor | FontWeight
BackStyle | ForeColor
BeforeUpdate (forms) | Format
BorderColor | Height
BorderStyle | HelpContextID (forms)
BorderWidth | InputMask
BoundColumn | InSelection (forms)
Column | IsHyperlink
ColumnCount | ItemData
ColumnHeads | LabelAlign
ColumnWidths | LabelX
ControlSource | LabelY
ControlTipText (forms) | Left
ControlType | LimitToList
DecimalPlaces | ListRows
DefaultValue (forms) | ListWidth
DisplayWhen (forms) | Locked (forms)

N–Z

Name | RowSource
OnChange (forms) | RowSourceType
OnClick (forms) | ShortcutMenuBar
OnDblClick (forms) | SpecialEffect
OnEnter (forms) | StatusBarText (forms)
OnExit (forms) | TabIndex (forms)
OnGotFocus (forms) | TabStop (forms)
OnKeyDown (forms) | Tag
OnKeyPress (forms) | TextAlign
OnKeyUp (forms) | Top
OnLostFocus (forms) | ValidationRule (forms)
OnMouseDown (forms) | ValidationText (forms)
OnMouseMove (forms) | Visible
OnMouseUp (forms) | Width
OnNotInList (forms) |


Command Button Control Properties

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

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

AddColon | Name
AutoLabel | OnClick (forms)
AutoRepeat (forms) | OnDblClick (forms)
Cancel (forms) | OnEnter (forms)
Caption | OnExit (forms)
ControlTipText (forms) | OnGotFocus (forms)
ControlType | OnKeyDown (forms)
Default | OnKeyPress (forms)
DisplayWhen (forms) | OnKeyUp (forms)
Enabled (forms) | OnLostFocus (forms)
FontItalic | OnMouseDown (forms)
FontName | OnMouseMove (forms)
FontSize | OnMouseUp (forms)
FontUnderline | Picture
FontWeight | PictureType
ForeColor | ShortcutMenuBar
Height | StatusBarText (forms)
HelpContextID (forms) | TabIndex (forms)
HyperlinkAddress | TabStop (forms)
HyperlinkSubAddress | Tag
InSelection (forms) | Top
LabelAlign | Transparent
LabelX | Visible
LabelY | Width
Left |


 Control Properties Reference

Control Properties Reference

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

You can change the default property settings before you add a control to a form or report, or you can change property settings for a control that has already been placed on a form or report.

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

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


 Data Access Page Control Properties

Data Access Page Control Properties

The following list identifies the Dynamic HTML properties, Microsoft Access properties, Access element extension properties, and Web properties you can set for a control when used on a data access page.

Click any name below to display additional information about that property. These properties can be set in the property sheet or in the Microsoft Script Editor.

AccessKey | DisplayGridlines | Overflow
Align | DisplayHorizontalScrollBox | Port
AlinkColor | DisplayPropertyToolbox | Position
AllowDetails | DisplayRowHeaders | ProviderType
AllowFiltering | DisplayTitleBar | ReadOnly
AllowGrouping | DisplayToolbar | RecordsetLabel
AllowPropertyToolbox | DisplayVerticalScrollBar | RecordSource
Alt | Dynsrc | ResyncCommand
AlternateDataSource | ElementID | RightMargin
AltHtml | EnableAutoCalculate | RightToLeft
AutoFit | EnableEvents | ScreenUpdating
BackColor | FgColor | Scroll
BackgroundColor | FileModifiedDate | ScrollAmount
BackgroundImage | FileUpdatedDate | ScrollDelay
BackgroundPositionX | FontFamily | SelectionType
BackgroundPositionY | FontSize | ShowDelButton
BackgroundRepeat | FontStyle | ShowFilterBySelectionButton
Behavior | FontVariant | ShowFirstButton
BGProperties | FontWeight | ShowLastButton
BorderColor | GridX | ShowNewButton
BorderStyle | GridY | ShowNextButton
BorderWidth | HasChartspaceLegend | ShowPrevButton
BottomMargin | HasChartspaceTitle | ShowSaveButton
BuildNumber | HasDetails | ShowSortAscendingButton
CanUndo | Height | ShowSortDescendingButton
Caption | Host | ShowToggleFilterButton
ChartLayout | Href | ShowUndoButton
ChartWrapCount | Hspace | Size
Checked | HTMLURL | Src
ChildLabel | Id | Start
ClassName | Indeterminate | Status
Code | IsExpanded | TabIndex
CodeBase | IsMap | TagName
CodeType | Lang | Target
Color | Left | TextAlign
CommandText | Length | Title
ConnectionString | LinkColor | Top
ConsumesRecordset | ListBoundField | TotalType
ControlSource | ListDisplayField | TrueSpeed
DataFormatAs | ListRowSource | Type
DataMember | Loop | UniqueTable
DataSourceType | Lowsrc | UseMap
Datatype | MajorVersion | UseRemoteProvider
DefaultChecked | MaxHeight | Value
DefaultValue | MaxWidth | Version
Dir | MemberExpand | ViewableRange
Direction | MinorVersion | Visibility
Disabled | MoveAfterReturn | VlinkColor
Display | MoveAfterReturnDirection | Vspace
DisplayColHeaders | Multiple | Width
DisplayExpandIndicator | NoShade | Zindex
DisplayFieldList | NoWrap |


DDE Functions and Statements

DDE Function

DDEExecute Statement

DDEInitiate Function

DDEPoke Statement

DDERequest Function

DDESend Function

DDETerminate Statement

DDETerminateAll Statement


Field Properties Reference

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

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

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


Image Control Properties

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

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

BackColor | OnDblClick (forms)
BackStyle | OnMouseDown (forms)
BorderColor | OnMouseMove (forms)
BorderStyle | OnMouseUp (forms)
BorderWidth | Picture
ControlTipText (forms) | PictureAlignment
ControlType | PictureTiling (forms)
DisplayWhen (forms) | PictureType
Height | ShortcutMenuBar
HelpContextID | SizeMode
HyperlinkAddress | SpecialEffect
HyperlinkSubAddress | Tag
InSelection (forms) | Top
Left | Visible
Name | Width
OnClick (forms) |


Label Control Properties

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

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

BackColor | InSelection (forms)
BackStyle | Left
BorderColor | LeftMargin
BorderStyle | LineSpacing
BorderWidth | Name
BottomMargin | OnClick (forms)
Caption | OnDblClick (forms)
ControlTipText (forms) | OnMouseDown (forms)
ControlType | OnMouseMove (forms)
DisplayWhen (forms) | OnMouseUp (forms)
FontItalic | RightMargin
FontName | ShortcutMenuBar
FontSize | SpecialEffect
FontUnderline | Tag
FontWeight | TextAlign
ForeColor | Top
Height | TopMargin
HelpContextID | Vertical
HyperlinkAddress | Visible
HyperlinkSubAddress | Width


Line Control Properties

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

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

BorderColor | LineSlant
BorderStyle | Name
BorderWidth | SpecialEffect
ControlType | Tag
DisplayWhen (forms) | Top
Height | Visible
InSelection (forms) | Width
Left |


List Box Control Properties

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

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

A–M

AddColon | Enabled (forms)
AfterUpdate (forms) | FontItalic
AutoLabel | FontName
BackColor | FontSize
BeforeUpdate (forms) | FontUnderline
BorderColor | FontWeight
BorderStyle | ForeColor
BorderWidth | Height
BoundColumn | HelpContextID (forms)
Column (forms) | InSelection (forms)
ColumnCount | ItemData
ColumnHeads | LabelAlign
ColumnWidths | LabelX
ControlSource | LabelY
ControlTipText (forms) | Left
ControlType | Locked (forms)
DefaultValue (forms) | MultiSelect
DisplayWhen (forms) |

N–Z

Name | RowSourceType
OnClick (forms) | ShortcutMenuBar
OnDblClick (forms) | SpecialEffect
OnEnter (forms) | StatusBarText (forms)
OnExit (forms) | TabIndex (forms)
OnGotFocus (forms) | TabStop (forms)
OnKeyDown (forms) | Tag
OnKeyPress (forms) | TextAlign
OnKeyUp (forms) | Top
OnLostFocus (forms) | ValidationRule (forms)
OnMouseDown (forms) | ValidationText (forms)
OnMouseMove (forms) | Visible
OnMouseUp (forms) | Width
RowSource |


Option Button Control Properties

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

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

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


Option Group Control Properties

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

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

AddColon Left
AfterUpdate (forms) | Locked (forms)
AutoLabel Name
BackColor | OnClick (forms)
BackStyle | OnDblClick (forms)
BeforeUpdate (forms) | OnEnter (forms)
BorderColor | OnExit (forms)
BorderStyle | OnMouseDown (forms)
BorderWidth | OnMouseMove (forms)
ControlSource | OnMouseUp (forms)
ControlTipText (forms) | ShortcutMenuBar
ControlType SpecialEffect
DefaultValue (forms) | StatusBarText (forms)
DisplayWhen (forms) | TabIndex (forms)
Enabled (forms) | TabStop (forms)
Height Tag
HelpContextID (forms) | Top
InSelection | ValidationRule (forms)
LabelAlign | ValidationText (forms)


Page Break Control Properties

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

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

ControlType Name
InSelection (forms) Tag


Query Properties Reference

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

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

Alias* | ODBCTimeout
Caption* | OrderBy
ColumnHeadings | OrderByOn
Description | OutputAllFields
DestConnectStr | RecordLocks
DestinationDB | RecordsetType
DestinationTable | ReturnsRecords
DisplayControl* | RunPermissions
FailOnError | Source*
Filter | SourceConnectStr
Format* | SourceDatabase
FrozenColumns | SubdatasheetExpanded
InputMask* | SubdatasheetHeight
LinkChildFields | SubdatasheetName
LinkMasterFields | TopValues
LogMessages | UniqueRecords
MaxRecords | UniqueValues
ODBCConnectStr | UseTransaction


Rectangle Control Properties

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

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

BackColor | OnClick (forms)
BackStyle | OnDblClick (forms)
BorderColor | OnMouseDown (forms)
BorderStyle | OnMouseMove (forms)
BorderWidth | OnMouseUp (forms)
ControlType | SpecialEffect
DisplayWhen (forms) | Tag
Height | Top
InSelection (forms) | Visible
Left | Width
Name |


Subform/Subreport Control Properties

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

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

AddColon | LinkChildFields
AutoLabel | LinkMasterFields
BorderColor | Locked (forms)
BorderStyle | Name
BorderWidth | OnEnter (forms)
CanGrow | OnExit (forms)
CanShrink | SourceObject
ControlType | SpecialEffect
DisplayWhen (forms) | StatusBarText (forms)
Enabled (forms) | TabIndex (forms)
Height | TabStop (forms)
InSelection (forms) | Tag
LabelAlign | Top
LabelX | Visible
LabelY | Width
Left |


Tab Control Properties

The following list identifies the properties you can set for a tab control.

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

BackStyle | OnKeyDown (forms)
ControlType | OnKeyPress (forms)
DisplayWhen | OnKeyUp (forms)
Enabled | OnMouseDown
FontItalic | OnMouseMove
FontName | OnMouseUp
FontSize | ShortcutMenuBar
FontUnderline | StatusBarText
FontWeight | Style
Height | TabFixedHeight
HelpContextID | TabFixedWidth
InSelection | TabIndex
Left | TabStop
MultiRow | Tag
Name | Top
OnChange | Visible
OnClick | Width
OnDblClick |


Table Properties Reference

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

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

Description | SubdatasheetExpanded
Filter | SubdatasheetHeight
LinkChildFields | SubdatasheetName
LinkMasterFields | ValidationRule
OrderBy | ValidationText


Text Box Control Properties

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

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

A–N

AddColon | FilterLookup
AfterUpdate (forms) | FontBold
AllowAutoCorrect | FontItalic
AutoLabel | FontName
AutoTab (forms) | FontSize
BackColor | FontUnderline
BackStyle | FontWeight
BeforeUpdate (forms) | ForeColor
BorderColor | Format
BorderStyle | Height
BorderWidth | HelpContextID (forms)
BottomMargin | InputMask
CanGrow | InSelection (forms)
CanShrink | IsHyperlink
ControlSource | LabelAlign
ControlTipText (forms) | LabelX
ControlType | LabelY
DecimalPlaces | Left
DefaultValue (forms) | LeftMargin
DisplayWhen (forms) | LineSpacing
Enabled (forms) | Locked (forms)
EnterKeyBehavior (forms) | Name

O–P

OnChange (forms) | ShortcutMenuBar
OnClick (forms) | SpecialEffect
OnDblClick (forms) | StatusBarText (forms)
OnEnter (forms) | TabIndex (forms)
OnExit (forms) | TabStop (forms)
OnGotFocus (forms) | Tag
OnKeyDown (forms) | TextAlign
OnKeyPress (forms) | Top
OnKeyUp (forms) | TopMargin
OnLostFocus (forms) | ValidationRule (forms)
OnMouseDown (forms) | ValidationText (forms)
OnMouseMove (forms) | Vertical
OnMouseUp (forms) | Visible
RightMargin | Width
ScrollBars (forms) |


Toggle Button Control Properties

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

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

AddColon | OnClick (forms)
AfterUpdate (forms) | OnDblClick (forms)
AutoLabel | OnEnter (forms)
BeforeUpdate (forms) | OnExit (forms)
Caption | OnGotFocus (forms)
ControlSource | OnKeyDown (forms)
ControlTipText (forms) | OnKeyPress (forms)
ControlType | OnKeyUp (forms)
DefaultValue (forms) | OnLostFocus (forms)
DisplayWhen (forms) | OnMouseDown (forms)
Enabled (forms) | OnMouseMove (forms)
FontItalic | OnMouseUp (forms)
FontName | Picture
FontSize | PictureType
FontUnderline | ShortcutMenuBar
FontWeight | StatusBarText (forms)
ForeColor | TabIndex (forms)
Height | TabStop (forms)
HelpContextID (forms) | Tag
InSelection (forms) | Top
LabelAlign | TripleState
LabelX | ValidationRule (forms)
LabelY | ValidationText (forms)
Left | Visible
Locked (forms) | Width
Name |


Unbound Object Frame Control Properties

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

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

AutoActivate (forms) | OnDblClick (forms)
BackColor | OnEnter (forms)
BackStyle | OnExit (forms)
BorderColor | OnGotFocus (forms)
BorderStyle | OnLostFocus (forms)
BorderWidth | OnMouseDown (forms)
Class | OnMouseMove (forms)
ColumnCount | OnMouseUp (forms)
ColumnHeads | OnUpdated (forms)
ControlTipText (forms) | RowSource
ControlType | RowSourceType
DisplayType | ShortcutMenuBar
DisplayWhen (forms) | SizeMode
Enabled (forms) | SourceDoc
Height | SourceItem
HelpContextID (forms) | SpecialEffect
InSelection (forms) | StatusBarText
Left | TabIndex (forms)
LinkChildFields | TabStop (forms)
LinkMasterFields | Tag
Locked (forms) | Top
Name | UpdateOptions
OLEClass | Verb
OLEType | Visible
OLETypeAllowed | Width
OnClick (forms) |


 Action Property

Action Property

You can use the Action property in Visual Basic to specify the operation to perform on an OLE object.

Setting

The Action property uses the following settings.

Constant | Description
acOLECreateEmbed (0) | Creates an embedded object. To use this setting, you must first set the control's OLETypeAllowed property to acOLEEmbedded or acOLEEither. Set the Class property to the type of OLE object you want to create. You can use the SourceDoc property to use an existing file as a template.
acOLECreateLink (1) | Creates a linked OLE object from the contents of a file. To use this setting, you must first set the control's OLETypeAllowed and SourceDoc properties. Set the OLETypeAllowed property to acOLELinked or acOLEEither. The SourceDoc property specifies the file used to create the OLE object. You can also set the control's SourceItem property (for example, to specify a row-and-column range if the object you're creating is a Microsoft Excel worksheet). When you create an OLE object by using this setting, the control displays a metafile graphic image of the file specified by the control's SourceDoc property. If you save the OLE object, only the link information, such as the name of the application that supplied the object and the name of the linked file, is saved because the control contains an image of the data but no source data.
acOLECopy (4) | Copies the object to the Clipboard. When you copy an OLE object to the Clipboard, all the data and link information associated with the object is placed on the Clipboard as well. You can copy both linked and embedded objects onto the Clipboard. Using this setting is equivalent to clicking Copy on the Edit menu.
acOLEPaste (5) | Pastes data from the Clipboard to the control. If the paste operation is successful, the control's OLEType property is set to acOLELinked or acOLEEmbedded. If the paste operation isn't successful, the OLEType property is set to acOLENone. Using the acOLEPaste setting is equivalent to clicking Paste on the Edit menu.
acOLEUpdate (6) | Retrieves the current data from the application that supplied the object and displays that data as a metafile graphic in the control.
acOLEActivate (7) | Opens an OLE object for an operation, such as editing. To use this setting, you must first set the control's Verb property. The Verb property specifies the operation to perform when the OLE object is activated.
acOLEClose (9) | Closes an OLE object and ends the connection with the application that supplied the object. This setting applies to embedded objects only. Using this setting is equivalent to clicking Close on the object's Control menu.
acOLEDelete (10) | Deletes the specified OLE object and frees the associated memory. This setting enables you to explicitly delete an OLE object. Objects are automatically deleted when a form is closed or when the object is updated to a new object. You can't use the Action property to delete a bound OLE object from its underlying table or query.
acOLEInsertObjDlg (14) | Displays the Insert Object dialog box. In Form view or Datasheet view, you display this dialog box to enable the user to create a new object or to link or embed an existing object. You can use the control's OLETypeAllowed property to determine the type of object the user can create (with the constant acOLELinked, acOLEEmbedded, or acOLEEither) by using this dialog box.
acOLEPasteSpecialDlg (15) | Displays the Paste Special dialog box. In Form view or Datasheet view, you display this dialog box to enable the user to paste an object from the Clipboard. The dialog box provides several options, including pasting either a linked or embedded object. You can use the control's OLETypeAllowed property to determine the type of object that can be pasted (with the constant acOLELinked, acOLEEmbedded, or acOLEEither) by using this dialog box.
acOLEFetchVerbs (17) | Updates the list of verbs an OLE object supports. To display the list of verbs, use the ObjectVerbs and ObjectVerbsCount properties.

You can set the Action property only 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.

Setting | Enabled = No | Locked = Yes
acOLECreateEmbed (0) | Not allowed | Not allowed
acOLECreateLink (1) | Not allowed | Not allowed
acOLECopy (4) | Allowed | Allowed
acOLEPaste (5) | Not allowed | Not allowed
acOLEUpdate (6) | Not allowed | Not allowed
acOLEActivate (7) | Allowed | Allowed
acOLEClose (9) | Not allowed | Allowed
acOLEDelete (10) | Not allowed | Not allowed
acOLEInsertObjDlg (14) | Not allowed | Not allowed
acOLEPasteSpecialDlg (15) | Not allowed | Not allowed
acOLEFetchVerbs (17) | Not allowed | Allowed


 ActiveControl Property

ActiveControl Property

You can use the ActiveControl property together with the Screen object to identify or refer to the control that has the focus.

Setting

This property setting contains 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 Control
Dim strControlName As String
Set ctlCurrentControl = Screen.ActiveControl
strControlName = 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.


 ActiveDatasheet Property

ActiveDatasheet Property

You can use the ActiveDatasheet property together with the Screen object to identify or refer to the datasheet that has the focus.

Setting

The ActiveDatasheet property setting contains the datasheet object that has the focus at run time.

This property is available 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


 ActiveForm Property

ActiveForm Property

You can use the ActiveForm property together with the Screen object to identify or refer to the form that has the focus.

Setting

This property setting contains 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 Form
Set frmCurrentForm = Screen.ActiveForm
MsgBox "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.


 ActiveReport Property

ActiveReport Property

You can use the ActiveReport property together with the Screen object to identify or refer to the report that has the focus.

Setting

This property setting contains 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

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 Report
Set rptCurrentReport = Screen.ActiveReport
MsgBox "Current report is " & rptCurrentReport.Name

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


 AddColon, AutoLabel Properties

AddColon, AutoLabel Properties

  • The AddColon property specifies whether a colon follows the text in labels for new controls.

  • The AutoLabel property specifies whether labels are automatically created and attached to new controls.

Setting

The AddColon property uses the following settings.

Setting | Description
Yes | A colon follows the text in labels for new controls.
No | A colon doesn't follow the text in labels for new controls.

The AutoLabel property uses the following settings.

Setting | Description
Yes | A label is attached to new controls.
No | A label isn't attached to new controls.

You can set these properties only 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 using a Microsoft Access wizard, see Specify a new template for forms and reports.


 Address Property

Address Property

You can use the Address property to specify or determine the path to an object, document, Web page or other destination for a Hyperlink object associated with a command button, image control, or label control.

Setting

The Address property is a string expression representing the HyperlinkAddress property's path to a file (UNC path) or Web page (URL).

The Address property is only available by using Visual Basic. When you set the Address property, you automatically specify the HyperlinkAddress property for the control associated with the hyperlink.

Remarks

For more information about hyperlink addresses and their format, see the HyperlinkAddress and HyperlinkSubAddress property topics.


 Alias Property

Alias Property

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.


AllDataAccessPages Property

You can use the AllDataAccessPages property to reference the AllDataAccessPages collection and its related properties.

Setting

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


AllDatabaseDiagrams Property

You can use the AllDatabaseDiagrams property to reference the AllDatabaseDiagrams collection and its related properties.

Setting

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


AllForms Property

You can use the AllForms property to reference the AllForms collection and its related properties.

Setting

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


AllMacros Property

You can use the AllMacros property to reference the AllMacros collection and its related properties.

Setting

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


AllModules Property

You can use the AllModules property to reference the AllModules collection and its related properties.

Setting

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


 AllowAdditions Property

AllowAdditions Property

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.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) The user can add new records.
No | False (0) | The user can't add new records.

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:

  • AllowEdits — Yes

  • AllowDeletions — Yes

  • AllowAdditions — Yes

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


 AllowAutoCorrect Property

AllowAutoCorrect Property

You can use the AllowAutoCorrect property to specify whether a text box or a combo box control will automatically correct entries made by the user.

Setting

The AllowAutoCorrect property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) Entries are automatically corrected according to the settings in the AutoCorrect dialog box.
No | False (0) | Entries aren't corrected.

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.


 AllowBreakIntoCode Property

AllowBreakIntoCode Property

You can use the AllowBreakIntoCode property to specify whether or not the user can view Visual Basic code after a run-time error occurs in a module.

Setting

The AllowBreakIntoCode property uses the following settings.

Setting | Description
True (–1) | Enable the Debug button on the dialog box that appears when a run-time error occurs.
False (0) | Disable the Debug button.

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 in the following ways:

  • In a Microsoft Access database (.mdb), you can add it by using the CreateProperty method and append it to the Properties collection of the Database object.

  • In a Microsoft Access project (.adp), you can add it to the AccessObjectProperties collection of the CurrentProject object by using the Add method.

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.


 AllowBuiltInToolbars Property

AllowBuiltInToolbars Property

You can use the AllowBuiltInToolbars property to specify whether or not the user can display Microsoft Access built-in toolbars. For example, you can use the AllowBuiltInToolbars property to prevent a user from seeing a Microsoft Access built-in toolbar within a database application.

Setting

The AllowBuiltInToolbars property 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.

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 in the following ways:

  • In a Microsoft Access database (.mdb), you can add it by using the CreateProperty method and append it to the Properties collection of the Database object.

  • In a Microsoft Access project (.adp), you can add it to the AccessObjectProperties collection of the CurrentProject object by using the Add method.

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.


 AllowBypassKey Property

AllowBypassKey Property

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

The AllowBypassKey property uses the following settings.

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.

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 in the following ways:

  • In a Microsoft Access database (.mdb), you can add it by using the CreateProperty method and append it to the Properties collection of the Database object.

  • In a Microsoft Access project (.adp), you can add it to the AccessObjectProperties collection of the CurrentProject object by using the Add method.

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.


 AllowContextMenu Property

AllowContextMenu Property

You can use the AllowContextMenu property to specify or determine whether the Snapshot Viewer control pop-up menu appears when you right-click the control or when you press the context menu on a Microsoft Windows keyboard.

Setting

The AllowContextMenu property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) The control's pop-up menu is displayed when you right-click the control.
No | False (0) | The control's right-click menu is not displayed.

You can set the AllowContextMenu property by using the control's property sheet or Visual Basic.

Remarks

When this property is set to Yes, the pop-up menu that is displayed when you right-click a Snapshot Viewer control contains commands to specify the control's Zoom property setting or navigate between pages in the snapshot. The pop-up menu also includes choices to print one or more pages of the current snapshot.

When this property is set to No, the pop-up menu will not appear when you right-click the control. You can still toggle between the Fill and Full Zoom property settings by clicking directly on the snapshot displayed in the control. You can navigate to other pages in the snapshot or print the snapshot by using the buttons at the bottom of the snapshot control. In addition, you can print a snapshot by using the Print button to the right of the navigation controls.

The Snapshot Viewer control does not support the ShortcutMenuBar property.


 AllowDeletions Property

AllowDeletions Property

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

Setting

The AllowDeletions property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) The user can delete records.
No | False (0) | The user can't delete records.

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:

  • AllowEdits — Yes

  • AllowDeletions — Yes

  • AllowAdditions — Yes

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


 AllowDesignChanges Property

AllowDesignChanges Property

You can use the AllowDesignChanges property to specify or determine if design changes can be made to a form in all views or Design view only.

Setting

The AllowDesignChanges property uses the following settings.

Setting | Visual Basic | Description
All Views | True (–1) | (Default) Design changes can be made in all form views.
Design View Only | False (0) | Design changes can be made in Design view only.

The AllowDesignChanges property can be set by using the form's property sheet or Visual Basic.


 AllowEdits Property

AllowEdits Property

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.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) The user can edit saved records.
No | False (0) | The user can't edit saved records.

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:

  • AllowEdits — Yes

  • AllowDeletions — Yes

  • AllowAdditions — Yes

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


 AllowFilters Property

AllowFilters Property

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

Settings

The AllowFilters property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) Records can be filtered.
No | False (0) | Records can't be filtered.

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.

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:

  • The Filter, Apply Filter/Sort, and Remove Filter/Sort commands.

  • The Filter By Form, Apply Filter/Sort, Remove Filter/Sort, Server Filter By Form, and Apply Server Filter commands on the form's shortcut menu.

  • The corresponding Filter By Selection [image] , Filter By Form [image] , Apply Filter / Remove Filter Filter object , and ServerFilterByForm [image] buttons.

Note Setting the AllowFilters property to No does not affect the Filter, FilterOn, ServerFilter, or ServerFilterByForm 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.

Actions Methods


 AllowFullMenus Property

AllowFullMenus Property

You can use the AllowFullMenus property to specify whether or not full Microsoft Access built-in menus will be available when the application database opens. For example, you can use the AllowFullMenus property to disable menu items that give users the ability to modify table, form, query, or report structures.

Setting

The AllowFullMenus property uses the following settings.

Setting | Description
True (–1) | Display the full built-in menus at startup.
False (0) | Don't display full built-in menus at startup.

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 in the following ways:

  • In a Microsoft Access database (.mdb), you can add it by using the CreateProperty method and append it to the Properties collection of the Database object.

  • In a Microsoft Access project (.adp), you can add it to the AccessObjectProperties collection of the CurrentProject object by using the Add method.

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.


 AllowShortcutMenus Property

AllowShortcutMenus Property

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.

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.

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 in the following ways:

  • In a Microsoft Access database (.mdb), you can add it by using the CreateProperty method and append it to the Properties collection of the Database object.

  • In a Microsoft Access project (.adp), you can add it to the AccessObjectProperties collection of the CurrentProject object by using the Add method.

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.


 AllowSpecialKeys Property

AllowSpecialKeys Property

You can use the AllowSpecialKeys property to specify whether or not special key sequences (ALT+F1 (F11), CTRL+F11, CTRL+BREAK, and CTRL+G) are disabled or enabled. For example, you can use the AllowSpecialKeys property to prevent a user from displaying the Database window by pressing F11, entering break mode within a Visual Basic module by pressing CTRL+BREAK, or displaying the Immediate window by pressing CTRL+G.

Setting

The AllowSpecialKeys property uses the following settings.

Setting | Description
True (–1) | Enable the special key sequences.
False (0) | Disable the special key sequences.

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. In a Microsoft Access database (.mdb), yYou 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 in the following ways:

  • In a Microsoft Access database (.mdb), you can add it by using the CreateProperty method and append it to the Properties collection of the Database object.

  • In a Microsoft Access project (.adp), you can add it to the AccessObjectProperties collection of the CurrentProject object by using the Add method.

Remarks

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

The AllowSpecialKeys property affects the following key sequences.

Key sequences | Effect
ALT+F1 (F11) | Bring the Database window to the front.
CTRL+G | Display the Immediate 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 Code window.

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.


 AllowToolbarChanges Property

AllowToolbarChanges Property

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

The AllowToolbarChanges property uses the following settings.

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.

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 in the following ways:

  • In a Microsoft Access database (.mdb), you can add it by using the CreateProperty method and append it to the Properties collection of the Database object.

  • In a Microsoft Access project (.adp), you can add it to the AccessObjectProperties collection of the CurrentProject object by using the Add method.

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.


 AllowZeroLength Property (Microsoft Access)

AllowZeroLength Property

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.

Setting | Visual Basic | Description
Yes | True (–1) | A zero-length string is a valid entry.
No | False (0) | (Default) A zero-length string is an invalid entry.

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 or the ADO Column.Properties("Set OLEDB:Allow Zero Length") 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.

AllowZeroLength | Required | User's action | Value stored
No | No | Presses ENTER Presses SPACEBAR Enters a zero-length string | Null Null (not allowed)
Yes | No | Presses ENTER Presses SPACEBAR Enters a zero-length string | Null Null Zero-length string
No | Yes | Presses ENTER Presses SPACEBAR Enters a zero-length string | (not allowed) (not allowed) (not allowed)
Yes | Yes | Presses ENTER Presses SPACEBAR Enters a zero-length string | (not allowed) Zero-length string Zero-length string

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.


AllQueries Property

You can use the AllQueries property to reference the AllQueries collection and its related properties.

Setting

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


AllReports Property

You can use the AllReports property to reference the AllReports collection and its related properties.

Setting

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


AllStoredProcedures Property

You can use the AllStoredProcedures property to reference the AllStoredProcedures collection and its related properties.

Setting

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


AllTables Property

You can use the AllTables property to reference the AllTables collection and its related properties.

Setting

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


AllViews Property

You can use the AllViews property to reference the AllViews collection and its related properties.

Setting

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


AlwaysSaveInDefaultEncoding Property

You can use the AlwaysSaveInDefaultEncoding property to specify or determine whether the Web browser opens a data access page with its default or original encoding (character set).

Setting

The AlwaysSaveInDefaultEncoding property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | Use the default encoding specified by the Encoding when saving a data access page.
No | False (0) | (Default) Use the original encoding of the data access page.

The AlwaysSaveInDefaultEncoding property is available only by using Visual Basic.

Remarks

The Encoding property can be used to set the default encoding.


 AnswerWizard Property (Microsoft Access)

AnswerWizard Property

You can use the AnswerWizard property to return a reference to the current AnswerWizard object and its related properties.

Setting

[application.]AnswerWizard[.method or property]

The AnswerWizard property uses the following settings.

Setting | Description
application | Optional. The Application object.
AnswerWizard | Required. When used without specifying a method or property, returns the AnswerWizard object.
method or property | A method or property of the AnswerWizard object.

The AnswerWizard property is available only by using Visual Basic.

Remarks

Once you establish a reference to the AnswerWizard object, you can access all the properties and methods of the object. You can set a reference to the AnswerWizard object by clicking References on the Tools menu while in module Design view. Then set a reference to the Microsoft Office 9.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 9.0 Object Library constant to set an AnswerWizard object's property or as an argument to an AnswerWizard object's method.


 AppIcon Property

AppIcon Property

You can use the AppIcon property to specify the name of the bitmap (.bmp) or icon (.ico) file that contains the application's icon. For example, you can use the AppIcon property to specify a .bmp file that contains 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.

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 in the following ways:

  • In a Microsoft Access database (.mdb), you can add it by using the CreateProperty method and append it to the Properties collection of the Database object.

  • In a Microsoft Access project (.adp), you can add it to the AccessObjectProperties collection of the CurrentProject object by using the Add method.

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.


Application Property (Microsoft Access)

Application Property

You can use the Application property in Visual Basic to access the active Microsoft Access Application object and its related properties.

Setting

The Application property is set by Microsoft Access and is read-only 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


 AppTitle Property

AppTitle Property

You can use the AppTitle property to specify the text that appears in the application database's title bar. For example, you can use the AppTitle property to specify that the string "Inventory Control" appear in the title bar of your Inventory Control database application.

Setting

The AppTitle property is a string expression containing the text to appear in the title bar.

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 in the following ways:

  • In a Microsoft Access database (.mdb), you can add it by using the CreateProperty method and append it to the Properties collection of the Database object.

  • In a Microsoft Access project (.adp), you can add it to the AccessObjectProperties collection of the CurrentProject object by using the Add method.

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.


 Assistant Property

Assistant Property

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

Setting

[application.]Assistant[.method or property]

The Assistant property uses the following settings.

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.

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 9.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 9.0 Object Library constant to set an Assistant object's property or as an argument to an Assistant object's method.


 AutoActivate Property

AutoActivate Property

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

Setting

The AutoActivate property uses the following settings.

Setting | Constant | Description
Manual | acOLEActivateManual (0) | 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.
GetFocus | acOLEActivateGetFocus (1) | (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.
Double-Click | acOLEActivateDoubleClick (2) | (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.

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


 AutoCenter Property

AutoCenter Property

You can use the AutoCenter property to specify whether a form will be centered automatically in the application window when the form is opened.

Setting

The AutoCenter property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The form will be centered automatically on opening.
No | False (0) | (Default) The form's upper-left corner will be in the same location as when the form was last saved.

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


 AutoExpand Property

AutoExpand Property

You can use the AutoExpand property to specify whether Microsoft Access automatically fills the text box portion of a combo box with a value 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.

Setting | Visual Basic | Description
Yes | True (–1) | (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.
No | False (0) | You must select a value from the list or type the entire value.

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

Remarks

When you enter characters in the text box portion of a combo box, Microsoft Access searches the values in the list to find those that match the characters you have typed. If the AutoExpand property is set to Yes, Microsoft Access automatically displays the first underlying value that matches the characters entered so far.

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.


 AutoRepeat Property

AutoRepeat Property

You can use the AutoRepeat property to specify whether an event procedure or macro runs repeatedly while a command button on a form remains pressed in.

Setting

The AutoRepeat property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The macro or event procedure in the Click event runs repeatedly while the command button remains pressed in.
No | False (0) | (Default) The macro or event procedure runs once.

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.


 AutoResize Property

AutoResize Property

You can use the AutoResize property to specify whether a Form window opens automatically sized to display complete records.

Setting

The AutoResize property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) The Form window is automatically sized to display a complete record.
No | False (0) | When opened, the Form window has the last saved size. To save a Form window's size, open the form, size the window, save the form by clicking Save on the File menu, and close the form. When you next open the form, it will be the saved window size.

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.


 AutoTab Property

AutoTab Property

You can use the AutoTab property to specify whether an automatic tab occurs when the last character permitted by a text box control's input mask is entered. An automatic tab moves the focus to the next control in the form's tab order.

Setting

The AutoTab property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | Generates a tab when the last allowable character in a text box is entered.
No | False (0) | (Default) Doesn't generate a tab when the last allowable character in a text box is entered.

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. After you have entered the maximum number of characters, 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.


 BackColor Property

BackColor Property

You can use the BackColor property to specify the color for the interior of a control or section.

Setting

The BackColor property contains a numeric expression that corresponds to the color used to fill a control's or section's interior.

You can use the Color Builder to set this property by clicking the Build button [image] to the right of the property box in the property sheet. Using the Color Builder enables you to define custom back colors for controls or sections.

You can also set this property by using Fill/Back Color [image] 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 Table objects you can set this property using Fill/Back Color [image] 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.


 BackStyle Property

BackStyle Property

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

Setting

The BackStyle property uses the following settings.

Setting | Visual Basic | Description
Normal | 1 | (Default for all controls except option group) The control has its interior color set by the BackColor property.
Transparent | 0 | (Default for option group) The control is transparent. The color of the form or report behind the control is visible.

You can set this property by using Fill/Back Color [image] 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.


 BaseConnectionString Property

BaseConnectionString Property

You can use the BaseConnectionString property returns the base connection string for the CurrentProject or CodeProject object.

Setting

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

Remarks

The BaseConnectionString property returns the connection string that was set through the OpenConnection method or by clicking Connection on the File menu. When making a connection, Microsoft Access project modifies the BaseConnectionString property for use with the ADO environment.


 Bookmark Property (Microsoft Access)

Bookmark Property

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 ADO Bookmark or 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 ADO Seek or DAO 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 ADO Find method or DAO Find methods 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.

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


 BorderColor Property

BorderColor Property

You can use the BorderColor property to specify the color of a control's border.

Setting

The BorderColor property setting is a numeric expression that corresponds to the color you want to use for a control's border.

You can use the Color Builder to set this property by clicking the Build button [image] 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 Line/Border Color [image] on the Formatting (Form/Report) toolbar, 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 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.


 BorderStyle Property

BorderStyle Property

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

  • 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 | Visual Basic | Description
None | 0 | The form has no border or related border elements. The form isn't resizable.
Thin | 1 | 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.)
Sizable | 2 | (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.
Dialog | 3 | 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.)

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.

Setting | Visual Basic | Description
Transparent | 0 | (Default only for label, chart, and subreport) Transparent
Solid | 1 | (Default) Solid line
Dashes | 2 | Dashed line
Short dashes | 3 | Dashed line with short dashes
Dots | 4 | Dotted line
Sparse dots | 5 | Dotted line with dots spaced far apart
Dash dot | 6 | Line with a dash-dot combination
Dash dot dot | 7 | Line with a dash-dot-dot combination
Double solid | 8 | Double solid lines

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

  • If the BorderStyle property is set to None or Dialog, the form doesn't have Maximize or Minimize buttons, regardless of its MinMaxButtons property setting.

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

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


 BorderWidth Property

BorderWidth Property

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

Setting

The BorderWidth property uses the following settings.

Setting | Visual Basic | Description
Hairline | 0 | (Default) The narrowest border possible on your system.
1 pt to 6 pt | 1 to 6 | The width as indicated in points.

You can set this property by using Line/Border Width [image] 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.


 LeftMargin, TopMargin, RightMargin, BottomMargin Properties

LeftMargin, TopMargin, RightMargin, BottomMargin Properties

You can use the LeftMargin, TopMargin, RightMargin, and BottomMargin property to specify or determine the location of information displayed within a label or text box control. For example, you might want display information in a text box control starting 0.25 inches from the left and top margins.

Setting

A control's displayed information location is the distance measured from the control's left, top, right, or bottom border to the left, top, right, or bottom edge of the displayed information. Setting the LeftMargin or TopMargin property to 0 places the displayed information's edge at the very left or top of the 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, 3 cm or 2 in).

In Visual Basic, use a numeric expression to set the value of this property. Values are expressed in twips.

You can set these properties by using the property sheet, a macro, or Visual Basic.


 BoundColumn Property

BoundColumn Property

When you make a selection from a list box or combo box, the BoundColumn property tells Microsoft Access which column's values to use as the value of the control. If the control is bound to a field, the value in the column specified by the BoundColumn property is stored in the field named in the ControlSource property.

Setting

The BoundColumn property uses the following settings.

Setting | Description
0 | The ListIndex property value, rather than the column value, is stored in the current record. The ListIndex property value of the first row is 0, the second row is 1, and so on. Microsoft Access sets the ListIndex property when an item is selected from a list box or the list box portion of a combo box. Setting the BoundColumn property to 0 and using the ListIndex property value of the control might be useful if, for example, you are only interested in storing a sequence of numbers.
1 or greater | (Default 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.

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


 BuiltIn Property (Microsoft Access)

BuiltIn Property

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.

Remarks

The default references in Microsoft Access include the Microsoft Access 9.0 object library, the Visual Basic For Applications library, OLE Automation library, and Microsoft ActiveX Data Objects 2.0 library.


 Callback Property

Callback Property

You set the Callback property when you're working with a modeless balloon. A modeless balloon is one that allows the user to switch back to the application in which they're working without first closing the balloon. A modeless balloon may be useful if you're creating help that the user will want to leave open while performing several steps in the application. To make a balloon modeless, set the Mode property of the Balloon object to msoModeModeless.

The Callback property specifies a function or a macro to run when the user clicks a button on a balloon. If you write a function to be called by the Callback property, you can use that function to determine which button was clicked.

You set the Callback property to the name of a function or macro. For example, the following line of code sets the Callback property:

Assistant.NewBalloon.Callback = "EvaluateCheckboxes"

Note that you must set the Callback property to the name of a Function procedure; you can't set it to the name of a Sub procedure. The Function procedure must be public.


 Cancel Property

Cancel Property

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

Setting

The Cancel property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The command button is the Cancel button.
No | False (0) | (Default) The command button isn't the Cancel button.

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.


 CanGrow, CanShrink Properties

CanGrow, CanShrink Properties

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

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

  • 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

The CanGrow property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The section or control grows vertically so that all data it contains can be printed or previewed.
No | False (0) | (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.

The CanShrink property uses the following settings.

Setting | Visual Basic | Description
Yes | True | The section or control shrinks vertically so that the data it contains can be printed or previewed without leaving blank lines.
No | False | (Default) The section or control doesn't shrink.

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

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

  • Overlapping controls can't grow or shrink.

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


 Caption Property

Caption Property

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

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

  • Form captions specify the text that appears in the title bar in Form view.

  • Report captions specify the title of the report in Print Preview.

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

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.


CheckIfOfficeIsHTMLEditor Property

You can use the CheckIfOfficeIsHTMLEditor property to specify or determine if the default system HTML editor is used when editing a Web page.

Setting

The CheckIfOfficeIsHTMLEditor property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) Check to see whether an Office application is the default HTML editor when starting Microsoft Access.
No | False (0) | Check is not performed..

The CheckIfOfficeIsHTMLEditor property is available only by using Visual Basic.

Remarks

The CheckIfOfficeIsHTMLEditor property is used only if the Web browser you are using supports HTML editing and HTML editors.

To use a different HTML editor, you must set this property to False and then register the editor as the default system HTML editor.


 Class Property

Class Property

You can use the Class property to specify or determine the class name of an embedded OLE object.

Setting

The Class property setting is a string expression 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.


 CloseButton Property

CloseButton Property

You can use the CloseButton property to specify whether the Close button [image] on a form is enabled.

Setting

The CloseButton property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) The Close button is enabled.
No | False (0) | The Close button is disabled and the Close command isn't available on the Control menu.

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.


 CodeContextObject Property

CodeContextObject Property

You can use the CodeContextObject property to determine the object in which a macro or Visual Basic code is executing.

Setting

The CodeContextObject property is set by Microsoft Access and is read-only in all views.

Remarks

The ActiveControl, ActiveDataAccessPage, ActiveDatasheet, 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 or Visual Basic code is currently running, for example, when Visual Basic code runs in the Timer event on a hidden form.


CodeData Property

You can use the CodeData property to access the CodeData object and its related collections.

Setting

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

Remarks

Use the CodeData property to refer to one of the following code database collections together with one of its properties or methods.

AllTables | AllQueries
AllViews | AllStoredProcedures
AllDatabaseDiagrams |


CodeProject Property

You can use the CodeProject property to access the CodeProject object and its related collections, properties, and methods.

Setting

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

Remarks

Use the CodeProject property to refer to one of the following code database collections together with one of its properties or methods.


Collection Property (Microsoft Access)

Collection Property

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.


 Column Property

Column Property

You can use the Column property to refer to a specific column, or column and row combination, in a multiple-column combo box or list box. Use 0 to refer to the first column, 1 to refer to the second column, and so on. Use 0 to refer to the first row, 1 to refer to the second row, and so on. For example, in a list box containing a column of customer IDs and a column of customer names, you could refer to the customer name in the second column and fifth row as:

Forms!Contacts!Customers.Column(1, 4)

Setting

control.Column(column, row)

The Column property uses the following settings.

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.

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.


 ColumnCount Property

ColumnCount Property

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.

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.


 ColumnHeadings Property

ColumnHeadings Property

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.
"Mexico", "Canada", "USA" | Displays column headings for each country.

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.


 ColumnHeads Property

ColumnHeads Property

You can use the ColumnHeads property to display a single row of column headings for list boxes, combo boxes, and OLE objects that accept column headings. You can also use this property to create a label for each entry in a chart 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.

Setting | Visual Basic | Description
Yes | True (–1) | 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.
No | False (0) | (Default) Column headings are not enabled.

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.

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.


 ColumnHidden Property

ColumnHidden Property

You can use the ColumnHidden property to show or hide a specified column in Datasheet view. For example, you might want to hide a CustomerAddress field that's too wide so you can view the CustomerName and PhoneNumber fields.

Note The ColumnHidden property applies to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

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 in a Microsoft Access database (.mdb) by using a Long Integer value in Visual Basic to specify the following settings.

Setting | Description
True (–1) | The column is hidden.
False (0) | (Default) The column is visible.

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

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.


 ColumnOrder Property

ColumnOrder Property

You can use the ColumnOrder property to specify the order of the columns in Datasheet view.

Note The ColumnOrder property applies to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

You can set this property by selecting a column in Datasheet view and dragging it to a new position.

You can also set this property in a Microsoft Access database (.mdb) 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 column's Properties collection. For details on using the Properties collection, see Properties.

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.


 ColumnWidth Property

ColumnWidth Property

You can use the ColumnWidth property to specify the width of a column in Datasheet view.

Note The ColumnWidth property applies to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

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

Setting | Description
0 | Hides the column.
–1 | (Default) Sizes the column to the default width.

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.


 ColumnWidths Property

ColumnWidths Property

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.

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

Setting | Description
1.5 in;0;2.5 in | The first column is 1.5 inches, the second column is hidden, and the third column is 2.5 inches.
2 in;;2 in | The first column is 2 inches, the second column is 1 inch (default), and the third column is 2 inches. Because only half of the third column is visible, a horizontal scroll bar appears.
(Blank) | The three columns are the same width (1.33 inches).

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


 COMAddIns Property

COMAddIns Property

You can use the COMAddIns property to return a reference to the current COMAddIns collection object and its related properties.

Setting

[application.]COMAddIns[.method or property]

The COMAddIns property uses the following settings.

Setting | Description
application | The Application object.
COMAddIns | Required. When used without specifying a method or property, returns the COMAddIns collection object.
method or property | A method or property of the COMAddIns collection object.

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

Remarks

The COMAddIns collection object is the collection of all currently registered COM add-ins of 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 COMAddIns collection's Count property.

Once you establish a reference to the COMAddIns collection object, you can access all the properties and methods of the object. You can set a reference to the COMAddIns collection object by clicking References on the Tools menu while in module Design view. Then set a reference to the Microsoft Office 9.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 9.0 Object Library constant to set a COMAddIns collection object's property or as an argument to a COMAddIns collection object's method.


 CommandBars Property (Microsoft Access)

CommandBars Property

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.

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 is the default property for the CommandBars collection object.

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 9.0 Object Library in the References dialog box by selecting the appropriate check box.


 Connection Property

Connection Property

You can use the Connection property to return a reference to the current ActiveX Data Objects (ADO) Connection object and its related properties.

Setting

[object.]Connection[.method or property]

The Connection property uses the following settings.

Setting | Description
object | The CurrentProject or CodeProject object.
Connection | Required. When used without specifying a method or property, returns the Connection object's ConnectionString property.
method or property | A method or property of the Connection object.

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

Remarks

Use the Connection property of the CurrentProject object to refer to the Connection object of the current Microsoft Access project (.adp) or Access database (.mdb) object. Use the Connection property of the CodeProject object to refer to the Connection object of the Access project or Access database code database object. You can use the Connection property to call methods on the Connection object such as BeginTrans and CommitTrans.

Notes The Connection property actually returns a reference to a copy of the ActiveX Data Object (ADO) connection for the active database. Thus, applying the Close method or in anyway attempting to alter the connection through the Connection object’s methods or properties will have no affect on the actual connection object used by Microsoft Access to hold a live connection to the current database. Since the Connection property is the main Shape provider connection, the following information is necessary when using this property.

  1. MSDataShape uses Recordset.CursorLocation = adUseClient. Do not set CursorLocation prior to assigning a recordset to CurrentProject.Connect.

  2. MSDataShape uses Recordset.CursorType = adOpenStatic. Do not set CursorType prior to assinging a recordset to CurrentProject.Connection.

  3. MSDataShape accepts Recordset.LockType = adLockOptimistic, adLockBatchOptimistic, or adLockReadOnly (default). If set to adLockPessimistic, it is changed to adLockOptimistic.

  4. The shape connection does not support the all ADOX operation, specifically the Columns.Properties collection is not supported.

  5. In order to ensure that a shape connection will work correctly, the Command.CommandType must be set to adCmdTable.


 ConnectionString Property

ConnectionString Property

You can use the ConnectionString property returns the base connection string for the DataAccessPage object.

Setting

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

Remarks

The ConnectionString property returns the connection string that was set through the OpenConnection method or by clicking Connection on the File menu. When making a connection, Microsoft Access project modifies the ConnectionString property for use with the ADO environment. The Microsoft Office Data Source Control (MSODSC) likewise modifies the ConnectionString.


 ControlBox Property

ControlBox Property

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.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) The form has a Control menu in Form view and Datasheet view.
No | False (0) | The form doesn't have a Control menu in Form view and Datasheet view.

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:

  • Open the form in Form view from the Database window.

  • Open the form from a macro.

  • Open the form from Visual Basic.

  • Open the form in Datasheet view.

  • Switch to Form view or Datasheet view from Design view.


 Controls Property (Form, SubForm, Report Object)

Controls Property (Form, SubForm, Report Object)

You can use the Controls property to reference the Controls collection of a form, subform, report or section.

Setting

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

Remarks

Use the Controls property to refer to one of the controls on a form, subform, report, or section, within another control, or attached to another control. For example, the first code syntax would return the number of controls located on Form1. The second would reference the name of a property within a control.

Forms("Form1").Controls.Count

Forms("Form1").Controls("Textbox1").Properties(5).Name


 ControlSource Property

ControlSource Property

You can use the ControlSource property to specify what data appears in a control. You can display and edit data bound to a field in a table, query, or SQL statement. You can also display the result of an expression. For a report group level, the ControlSource property determines the field or expression to group on.

Note The ControlSource property doesn't apply to check box, option button, or toggle button controls in an option group. It applies only to the option group itself.

For reports, the ControlSource property applies only to report group levels.

Setting

The ControlSource property uses 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.

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.

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


 ControlTipText Property

ControlTipText Property

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.

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.


 ControlType Property

ControlType Property

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
acBoundObjectFrame | Bound object frame
acCheckBox | Check box
acComboBox | Combo box
acCommandButton | Command button
acCustomControl | ActiveX (custom) control
acImage | Image
acLabel | Label
acLine | Line
acListBox | List box
acObjectFrame | Unbound object frame or chart
acOptionButton | Option button
acOptionGroup | Option group
acPage | Page
acPageBreak | Page break
acRectangle | Rectangle
acSubform | Subform/subreport
acTabCtl | Tab
acTextBox | Text box
acToggleButton | Toggle button

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


 Count Property (Microsoft Access)

Count Property

You can use the Count property to determine the number of items in a specified collection.

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.

Remarks

For example, if you want to determine the number of forms currently open or exisiting on the database, you would use the following code strings:

'Determine the number of open forms.

forms.count

'Determine the number of forms (open or closed)
'in the current database.

currentproject.allforms.count


 CountOfDeclarationLines Property

CountOfDeclarationLines Property

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.

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.


 CountOfLines Property

CountOfLines Property

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.


CurrentData Property

You can use the CurrentData property to access the CurrentData object and its related collections.

Setting

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

Remarks

Use the CurrentData property to refer to one of the following current database collections together with one of its properties or methods.

AllTables | AllQueries
AllViews | AllStoredProcedures
AllDatabaseDiagrams |


 CurrentObjectType, CurrentObjectName Properties

CurrentObjectType, CurrentObjectName Properties

You can use the CurrentObjectType and CurrentObjectName properties together with the Application object to determine the type of the active database object (table, query, form, report, macro, module, data access page, server view, database diagram, or stored procedure) 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.

Setting | Description
acTable (0) | The active object is a table.
acQuery (1) | The active object is a query.
acForm (2) | The active object is a form.
acReport (3) | The active object is a report.
acMacro (4) | The active object is a macro.
acModule (5) | The active object is a module.
acDataAccessPage (6) | The active object is a data access page.
acServerView (7) | The active object is a server view.
acDiagram (8) | The active object is a database diagram.
acStoredProcedure (9) | The active object is a stored procedure.

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:

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

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

  • If the active object is the Database window, the CurrentObjectType and CurrentObjectName properties return the item selected in the Database window.

  • If no object is selected, the CurrentObjectType property returns True (–1), and the CurrentObjectName property returns a zero-length string (" ").

  • If the current state is ambiguous (the active object isn't a table, query, form, report, macro, or module) — 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 method to determine the active object and its state (for example, if the object is open, new, or has been changed but not saved).


 CurrentPage Property

CurrentPage Property

You can use the CurrentPage property to specify or determine the page number of the page displayed in the Snapshot Viewer control.

Setting

The CurrentPage property setting is a Long value representing a page number in a snapshot.

This property is available only by using Visual Basic..

Remarks

If you set this property to an invalid page number, load an invalid file type, or try to access it while the ReadyState property is less than 4, then an error will occur.


CurrentProject Property

You can use the CurrentProject property to access the CurrentProject object and its related collections, properties, and methods.

Setting

The CurrentProject property setting contains a reference to the CurrentProject for the current code database.

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

Remarks

Use the CurrentProject property to refer to one of the following current database collections together with one of its properties or methods.


 CurrentRecord Property

CurrentRecord Property

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.


 CurrentSectionLeft, CurrentSectionTop Properties

CurrentSectionLeft, CurrentSectionTop Properties

You can use these properties to determine the distance in twips from the top edge and left side of the current section to the top edge and left side of the form.

Setting

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

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


 CurrentView Property

CurrentView Property

You can use the CurrentView property to determine how a form or data access page 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.

Setting | Form Displayed In: | Data Access Page Displayed In:
0 | Design view | Design view
1 | Form view | Page view
2 | Datasheet view | Not applicable

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.


 CurrentX, CurrentY Properties

CurrentX, CurrentY Properties

You can use the CurrentX and CurrentY properties to specify the horizontal and vertical coordinates for the starting position of the next printing and drawing method on a report. For example, you can use these properties to determine where the center point of a circle is drawn on a report section.

Setting

  • The CurrentX property specifies a Single value used in a numeric expression to set the horizontal coordinate of the next printing drawing method.

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

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.


 Cycle Property

Cycle Property

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.

Setting | Visual Basic | Description
All Records | 0 | (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.
Current Record | 1 | 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.
Current Page | 2 | 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.

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


DataAccessPages Property

You can use the DataAccessPages property to reference the DataAccessPages collection and its related properties.

Setting

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


 Database Properties

Database Properties

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 in a Microsoft Access database (.mdb), by using Visual Basic.

Note The Database properties of a Microsoft Access project (.adp) are not available 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, click Specifics in the Documents collection topic.

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.

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 | 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. In Microsoft Access databases (.mdb), the information you enter on this tab is added to the SummaryInfo Document object in the Documents collection for Microsoft Access databases. 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 | In Microsoft Access databases (.mdb), the custom properties you enter become properties of the UserDefined Document object in the Documents collection.


 DataEntry Property

DataEntry Property

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 | Visual Basic | Description
Yes | True (–1) | The form opens showing only a blank record.
No | False (0) | (Default) The form opens showing existing records.

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:

  • AllowEdits — Yes

  • AllowDeletions — Yes

  • AllowAdditions — Yes

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


 DatasheetBackColor, DatasheetForeColor Properties

DatasheetBackColor, DatasheetForeColor Properties

  • 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 within a Microsoft Access database (.mdb).

  • 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 within an Access database (.mdb).

Setting

The DatasheetBackColor and DatasheetForeColor properties are a Long Integer value representing the background color and font color setting for a datasheet.

The following setting information applies to both Microsoft Access database and Access projects (.adp):

  • You can also set these properties by clicking Fill/BackColor [image] or Font/ForeColor [image] 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 table contains the properties that don't exist in the DAO Properties collection of until you set them by using the Formatting (Datasheet) toolbar or you can add them in an Access database (.mdb) by using the CreateProperty method and append it to the DAO Properties collection.

DatasheetBackColor | DatasheetFontUnderline*
DatasheetCellsEffect | DatasheetFontWeight*
DatasheetFontHeight* | DatasheetForeColor*
DatasheetFontItalic* | DatasheetGridlinesBehavior
DatasheetFontName* | DatasheetGridlinesColor

Note When you add or set any property listed with an asterisk, Microsoft Access automatically adds it to the Properties collection.


 DatasheetCellsEffect Property

DatasheetCellsEffect Property

You can use the DatasheetCellsEffect property to specify whether special effects are applied to cells in a datasheet.

Notes The DatasheetCellsEffect property applies only to objects in Datasheet view.

This property is only available in Visual Basic within a Microsoft Access database (.mdb)

Setting

The DatasheetCellsEffect property uses the following settings.

Setting | Visual Basic | Description
Flat | acEffectNormal (0) | (Default) No special effects are applied to the cells in the datasheet.
Raised | acEffectRaised (1) | Cells in the datasheet appear raised.
Sunken | acEffectSunken (2) | Cells in the datasheet appear sunken.

You can set this property by using Special Effect button on the Formatting (Datasheet) toolbar, and in an Access database (.mdb), by using a macro, or by using Visual Basic.

The following setting information applies to both Access databases (.mdb) and Access projects (.adp):

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 don't exist in the DAO Properties collection of until you set them by using the Formatting (Datasheet) toolbar or you can add them in an Access database (.mdb) by using the CreateProperty method and append it to the DAO Properties collection.

DatasheetFontItalic* | DatasheetForeColor*
DatasheetFontHeight* | DatasheetBackColor
DatasheetFontName* | DatasheetGridlinesColor
DatasheetFontUnderline* | DatasheetGridlinesBehavior
DatasheetFontWeight* | DatasheetCellsEffect

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


 DatasheetFontName, DatasheetFontHeight Properties

DatasheetFontName, DatasheetFontHeight Properties

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.

Notes The DatasheetFontName and DatasheetFontHeight properties apply to all fields in Datasheet view and to form controls when the form is in Datasheet view.

These properties are only available in Visual Basic within a Microsoft Access database (.mdb)

Setting

  • The DatasheetFontName property. In Visual Basic, a string expression equal to the name of the font.

  • The DatasheetFontHeight property. In Visual Basic, an Integer value between 1 and 127 representing the font size in points.

The following setting information applies to both Access databases (.mdb) and Access projects (.adp):

  • You can set these properties by selecting the font name from the Font box FontNames object or font size from the Font Size box [image] 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 don't exist in the DAO Properties collection of until you set them by using the Formatting (Datasheet) toolbar or you can add them in an Access database (.mdb) by using the CreateProperty method and append it to the DAO Properties collection.

DatasheetFontItalic* | DatasheetForeColor*
DatasheetFontHeight* | DatasheetBackColor
DatasheetFontName* | DatasheetGridlinesColor
DatasheetFontUnderline* | DatasheetGridlinesBehavior
DatasheetFontWeight* | DatasheetCellsEffect

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 of the database.


 DatasheetFontItalic, DatasheetFontUnderline Properties

DatasheetFontItalic, DatasheetFontUnderline Properties

You can use the DatasheetFontItalic and DatasheetFontUnderline properties to specify an italic or underlined appearance for field names and data in Datasheet view.

Notes The DatasheetFontItalic and DatasheetFontUnderline properties apply to all fields in Datasheet view and to form controls when the form is in Datasheet view.

These properties are only available in Visual Basic within a Microsoft Access database (.mdb).

Setting

In Visual Basic, the DatasheetFontItalic property uses the following settings.

Setting | Description
True (–1) | The text is italic.
False (0) | (Default) The text isn't italic.

In Visual Basic, the DatasheetFontUnderline property uses the following settings.

Setting | Description
True | The text is underlined.
False | (Default) The text isn't underlined.

In Visual Basic, these property settings are Boolean values.

The following setting information applies to both Access databases (.mdb) and Access projects (.adp):

You can set these properties by clicking Italic [image] or Underline [image] 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.

Remarks

The following table contains the properties that don't exist in the DAO Properties collection of until you set them by using the Formatting (Datasheet) toolbar or you can add them in an Access database (.mdb) by using the CreateProperty method and append it to the DAO Properties collection.

DatasheetFontItalic* | DatasheetForeColor*
DatasheetFontHeight* | DatasheetBackColor
DatasheetFontName* | DatasheetGridlinesColor
DatasheetFontUnderline* | DatasheetGridlinesBehavior
DatasheetFontWeight* | DatasheetCellsEffect

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 of the database.


 DatasheetFontWeight Property

DatasheetFontWeight Property

You can use the DatasheetFontWeight property to specify the line width of the font used to display and print characters for field names and data in Datasheet view.

Notes The DatasheetFontWeight property applies to all fields in Datasheet view and to form controls when the form is in Datasheet view.

These properties are only available in Visual Basic within a Microsoft Access database (.mdb)

Setting

In Visual Basic, the DatasheetFontWeight property setting uses the following Integer values.

Setting | Description
100 | Thin
200 | Extra Light
300 | Light
400 | (Default) Normal
500 | Medium
600 | Semi-bold
700 | Bold
800 | Extra Bold
900 | Heavy

The following setting information applies to both Access databases (.mdb) and Access projects (.adp):

  • 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 Bold [image] 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.

Remarks

The following table contains the properties that don't exist in the DAO Properties collection of until you set them by using the Formatting (Datasheet) toolbar or you can add them in an Access database (.mdb) by using the CreateProperty method and append it to the DAO Properties collection.

DatasheetFontItalic* | DatasheetForeColor*
DatasheetFontHeight* | DatasheetBackColor
DatasheetFontName* | DatasheetGridlinesColor
DatasheetFontUnderline* | DatasheetGridlinesBehavior
DatasheetFontWeight* | DatasheetCellsEffect

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 of the database.


 DatasheetGridlinesBehavior Property

DatasheetGridlinesBehavior Property

You can use the DatasheetGridlinesBehavior property to specify which gridlines will appear in Datasheet view.

Notes This DatasheetGridlinesBehavior property applies only to objects in Datasheet view.

This property is only available in Visual Basic within a Microsoft Access database (.mdb).

Setting

The DatasheetGridlinesBehavior property uses the following settings.

Setting | Visual Basic | Description
None | acGridlinesNone (0) | No gridlines are displayed.
Horizontal | acGridlinesHoriz (1) | Only horizontal gridlines are displayed.
Vertical | acGridlinesVert (2) | Only vertical gridlines are displayed.
Both | acGridlinesBoth (3) | (Default) Horizontal and vertical gridlines are displayed.

You can set this property by using the Gridlines button on the Formatting (Datasheet) toolbar, and in an Access database (.mdb), by using a macro, or by using Visual Basic.

The following setting information applies to both Access databases (.mdb) and Access projects (.adp):

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 don't exist in the DAO Properties collection of until you set them by using the Formatting (Datasheet) toolbar or you can add them in an Access database (.mdb) by using the CreateProperty method and append it to the DAO Properties collection.

DatasheetFontItalic* | DatasheetForeColor*
DatasheetFontHeight* | DatasheetBackColor
DatasheetFontName* | DatasheetGridlinesColor
DatasheetFontUnderline* | DatasheetGridlinesBehavior
DatasheetFontWeight* | DatasheetCellsEffect

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


 DatasheetGridlinesColor Property

DatasheetGridlinesColor Property

You can use the DatasheetGridlinesColor property to specify the color of gridlines in a datasheet.

Notes The DatasheetGridlinesColor property applies only to objects in Datasheet view.

This property is only available in Visual Basic within a Microsoft Access database (.mdb).

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 Line Color [image] on the Formatting (Datasheet) toolbar, in an Access database (.mdb), you can add the property by using a macro, or by using Visual Basic.

The following setting information applies to both Access databases (.mdb) and Access projects (.adp):

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 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 don't exist in the DAO Properties collection of until you set them by using the Formatting (Datasheet) toolbar or you can add them in an Access database (.mdb) by using the CreateProperty method and append it to the DAO Properties collection.

DatasheetFontItalic* | DatasheetForeColor*
DatasheetFontHeight* | DatasheetBackColor
DatasheetFontName* | DatasheetGridlinesColor
DatasheetFontUnderline* | DatasheetGridlinesBehavior
DatasheetFontWeight* | DatasheetCellsEffect

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


 DataType Property

DataType Property

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.

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 topic. | 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.
AutoNumber | A unique sequential (incremented by 1) number or random number assigned by Microsoft Access whenever a new record is added to a table. AutoNumber fields can't be updated. For more information, see the NewValues property topic. | 4 bytes (16 bytes 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: text to display — 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. screentip — the text displayed as a tooltip. The easiest way to insert a hyperlink address in a field or control is to click Hyperlink on the Insert menu. For more information, see Type a hyperlink address in Form view or Datasheet view. | Each part of the three parts of a Hyperlink data type can contain up to 2048 characters.
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.

You can set this property only in the upper portion of table Design view.

In Visual Basic, you can use the ADO 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 3, "Writing Solid Code," in the Microsoft Office 2000/Visual Basic Programmer's Guide. For information about how to obtain the Microsoft Office 2000/Visual Basic Programmer's Guide, click [image] .


 DateGrouping Property

DateGrouping Property

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.

Setting | Visual Basic | Description
US Defaults | 0 | 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).
Use System Settings | 1 | (Default) Microsoft Access uses settings based on the locale selected in the Regional Settings Properties dialog box in Windows Control Panel.

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.


DBEngine Property

You can use the DBEngine property in Visual Basic to access the current DBEngine object and its related properties.

Setting

The DBEngine property is set by Microsoft Access and is read-only 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.


 DecimalPlaces Property

DecimalPlaces Property

You can use the DecimalPlaces property to specify the number of decimal places Microsoft Access uses to display numbers.

Setting

The DecimalPlaces property uses the following settings.

Setting | Visual Basic | Description
Auto | 255 | (Default) Numbers appear as specified by the Format property setting.
0 to 15 | 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.

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.

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.


 Default Property

Default Property

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.

Setting | Visual Basic | Description
Yes | True (–1) | The command button is the default button.
No | False (0) | (Default) The command button isn't the default button.

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

Remarks

When the command button's Default property setting is Yes and the Form 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.


 DefaultValue Property (Microsoft Access)

DefaultValue Property

You can use the DefaultValue property to specify a value that is automatically entered in a field when a new record is created. For example, in an Addresses table you can set the default value for the City field to New York. When users add a record to the table, they can either accept this value or enter the name of a different city.

Notes

  • The DefaultValue property doesn't apply to check box, option button, or toggle button controls when they are in an option group. It does apply to the option group itself.

  • The DefaultValue property applies to all table fields except those fields with the data type of AutoNumber or OLE Object.

Setting

The DefaultValue property specifies text or an expression that'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":

Forms!frmInvoice!PaymentMethod.DefaultValue = """Cash"""

Note To set this property for a field by using Visual Basic, use the ADO DefaultValue or 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.


 DefaultView, ViewsAllowed Properties

DefaultView, ViewsAllowed Properties

  • You can use the DefaultView property to specify the opening view of a form.

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

Setting | Visual Basic | Description
Single Form | 0 | (Default) Displays one record at a time.
Continuous Forms | 1 | Displays multiple records (as many as will fit in the current window), each in its own copy of the form's detail section.
Datasheet | 2 | Displays the form fields arranged in rows and columns like a spreadsheet.

The ViewsAllowed property uses the following settings.

Setting | Visual Basic | Description
Both | 0 | (Default) Users can switch between Form view and Datasheet view.
Form | 1 | Users can't switch to Datasheet view from Form view.
Datasheet | 2 | Users can't switch to Form view from Datasheet view.

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.

DefaultView | ViewsAllowed | Description
Single, Continuous Forms, or Datasheet | Both | Users can switch between Form view and Datasheet view.
Single or Continuous Forms | Form | Users can't switch from Form view to Datasheet view.
Single or Continuous Forms | Datasheet | Users can switch from Form view to Datasheet view but not back again.
Datasheet | Form | Users can switch from Datasheet view to Form view but not back again.
Datasheet | Datasheet | Users can't switch from Datasheet view to Form view.


DefaultWebOptions Property (Microsoft Access)

DefaultWebOptions Property

You can use the DefaultWebOptions property to reference the DefaultWebOptions object and its related properties.

Setting

The DefaultWebOptions property is available by using Visual Basic.

Remarks

DefaultWebOptions property to identify or set the Application object's DefaultWebOptions object properties. These properties can be used to set or change the default web page settings available in the Web Options dialog box. To display this dialog box, click Options on the Tools menu. Click the General tab and click the Web Pages button.


 Description Property (Microsoft Access)

Description Property

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 in a Microsoft Access project (.adp), you must create an application-defined property by using the Add method. In a Microsoft Access database (.mdb), you must use the DAO CreateProperty method.

Remarks

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.


 DestConnectStr, DestinationDB, DestinationTable Properties

DestConnectStr, DestinationDB, DestinationTable Properties

  • The DestinationDB property specifies the type of application used to create an external database.

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

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

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 ADO 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 15, "Retrieving and Analyzing Data," in the Microsoft Office 2000/Visual Basic Programer's Guide. For information about how to obtain the Microsoft Office 2000/Visual Basic Programer's Guide, click [image] .


Dir Property (Data Access Page)

Language-specific information

You can use the Dir property to specify or determine the view orientation for information within a control for language-specific displays.

Setting

The Dir property uses the following settings.

Setting | Description
ltr | Sets the control's text direction to left to right.
rtl | Sets the control's text direction to right to left.

Remarks

The Dir property directly influences how information in controls is displayed.


 Dirty Property

Dirty Property

You can use the Dirty property to determine whether the current record has been modified since it was last saved. For example, you may want to ask the user whether changes to a record were intended and, if not, allow the user to move to the next record without saving the changes.

Setting

The Dirty property uses the following settings.

Setting | Visual Basic | Description
True | True (–1) | The current record has been changed.
False | False (0) | The current record has not been changed.

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.


 DisplayControl Property

DisplayControl Property

You can use the DisplayControl property in table Design view to specify the default control you want to use for displaying a field.

Setting

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.

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

DisplayType Property

You can use the DisplayType property to specify whether Microsoft Access displays an OLE object's content or an icon. For example, if the OLE object is a Microsoft Word document and you set this property to Content, the control displays the Word document; if you set this property to Icon, the control displays the Microsoft Word icon.

Setting

The DisplayType property uses the following settings.

Setting | Visual Basic | Description
Content | acOLEDisplayContent (0) | (Default) When the control contains an OLE object, the control displays the object's data, such as a document or spreadsheet.
Icon | acOLEDisplayIcon (1) | When the control contains an OLE object, the control displays the object's icon.

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.


 DisplayWhen Property

DisplayWhen Property

You can use the DisplayWhen property to specify which of a form's sections or controls you want displayed on screen and in print.

Note The DisplayWhen property applies only to 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.

Setting | Visual Basic | Description
Always | 0 | (Default) The object appears in Form view and when printed.
Print Only | 1 | The object is hidden in Form view but appears when printed.
Screen Only | 2 | The object appears in Form view but not when printed.

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.


 DividingLines Property

DividingLines Property

You can use the DividingLines property to specify whether dividing lines will separate sections on a form or records displayed on a continuous form.

Setting

The DividingLines property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) Dividing lines will separate sections and records on continuous forms.
No | False (0) | There are no dividing lines.

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.


DoCmd Property

You can use the DoCmd property to access the DoCmd object and its related methods.

Setting

This property is available only by using Visual Basic.


Document Property

You can use the Document property to access the Microsoft Internet Explorer 5.0 Dynamic HTML Document object for HTML pages.

Setting

This property is available only by using Visual Basic.

Remarks

For more information about the DHTML and the Document object model, see the following topics:

DHTML Tutorials

Document Object Model

Document Object References


 DownloadComponents Property

DownloadComponents Property

You can use the DownloadComponents property to specify or determine if the Microsoft Office tools are automatically downloaded with the Web page.

Setting

The DownloadComponents property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | Use the the necessary Office controls are downloaded when you view the saved document in a Web browser.
No | False (0) | (Default) Do not download the controls.

The DownloadComponents property is available only by using Visual Basic.

Remarks

You can set the LocationOfComponents property to a central URL where the controls can be downloaded by authorized users viewing your saved data access page. The path must be valid and must point to a location that contains the necessary components, and the user must have a valid Microsoft Office 2000 license.

Office Web components add interactivity to data access pages that you save as Web pages. If you view a Web page in a browser on a computer that does not have the components installed, the interactive portions of the page will be static.


 DrawMode Property

DrawMode Property

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

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.


 DrawStyle Property

DrawStyle Property

You can use the DrawStyle property to specify the line style when using the Line and Circle methods to print lines on reports.

Setting

The DrawStyle property uses the following settings.

Setting | Description
0 | (Default) Solid line, transparent interior
1 | Dash, transparent interior
2 | Dot, transparent interior
3 | Dash-dot, transparent interior
4 | Dash-dot-dot, transparent interior
5 | Invisible line, transparent interior
6 | Invisible line, solid interior

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


 DrawWidth Property

DrawWidth Property

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.


 EmailSubject Property

EmailSubject Property

You can use the EmailSubject property to specify or determine return the email subject line of a hyperlink to an object, document, Web page or other destination for a command button, image control, or label control.

Setting

The EmailSubject property is a string expression representing the subject line within a file (UNC path) or Web page (URL).

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

You can also use the Insert Hyperlink dialog box to set this property by clicking the Build button [image] 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 EmailSubject property to the location specified in the Subject box of the E-Mail Address tab.

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.


 Enabled, Locked Properties (Microsoft Access)

Enabled, Locked Properties

  • The Enabled property specifies whether a control can have the focus in Form view.

  • The Locked property specifies whether you can edit data in a control in Form view.

Setting

The Enabled property uses the following settings.

Setting | Visual Basic | Description
Yes | (True (–1) | 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.
No | False (0) | (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.

The Locked property uses the following settings.

Setting | Visual Basic | Description
Yes | True | (Default for unbound object frames) The control functions normally but doesn't allow editing, adding, or deleting data.
No | False | (Default for all controls except unbound object frames) The control functions normally and allows editing, adding, and deleting data.

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.

Enabled | Locked | Effect
Yes | Yes | The control can have the focus. Data is displayed normally and can be copied but not edited.
Yes | No | The control can have the focus. Data is displayed normally and can be copied and edited.
No | Yes | The control can't have the focus. Data is displayed normally but can't be copied or edited.
No | No | The control can't have the focus. Control and data are disabled (dimmed).

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.


 Encoding Property

Encoding Property

You can use the Encoding property to specify or determine the data access page encoding (code page or character set) to be used by the Web browser when you view the saved data access page.

Setting

The Encoding property is a Long value representing one the MsoEncoding constants. For a list of valid MsoEncoding constants, see the Object Browser in the Microsoft Visual Basic Editor.


 EnterKeyBehavior Property

EnterKeyBehavior Property

You can use the EnterKeyBehavior property to specify what happens when you press ENTER in a text box control in Form view or Datasheet view. For example, you can use 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 | Visual Basic | Description
Default | False (0) | (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.
New Line In Field | True (–1) | Pressing ENTER in the control creates a new line in the control so you can enter additional text.

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.

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.


 Error Property

Error Property

You can use the Error property to determine if an error occurred while loading or printing a snapshot.

Setting

The Error property setting is a Long value representing the error that occurred while trying to load a snapshot file.

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

Remarks

When you finish loading a snapshot, you can check this property to determine if any errors occurred. If the Error property is 0, then no error occurred.

The following table contains a description of the errors that may occur while opening a snapshot file.

Error | Description
2500 | Invalid value.
2501 | Invalid page.
2502 | Missing or invalid snapshot file.
2503 | Property is read-only.
2504 | Operation canceled by user.
2505 | You need a newer version of the Snapshot Viewer control to view this snapshot file.
2506 | An error occurred while printing.
2507 | An error occurred while opening a snapshot file.
2508 | Out of memory.
2509 | An error occurred writing to a temporary file while opening a snapshot file.
2510 | You have no printer installed, or no printer has been selected as the default.


 Event Properties

Event Properties

Event properties cause a macro or the associated Visual Basic event procedure to run when a particular event occurs. For example, if you enter the name of a macro in a command button's OnClick property, that macro runs when the command button is clicked. For a complete list of event properties, see Events and Event Properties Reference.

Setting

To run a macro, enter the name of the macro. You can choose an existing macro in the list. If the macro is in a macro group, it will be listed under the macro group name, as macrogroupname.macroname.

To run the event procedure associated with the event, select [Event Procedure] in the list.

Note Although using an event procedure is the recommended method for running Visual Basic code in response to an event, you can also run a user-defined function when an event occurs. To run a user-defined function, place an equal sign (=) before the function name and parentheses after it, as in =functionname( ).

You can set event properties in the property sheet for an object, 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 [image] 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:

  • The Macro Builder to create and specify a macro for this event property. You can also use the Macro Builder to edit a macro already specified by the property.

  • The Code Builder to create and specify an event procedure for this event property. You can also use the Code Builder to edit an event procedure already specified by the property.

  • In a Microsoft Access database (.mdb), the Expression Builder to choose and specify a user-defined function for this event property.

In Visual Basic, set the property to a string expression.

To run this Use this syntax Example
Macro "macroname"
Button1.OnClick = "MyMacro"
Event procedure "[Event Procedure]"
Button1.OnClick = "[Event Procedure]"
User-defined function "=functionname( )"
Button1.OnClick = "=MyFunction()"


 EventProcPrefix Property

EventProcPrefix Property

You can use the EventProcPrefix property to get the prefix portion of an event procedure name. For example, if you have a command button with an event procedure named Details_Click, the EventProcPrefix property returns the string "Details".

Setting

The EventProcPrefix property setting is a string expression.

This property is available only 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 (_).


 Expression1, Expression2 Properties (FormatCondition Object)

Expression1, Expression2 Properties (FormatCondition Object)

You can use the Expression1 and Expression2 properties to return the values of a conditional format within a FormatCondition object.

Setting

  • The Expression1 property returns a Variant value or expression associated with the first part of the conditional format.

  • The Expression2 property returns a Variant value or expression associated with the second part of the conditional format when the Operator property of the FormatCondition object is acBetween or acNotBetween, otherwise, the Expression2 property is NULL.

The Expression1 and Expression2 properties are available only by using Visual Basicand are read-only.

Conditional formatting can also be set on a combo box or text box from the Conditional Formatting dialog box. The Conditional Formatting dialog box is available by clicking Conditional Formatting on the Format menu when a form is in Design view.


 FailOnError Property

FailOnError Property

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.

Setting | Visual Basic | Description
Yes | True (–1) | Errors terminate the query.
No | False (0) | (Default) Errors don't terminate the query.

You can set the FailOnError property by using the query's property sheet or Visual Basic. To set this property in a Microsoft Access database (.mdb) with Visual Basic, you must first add it to a QueryDef object's Properties collection 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

FastLaserPrinting Property

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 | Visual Basic | Description
Yes | True (–1) | (Default) Lines and rectangles are replaced by text character lines.
No | False (0) | Lines and rectangles aren't replaced by text character lines.

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.


FeatureInstall Property

You can use the FeatureInstall property to specify or determine how Microsoft Access handles calls to methods and properties that require features not yet installed.

Setting

The FeatureInstall property uses one of the following msoFeatureInstall constants.

Constant | Value | Description
msoFeatureInstallNone | 0 | (Default) An Automation error occurs at run time when uninstalled features are called.
msoFeatureInstallOnDemand | 1 | The user is prompted to install new features.
msoFeatureInstallOnDemandWithUI | 2 | The feature is installed automatically and a progress meter is displayed during installation. The user isn't prompted to install new features.

Remarks

When VBA code references an object that is not installed the Microsoft Installer technology will attempt to install the required feature. You use the FeatureInstall property to control what happens when an uninstalled object is referenced. When this property is set to the default, any attempt to use an uninstalled object causes the Installer technology to try to install the requested feature. In some circumstances this may take some time, and the user may believe that the machine has stopped responding to additional commands.

You can set the FeatureInstall property to msoFeatureInstallOnDemandWithUI so users can see that something is happening as the feature is being installed. You can set the FeatureInstall property to msoFeatureInstallNone if you want to trap the error that is returned and display your own dialog box to the user or take some other custom action.

If you have the UserControl property set to False, users will not be prompted to install new features even if the FeatureInstall property is set to msoFeatureInstallOnDemand. If the UserControl property is set to True, an installation progress meter will appear if the FeatureInstall property is set to msoFeatureInstallOnDemand.


FELineBreak Property

Language-specific information

You can use the FELineBreak property to control line breaks at the beginning and end of lines in the form control (text box).

Settings

The FELineBreak property uses the following settings.

Setting | Description | Visual Basic
Yes | Controls line breaks. | True (-1)
No | Does control line breaks (default). | False (0)

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

Remarks

Setting the FELineBreak property to Yes moves any punctuation marks and closing parentheses at the beginning of a line to the end of the previous line, and opening parentheses at the end of a line to the beginning of the next line.


 FieldName Property

FieldName Property

You can use the FieldName property to specify the name of a field within a table. For example, you can specify "Last Name" for a field that stores employees' last names within the Employees table.

Setting

Enter a field name, following Microsoft Access object naming rules. The name can't duplicate any other field name in the table.

Note Avoid specifying a name for a field that could cause a conflict with built-in Microsoft Access function or property names, such as the Name property.

You can set this property in the upper portion of table Design view or by using Visual Basic.

In Visual Basic, use the ADO Name property to read and set a table's field name.

Remarks

Microsoft Access identifies a field by its field name. Once you have specified a field name in table Design view, you can use that name in expressions, Visual Basic procedures, and SQL statements.


 FieldSize Property (Microsoft Access)

FieldSize Property

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
Decimal | Stores numbers from -10^38 -1 through 10^38 -1 (.adp) Stores numbers from-10^28 -1 through 10^28 -1 (.mdb) | 28 | 12bytes
Integer | Stores numbers from –32,768 to 32,767 (no fractions). | None | 2 bytes
Long Integer | (Default) Stores numbers from –2,147,483,648 to 2,147,483,647 (no fractions). | None | 4 bytes
Single | Stores numbers from –3.402823E38 to –1.401298E–45 for negative values and from 1.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

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


 FileSearch Property (Microsoft Access)

FileSearch Property

You can use the FileSearch property to return a reference to the current FileSearch object and its related properties and methods.

Setting

[application.]FileSearch[.method or property]

The FileSearch property uses the following settings.

Setting | Description
application | The Application object.
FileSearch | Required. When used without specifying a method or property, returns the FileSearch object.
method or property | A method or property of the FileSearch object.

The FileSearch property is available only by using Visual Basic.

Remarks

Once you establish a reference to the FileSearch object, you can access all the properties and methods of the object. You can set a reference to the FileSearch object by clicking References on the Tools menu while in module Design view. Then set a reference to the Microsoft Office 9.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 9.0 Object Library constant to set a FileSearch object's property or as an argument to a FileSearch object's method.


 FillColor Property

FillColor Property

You use the FillColor property to specify the color that fills in boxes and circles drawn on reports with the Line and Circle methods. You can also use this property with Visual Basic to create special visual effects on custom reports when you print using a color printer 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.


 FillStyle Property

FillStyle Property

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.

Setting | Description
0 | Opaque
1 | (Default) Transparent
2 | Horizontal Line
3 | Vertical Line
4 | Upward Diagonal
5 | Downward Diagonal
6 | Cross
7 | Diagonal Cross

You can set the FillStyle property 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.


 Filter Property (Microsoft Access)

Filter Property

You can use the Filter property to specify a subset of records to be displayed when a filter is applied to a form, report query, or table.

Note If you want to specify a server filter within a Microsoft Access project (.adp) for data located on a server, use the ServerFilter property.

Setting

The Filter property is a string expression consisting of a WHERE clause without the WHERE keyword. For example, the following Visual Basic code defines and applies a filter to show only customers from the USA:

Me.Filter = "Country = 'USA'"
Me.FilterOn = True

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

You can also set this property in Form view or Datasheet view by pointing to Filter on the Records menu and clicking one of the commands on the submenu.

Note Setting the Filter property has no effect on the ADO Filter property.

Remarks

You can use the Filter property to save a filter and apply it at a later time. Filters are saved with the objects in which they are created. They are automatically loaded when the object is opened, but they aren't automatically applied.

When a new object is created, it inherits the RecordSource, Filter, OrderBy, and OrderByOn properties of the table or query it was created from.

To apply a saved filter to a form, query, or table, you can click Apply Filter Filter object on the toolbar, click Apply Filter/Sort on the Records menu, or use a macro or Visual Basic to set the FilterOn property to True (–1). For reports, you can apply a filter by setting the FilterOn property to Yes in the report's property sheet.

The Apply Filter button indicates the state of the Filter and FilterOn properties. The button remains disabled until there is a filter to apply. If an existing filter is currently applied, the Apply Filter button appears pressed in.

To apply a filter automatically when a form is opened, specify in the OnOpen event property setting of the form either a macro that uses the ApplyFilter action or an event procedure that uses the ApplyFilter method of the DoCmd object.

You can remove a filter by clicking the pressed-in Apply Filter button, clicking Remove Filter/Sort on the Records menu, or using Visual Basic to set the FilterOn property to False (0).

Note You can save a filter as a query by clicking Save As Query on the File menu while in the Filter By Form window or the Advanced Filter/Sort window.

When the Filter property is set in form Design view, Microsoft Access does not attempt to validate the SQL expression. If the SQL expression is invalid, an error occurs when the filter is applied.


 FilterLookup Property

FilterLookup Property

You can use the FilterLookup property to specify whether values appear in a bound text box control when using the Filter By Form or Server Filter By Form window.

Setting

The FilterLookup property uses the following settings.

Setting | Visual Basic | Description
Never | 0 | The field values aren't displayed. You can specify whether the filtered records can contain Null values.
Database Default | 1 | (Default) The field values are displayed according to the settings under Filter By Form Defaults on the Edit/Find tab of the Option dialog box, available by clicking Options on the Tools menu.
Always | 2 | The field values are always displayed.

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

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

Remarks

If you want to limit the types of fields to display, clear the appropriate check box under Filter By Form Defaults on the Edit/Find tab of the Option dialog box, available by clicking Options on the Tools menu. If field lists aren't displayed, you should increase the number in the Don't Display Lists Where More than This Number of Records Read box so the setting is greater than or equal to the maximum number of records in any field in the underlying source of records.


 FilterOn Property

FilterOn Property

You can use the FilterOn property to specify or determine whether the Filter property for a form or report is applied.

Note If you have specified a server filter within a Microsoft Access project (.adp), use the ServerFilterByForm property.

Setting

The FilterOn property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The object's Filter property is applied.
No | False (0) | (Default) The object's Filter property isn't applied.

For reports, you can set the FilterOn property by using the report's property sheet or Visual Basic.

For forms, you can set the FilterOn property in a macro or by using Visual Basic. You can also set this property by clicking Apply Filter Filter object on the Form View toolbar or the Filter/Sort toolbar.

Remarks

To apply a saved filter, press the Apply Filter button for forms, or apply the filter by using a macro or Visual Basic by setting the FilterOn property to True for forms or reports. For reports, you can set the FilterOn property to Yes in the report's property sheet.

The Apply Filter button indicates the state of the Filter and FilterOn properties. The button remains disabled until there is a filter to apply. If an existing filter is currently applied, the Apply Filter button appears pressed in. To apply a filter automatically when a form or report is opened, specify in the OnOpen event property setting of the form either a macro that uses the ApplyFilter action or an event procedure that uses the ApplyFilter method of the DoCmd object.

You can remove a filter by clicking the pressed-in Apply Filter button, clicking Remove Filter/Sort on the Records menu, or by using Visual Basic to set the FilterOn property to False. For reports, you can remove a filter by setting the FilterOn property to No in the report's property sheet.

Note When a new object is created, it inherits the RecordSource, Filter, ServerFilter. 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.


 FolderSuffix Property

FolderSuffix Property

You can use the FolderSuffix property to determine the folder suffix that Microsoft Access uses when you save a data access page as a Web page, use long file names, and choose to save supporting files in a separate folder (that is, if the UseLongFileNames and OrganizeInFolder properties are set to True)

Setting

The FolderSuffix property is a string expression representing the text displayed as a hyperlink.

This property is available only by using Visual Basic.

Remarks

Newly created data access pages use the suffix returned by the FolderSuffix property of the DefaultWebOptions object. The value of the FolderSuffix property of the WebOptions object may differ from that of the DefaultWebOptions object if the data access page was previously edited in a different language version of Microsoft Access. You can use the UseDefaultFolderSuffix method to change the suffix to the language you are currently using in Microsoft Office 2000.

By default, the name of the supporting folder is the name of the Web page plus an underscore (_), a period (.), or a hyphen (-) and the word "files" (appearing in the language of the version of Microsoft Access 2000 in which the file was saved as a Web page). For example, suppose that you use the Dutch language version of Access 2000 to save a file called "Page1" as a Web page. The default name of the supporting folder would be Page1_bestanden.

The following table lists each language version of Office 2000, and gives its corresponding LanguageID property value and folder suffix. For the languages that are not listed in the table, the suffix ".files" is used.

Language

Language | LanguageID | Folder suffix
Arabic | 1025 | .files
Basque | 1069 | _fitxategiak
Brazilian | 1046 | _arquivos
Bulgarian | 1026 | .files
Catalan | 1027 | _fitxers
Chinese - Simplified | 2052 | .files
Chinese - Traditional | 1028 | .files
Croatian | 1050 | _datoteke
Czech | 1029 | _soubory
Danish | 1030 | -filer
Dutch | 1043 | _bestanden
English | 1033 | _files
Estonian | 1061 | _failid
Finnish | 1035 | _tiedostot
French | 1036 | _fichiers
German | 1031 | -Dateien
Greek | 1032 | .files
Hebrew | 1037 | .files
Hungarian | 1038 | _elemei
Italian | 1040 | -file
Japanese | 1041 | .files
Korean | 1042 | .files
Latvian | 1062 | _fails
Lithuanian | 1063 | _bylos
Norwegian | 1044 | -filer
Polish | 1045 | _pliki
Portuguese | 2070 | _ficheiros
Romanian | 1048 | .files
Russian | 1049 | .files
Serbian (Cyrillic) | 3098 | .files
Serbian (Latin) | 2074 | _fajlovi
Slovakian | 1051 | .files
Slovenian | 1060 | _datoteke
Spanish | 3082 | _archivos
Swedish | 1053 | -filer
Thai | 1054 | .files
Turkish | 1055 | _dosyalar
Ukranian | 1058 | .files
Vietnamese | 1066 | .files


 FollowHyperlinkColor Property

FollowedHyperlinkColor Property

You can use the FollowedHyperlinkColor property to specify or determine the default color of all followed hyperlinks within the Application object.

Setting

The FollowedHyperlinkColor property uses the following settings.

Setting | Visual Basic
Black | acColorIndexBlack (0)
Maroon | acColorIndexMaroon (1)
Green | acColorIndexGreen (2)
Olive | acColorIndexOlive (3)
Dark Blue | acColorIndexDarkBlue (4)
Violet (default) | acColorIndexViolet (5)
Teal | acColorIndexTeal (6)
Gray | acColorIndexGray (7)
Silver | acColorIndexSilver (8)
Red | acColorIndexRed (9)
Bright Green | acColorIndexBrightGreen (10)
Yellow | acColorIndexYellow (11)
Blue | acColorIndexBlue (12)
Fushia | acColorIndexFushia (13)
Aqua | acColorIndexAqua (14)
White | acColorIndexWhite (15)

You can set the FollowedHyperlinkColor property through the DefaultWebOptions property or the SetOption method by using Visual Basic.

You can to set or change the default followed hyperlink color available in the Web Options dialog box. To display this dialog box, click Options on the Tools menu. Click the General tab and click the Web Pages button.

Remarks

The default color of a hyperlink is changed to the followed hyperlink color when a hyperlink control has been pressed.

Use the DefaultWebOptions property to identify or set the Application object's DefaultWebOptions object properties.


 FontBold Property

FontBold Property

You can use the FontBold property to specify whether a font appears in a bold style in the following situations:

  • When displaying or printing controls on forms and reports.

  • When using the Print method on a report.

Setting

The FontBold property uses the following settings.

Setting | Description
True (–1) | The text is bold.
False (0) | (Default) The text isn't bold.

You can set the FontBold property only by using a macro or Visual Basic.

Remarks

To use the FontBold property on a report, first create a Print event procedure that prints the desired text.

A font's appearance on screen and in print may differ, depending on your computer and printer.

The FontWeight property, which is available in the property sheet for controls, can also be used to set the line width for a control's text. The FontBold property gives you a quick way to make text bold; the FontWeight property gives you finer control over the line width setting for text. The following table shows the relationship between these properties' settings.

If | Then
FontBold = False | FontWeight = Normal (400)
FontBold = True | FontWeight = Bold (700)
FontWeight < 700 | FontBold = False
FontWeight > = 700 | FontBold = True


 FontItalic, FontUnderline Properties

FontItalic, FontUnderline Properties

You can use the FontItalic and FontUnderline properties to specify whether text is italic or underlined respectively in the following situations:

  • When displaying or printing controls on forms and reports.

  • When using the Print method on a report.

Setting

The FontItalic property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The text is italic.
No | False (0) | (Default) The text isn't italic.

The FontUnderline property uses the following settings.

Setting | Visual Basic | Description
Yes | True | The text is underlined.
No | False | (Default) The text isn't underlined.

For controls on forms and reports, you can set these properties by using the control's property sheet, a macro, or Visual Basic.

For reports, you can use these properties only in an event procedure or in a macro specified by the OnPrint event property setting.

You can also set these properties by clicking Italic [image] and Underline [image] on the Formatting (Form/Report) toolbar.

You can set the defaults for these properties by using the default control style or the DefaultControl method in Visual Basic.

Remarks

For a text box, combo box, label, or command button that contains a hyperlink, Microsoft Access automatically sets the FontUnderline property to Yes if the Underline Hyperlinks box is checked on the Hyperlinks/HTML tab of the Options dialog box, available by clicking Options on the Tools menu. If you remove the hyperlink from the control (for example, by changing the ControlSource property of a bound text box to a source that isn't a Hyperlink field), Microsoft Access sets the FontUnderline property back to the default control style. For command buttons, the FontUnderline property setting takes effect only if the command button contains a caption rather than a picture.


 FontName, FontSize Properties

FontName, FontSize Properties

You can use the FontName and FontSize properties to specify the font and point size respectively for text in the following situations:

  • When displaying or printing controls on forms and reports.

  • When using the Print method on a report.

Setting

The FontName property setting is the name of the font that the text is displayed in.

The FontSize property uses the following settings.

Setting | Description
8 | (Default for all reports and controls except command buttons) The text is 8-point type.
10 | (Default for command buttons) The text is 10-point type.
Other sizes | The text is the indicated size.

For controls on forms and reports, you can set these properties by using the property sheet, a macro, or Visual Basic.

You can also set these properties by clicking the Font box [image] and the Font Size box [image] on the Formatting (Form/Report) toolbar.

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

For reports, you can set these properties only in an event procedure or in a macro specified by the OnPrint event property setting.

In Visual Basic, you set the FontName property by using a string expression that is the name of the desired font and you set the FontSize property by using a numeric expression equal to the desired size of the font. The setting for the FontSize property can be between 1 and 127, inclusive.

Remarks

Font availability depends on your system and printer. If you select a font that your system can't display or that isn't installed, Windows substitutes a similar font.


 FontWeight Property

FontWeight Property

You use the FontWeight property to specify the line width that Windows uses to display and print characters in a control.

Setting

The FontWeight property uses the following settings.

Setting | Visual Basic
Thin | 100
Extra Light | 200
Light | 300
Normal | 400
Medium | 500
Semi-bold | 600
Bold | 700
Extra Bold | 800
Heavy | 900

You can set this property by using the control's property sheet, a macro, or Visual Basic. You can also click Bold [image] on the Formatting (Form/Report) toolbar. This sets the FontWeight property to Bold (700).

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 font's appearance on screen and in print may differ, depending on your computer and printer. For example, a FontWeight property setting of Thin may look identical to Normal on screen but appear lighter when printed.

The FontBold property, which is available only in Visual Basic and macros, can also be used to set the line width for a control's or report's text to bold. The FontBold property gives you a quick way to make text bold; the FontWeight property gives you finer control over the line width setting for text. The following table shows the relationship between these properties' settings.

If | Then
FontBold = False (0) | FontWeight = Normal (400)
FontBold = True (–1) | FontWeight = Bold (700)
FontWeight < 700 | FontBold = False
FontWeight > = 700 | FontBold = True


 ForceNewPage Property

ForceNewPage Property

You can use the ForceNewPage property to specify whether form sections (header, detail, footer) or report sections (header, detail, footer) print on a separate page, rather than on the current page. For example, you may have designed the last page of a report as an order form. If the report footer's ForceNewPage property is set to Before Section, the order form is always printed on a new page.

Note The ForceNewPage property does not apply to page headers or page footers.

Setting

The ForceNewPage property uses the following settings.

Setting | Visual Basic | Description
None | 0 | (Default) The current section (the section for which you're setting the property) is printed on the current page.
Before Section | 1 | The current section is printed at the top of a new page.
After Section | 2 | The section immediately following the current section is printed at the top of a new page.
Before & After | 3 | The current section is printed at the top of a new page, and the next section is printed at the top of a new page.

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

Remarks

Here are some examples of the ForceNewPage property setting.

Section | Sample setting | Description
A group header displaying the year | Before Section | The group header is printed at the top of the page, followed by the detail section, group footer, and page footer.
A report detail section | After Section | The group footer is printed at the top of a new page.
A report header containing the report title and company logo. | After Section | The report title and logo are printed on a separate page at the beginning of the report.


 ForeColor Property

ForeColor Property

You can use the ForeColor property to specify the color for text in a control. You can use this property for controls on forms or reports to make them easy to read or to convey a special meaning. For example, you can change the color of the text in the UnitsInStock control when its value falls below the reorder level.

You can also use this property on reports to create special visual effects when you print with a color printer. When used on a report, this property specifies the printing and drawing color for the Print, Line, and Circle methods.

Setting

The ForeColor property contains a numeric expression that represents the value of the text color in the control.

You can use the Color Builder to set this property by clicking the Build button [image] to the right of the property box in the property sheet. Using the Color Builder enables you to define custom colors for text in controls.

For controls, you can set this property by using Font/Fore Color [image] 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 a control's default control style or the DefaultControl method in Visual Basic.

For reports, you can set the ForeColor property only by using a macro or a Visual Basic event procedure specified in a section's OnPrint event property setting.

For Table objects, you can set this property using Font/Fore Color [image] on the Formatting (Datasheet) toolbar, or in Visual Basic by using the DatasheetForeColor property.

Remarks

For a text box, combo box, label, or command button that contains a hyperlink, Microsoft Access automatically sets the ForeColor property to the color specified in the Followed Hyperlink Color or Hyperlink Color box on the Hyperlinks/HTML tab of the Options dialog box, available by clicking Options on the Tools menu. If you remove the hyperlink from the control (for example, by changing the ControlSource property of a bound text box to a source that isn't a Hyperlink field), Microsoft Access sets the ForeColor property back to the default control style. For command buttons, the ForeColor property setting takes effect only if the command button contains a caption rather than a picture.


 Form, Report Properties

Form, Report Properties

You can use the Form and Report properties to refer to a form or report or to refer to the form or report associated with a subform control or subreport control.

Setting

These properties refer to a form or report object. They are read-only in all views.

You can use these properties by using a macro or Visual Basic.

Remarks

These properties are typically used to refer to the form or report contained in a subform or subreport control. For example, the following code uses the Form property to access the OrderID control on a subform contained in the OrderDetails subform control.

Dim intOrderID As Integer
intOrderID = Forms!Orders!OrderDetails.Form!OrderID

The next example calls a function from a property sheet by using the Form property to refer to the active form that contains the control named CustomerID.

=MyFunction(Form!CustomerID)

When you use the Form property in this manner, you are referring to the active form, and the name of the form isn't necessary.

The next example is the Visual Basic equivalent of the preceding example.

X = MyFunction(Forms!Customers!CustomerID)

Note When you use the Forms or Reports collection, you must specify the name of the form or report.


 Format Property

Format Property

You can use the Format property to customize the way numbers, dates, times, and text are displayed and printed. For example, if you've created a Price text box, you can set its Format property to Currency and its DecimalPlaces property to 2 or Auto. If you enter 4321.678 in the control, the number would be displayed as $4,321.68.

You can use one of the predefined formats or you can create a custom format by using formatting symbols.

Setting

The Format property uses different settings for different data types. For information about settings for a specific data type, see one of the following topics:

  • Date/Time Data Type

  • Number and Currency Data Types

  • Text and Memo Data Types

  • Yes/No Data Type

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) or in Design view of the Query window (in the Field Properties property sheet). You can also use a macro or Visual Basic.

Note In Visual Basic, enter a string expression that corresponds to one of the predefined formats or enter a custom format.

Remarks

The Format property affects only how data is displayed. It doesn't affect how data is stored.

Microsoft Access provides predefined formats for Date/Time, Number and Currency, Text and Memo, and Yes/No data types. The predefined formats depend on the country specified by double-clicking Regional Settings in Windows Control Panel. Microsoft Access displays formats appropriate for the country selected. For example, with English (United States) selected on the Regional Settings tab, 1234.56 in the Currency format appears as $1,234.56, but when English (British) is selected on the Regional Settings tab, the number appears as £1,234.56.

If you set a field's Format property in table Design view, Microsoft Access uses that format to display data in datasheets. It also applies the field's Format property to new controls on forms and reports.

You can use the following symbols in custom formats for any data type.

Symbol | Meaning
(space) | Display spaces as literal characters.
"ABC" | Display anything inside quotation marks as literal characters.
! | Force left alignment instead of right alignment.
* | Fill available space with the next character.
\ | Display the next character as a literal character. You can also display literal characters by placing quotation marks around them.
[color] | Display the formatted data in the color specified between the brackets. Available colors: Black, Blue, Green, Cyan, Red, Magenta, Yellow, White.

You can't mix custom formatting symbols for the Number and Currency data types with Date/Time, Yes/No, or Text and Memo formatting symbols.

When you have defined an input mask and set the Format property for the same data, the Format property takes precedence when the data is displayed and the input mask is ignored. For example, if you create a Password input mask in table Design view and also set the Format property for the same field, either in the table or in a control on a form, the Password input mask is ignored and the data is displayed according to the Format property.


FormatConditions Property

You can use the FormatConditions property to return a reference to the FormatConditions collection and its related properties.

Setting

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

Remarks

Conditional formatting can also be set on a combo box or text box from the Conditional Formatting dialog box. The Conditional Formatting dialog box is available by clicking Conditional Formatting on the Format menu when a form is in Design view.


 FormatCount Property

FormatCount Property

You can use the FormatCount property to determine the number of times the OnFormat property has been evaluated for the current section on a report.

Setting

You can use this property only in a macro or an Visual Basic event procedure specified by a section's OnFormat property setting.

The FormatCount property setting has a Long data type value.

This property isn't available in report Design view and is read-only in other views.

Remarks

Microsoft Access increments the FormatCount property each time the OnFormat property setting is evaluated for the current section. As the next section is formatted, Microsoft Access resets the FormatCount property to 1.

Under some circumstances, Microsoft Access formats a section more than once. For example, you might design a report in which the KeepTogether property for the detail section is set to Yes. When Microsoft Access reaches the bottom of a page, it formats the current detail section once to see if it will fit. If it doesn't fit, Microsoft Access moves to the next page and formats the detail section again. In this case, the setting for the FormatCount property for the detail section is 2 because it was formatted twice before it was printed.

You can use the FormatCount property to ensure that an operation that affects formatting gets executed only once for a section. In the following example, the DLookup function is evaluated only when the FormatCount property is set to 1:

Private Sub Detail_Format(Cancel As Integer, _
     FormatCount As Integer)
    Const conBold = 700
    Const conNormal = 400
    If FormatCount = 1 Then
        If DLookup("CompanyName", _
                "Customers", "CustomerID = Reports!" _
                & "[Customer Labels]!CustomerID") _
                Like "B*" Then
            CompanyNameLine.FontWeight = conBold
        Else
            CompanyNameLine.FontWeight = conNormal
        End If
    End If
End Sub


Forms Property

You can use the Forms property to return a reference to the Forms collection and its related properties.

Setting

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

Remarks

The properties of the Forms collection in Visual Basic refer to forms that are currently open.


 FrozenColumns Property

FrozenColumns Property

You can use the FrozenColumns property to determine how many columns in a datasheet are frozen. Frozen columns are displayed on the left side of the datasheet and don't move when you scroll horizontally through the datasheet.

Note The FrozenColumns property applies only to tables, forms, and queries in Datasheet view.

Setting

The FrozenColumns property is set by Microsoft Access when you click Freeze Columns on the Format menu.

In Visual Basic, this property setting is an Integer value indicating the number of columns in the datasheet that have been frozen by using the Freeze Columns command. The record selector column is always frozen, so the default value is 1. Consequently, if you freeze one column, the FrozenColumns property is set to 2; if you freeze two columns, it's set to 3; and so on.

This property setting is read-only in all views.

Remarks

When you freeze columns by using the Freeze Columns command, Microsoft Access automatically moves the columns to the leftmost edge of the datasheet in the order in which you freeze them. For example, if you freeze three columns, these become the first, second, and third columns in the datasheet. Because the record selector column is always frozen, the FrozenColumns property in this case will be set to 4. The three columns you freeze will have their ColumnOrder properties set to 1, 2, and 3 (in the order they are frozen).

If you click Unfreeze All Columns on the Format menu, all frozen columns will be unfrozen, and the FrozenColumns property will be set to 1.

Note The Unfreeze All Columns command will not restore the original order of columns if the Freeze Columns command caused the column order to change.


 FullName Property

FullName Property

You can use the FullName property to determine the full pathname (including filename) of a specific data access page.

Setting

The FullName property is a string expression and is available only by using Visual Basic and is read-only.

Remarks

The FullName property is the full name of the file that the link points to. The Name property is the name of the link.

The FullName value is the same string that is displayed when you hover over a data access page name in the Database window.


 FullPath Property

FullPath Property

The FullPath property returns a string containing the path and file name of the referenced type library.

Setting

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

Remarks

Type libraries reside in files. The following table shows the file extensions for files that commonly contain type libraries.

File extension | Type of file
.olb, .tlb | Type library file
.adp, .ade, .mdb, .mda, .mde | Database
.exe, .dll | Executable file
.ocx | ActiveX control

If the IsBroken property setting of a Reference object is True (–1), reading the FullPath property generates an error.


FuriganaControl Property

Language-specific information

You can use the FuriganaControl property to indicate a target control and automatically create furigana for text entered in a text box.

Settings

The setting value is the name of the control for entering Furigana.

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

Remarks

If the FuriganaControl property is set in the control, furigana will automatically be created, and can be displayed in a separately designated control. Only if a control name in the same form is set with the FuriganaControl property will the form run properly when executed. If text is entered in a control other than the designated control name in the same form, an error will occur. The type of furigana characters is determined by the IMEMode/KanjiConversionMode property settings in the control.

Note If you enter text in the target control, the furigana of the newly entered text is automatically added to the end of the designated target control content. Even if the text of the target control is revised or deleted, the characters before the change in the target control will not be revised or deleted. Changing the content of the target control revises the text in the Furigana control as necessary. The FuriganaControl property will not run if text is pasted into the target control.


 GridX, GridY Properties

GridX, GridY Properties

You can use the GridX and GridY properties to specify the horizontal and vertical divisions of the alignment grid in form Design view and report Design view.

Setting

Enter an integer between 1 and 64 representing the number of subdivisions per unit of 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

GroupHeader, GroupFooter Properties

You can use the GroupHeader and GroupFooter properties to create a group header or a group footer for a selected field or expression 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.

Setting | Description
Yes | Creates a group header or footer.
No | (Default) Doesn't create a group header or footer.

You set these properties in the Sorting And Grouping box.

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

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.


 GroupInterval Property

GroupInterval Property

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.
Text | Prefix characters | Set to 3 for grouping by the first three characters in the field (for example, Chai, Chartreuse, and Chang would be grouped together).
Date/Time | Week | Set to 2 to return data in biweekly groups.
Date/Time | Hour | Set to 12 to return data in half-day groups.

To set the GroupInterval property to a value other than its default setting (1), you must first set the GroupHeader or GroupFooter property or both to Yes for the selected field or expression.


 GroupLevel Property

GroupLevel Property

You can use the GroupLevel property in Visual Basic to refer to the group level you are grouping 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.

Group level | Refers to
GroupLevel(0) | The first field or expression you sort or group on.
GroupLevel(1) | The second field or expression you sort or group on.
GroupLevel(2) | The third field or expression you sort or group on.

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

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!txtPromptYou
End Sub


 GroupOn Property

GroupOn Property

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
 | Year | Dates in the same calendar year. | 2
 | Qtr | Dates in the same calendar quarter. | 3
 | Month | Dates in the same month. | 4
 | Week | Dates in the same week. | 5
 | Day | Dates on the same date. | 6
 | Hour | Times in the same hour. | 7
 | Minute | Times in the same minute. | 8
AutoNumber, Currency, Number | (Default) Each Value | The same value in the field or expression. | 0
 | Interval | Values within an interval you specify. | 9

You can set the GroupOn property 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.


 GrpKeepTogether Property

GrpKeepTogether Property

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.

Setting | Visual Basic | Description
Per Page | 0 | Groups are kept together by page.
Per Column | 1 | (Default) Groups are kept together by column.

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.


 GUID Property

GUID Property

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.


HasContinued Property

You can use the HasContinued property to determine if part of the current section begins on the previous page.

Setting

The HasContinued property is set by Microsoft Access and is read-only in all views.

Value | Description
True (–1) | Part of the current section has been printed on the previous page.
False (0) | Part of the current section hasn't been printed on the previous page.

You can get the value of the HasContinued property 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.


 HasData Property

HasData Property

You can use the HasData property to determine if a form or report is bound to an empty recordset.

Setting

The HasData property is set by Microsoft Access. The value of this property can be read only while printing or while in Print Preview.

Value | Description
–1 | The object has data.
0 | The object doesn't have data.
1 | The object is unbound.

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


 HasModule Property

HasModule Property

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.

Setting | Visual Basic | Description
Yes | True (–1) | The form or report has a class module.
No | False (0) | (Default) The form or report doesn't have a class module.

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

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 methods are lightweight by default.


 Height, Width Properties (Microsoft Access)

Height, Width Properties

You can use the Height and Width properties to size an object to specific dimensions. This can be useful, for example, if you want to create objects that are exactly the same size or that have the same width or height.

Notes

  • The Height property applies only to form sections and report sections, not to forms and reports.

  • The Width property applies only to forms and reports, not to form sections and report sections.

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


 HelpContextID, HelpFile Properties (Microsoft Access)

HelpContextID, HelpFile Properties

  • The HelpContextID property specifies the context ID of a topic in the custom Help file specified by the HelpFile property setting.

  • The HelpFile property specifies the name of a custom Help file for the current form or report.

Setting

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

    Note If you enter the context ID of the Help file topic as a positive number, the help topic will display in a "full" help topic window. If you add a minus sign ("-") in from of the context ID, the help topic will be displayed in a "pop-up" window. It is important to note the the context id does not have to have a negative number when authored in Microsoft Help Workshop. You must add the minus sign when setting the property to make the topic display in the pop-up window.

  • 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

You can create a custom Help file to document forms, reports, or applications you create with Microsoft Access.

When you press the F1 key in Form view, Microsoft Access calls the Microsoft Help Workshop or Microsoft HTML Help Workshop 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.


 HideDuplicates Property

HideDuplicates Property

You can use the HideDuplicates property to hide a control on a report when its value is the same as in the preceding record. For example, on a report listing suppliers and their products, each supplier's name can appear once for each group of products, rather than once for each product.

Note The HideDuplicates property applies only to controls (check box, combo box, list box, option button, option group, text box, toggle button) on a report.

The property doesn't apply to check boxes, option buttons, or toggle buttons when they appear in an option group. It does apply to the option group itself.

Setting

The HideDuplicates property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | If the value of a control or the data it contains is the same as in the preceding record, the control is hidden.
No | False (0) | (Default) The control is visible regardless of the value in the preceding record.

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.


 hWnd Property

hWnd Property

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.


 Hyperlink Property

Hyperlink Property

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 command button, image, or label control.

Setting

The Hyperlink property is available only by using Visual Basic.


 HyperlinkAddress Property

HyperlinkAddress Property

You can use the HyperlinkAddress property to specify or determine the path to an object, document, Web page or other destination for a hyperlink associated with 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 Web page (URL).

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

Note When you set the HyperlinkAddress property, you automatically specify the Address property for the Hyperlink object associated with the control.

You can also use the Insert Hyperlink dialog box to set this property by clicking the Build button [image] 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 and HyperlinkSubAddress to the location specified in the Type the file or Web page name box. The HyperlinkSubAddress property can also be set to the location specified in the Select an object in this database 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 property, 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.
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.
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".


 HyperlinkColor Property

HyperlinkColor Property

You can use the HyperlinkColor property to specify or determine the default color of all hyperlinks within the Application object.

Setting

The HyperlinkColor property uses the following settings.

Setting | Visual Basic
Black | acColorIndexBlack (0)
Maroon | acColorIndexMaroon (1)
Green | acColorIndexGreen (2)
Olive | acColorIndexOlive (3)
Dark Blue | acColorIndexDarkBlue (4)
Violet | acColorIndexViolet (5)
Teal | acColorIndexTeal (6)
Gray | acColorIndexGray (7)
Silver | acColorIndexSilver (8)
Red | acColorIndexRed (9)
Bright Green | acColorIndexBrightGreen (10)
Yellow | acColorIndexYellow (11)
Blue (default) | acColorIndexBlue (12)
Fushia | acColorIndexFushia (13)
Aqua | acColorIndexAqua (14)
White | acColorIndexWhite (15)

You can set the HyperlinkColor property through the DefaultWebOptions property or the SetOption method by using Visual Basic.

You can set or change the default hyperlink color available in the Web Options dialog box. To display this dialog box, click Options on the Tools menu. Click the General tab and click the Web Pages button.

Remarks

The default color of a hyperlink is changed to the followed hyperlink color when a hyperlink control has been pressed.

Use the DefaultWebOptions property to identify or set the Application object's DefaultWebOptions object properties.


 HyperlinkSubAddress Property

HyperlinkSubAddress Property

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 [image] 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 and HyperlinkSubAddress to the location specified in the Type the file or Web page name box. The HyperlinkSubAddress property is set to the location specified in the Select an object in this database 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.
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".


 IgnoreNulls Property (Microsoft Access)

IgnoreNulls Property

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.

Setting | Visual Basic | Description
Yes | True (–1) | Records that contain Null values in the indexed fields aren't included in the index.
No | False (0) | (Default) Records that contain Null values in the indexed fields are included in the index.

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.


 ImageHeight Property

ImageHeight Property

You can use the ImageHeight property in Visual Basic to determine the height in twips of the picture in an image control.

Setting

The ImageHeight property is an Integer value equal to the height of a picture in twips.

This property is read-only in all views.

Remarks

You can use the ImageHeight property together with the ImageWidth property to determine the size of a picture in an image control. You could then use this information to change the image control's Height and Width properties to match the size of the picture displayed.


 ImageWidth Property

ImageWidth Property

You can use the ImageWidth property in Visual Basic to determine the width in twips of a picture in an image control.

Setting

The ImageWidth property is an Integer value equal to the width of a picture in twips.

This property is read-only in all views.

Remarks

You can use the ImageWidth property together with the ImageHeight property to determine the size of a picture in an image control. You could then use this information to change the image control's Height and Width properties to match the size of the picture displayed.


 IMEHold/HoldKanjiConversionMode Property

IMEHold/HoldKanjiConversionMode Property

Language-specific information

You can use the IMEHold/Hold KanjiConversionMode property to show whether the Kanji Conversion Mode is maintained when the control loses the focus.

Settings

The IMEHold/Hold KanjiConversionMode property uses the following settings.

Settings | Description | Visual Basic
Yes | Maintains the Kanji Conversion Mode set in the last control. | True (-1)
No | Does not maintain the Kanji Conversion Mode set in the last control (default). | False (0)

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

Remarks

By setting the IMEHold/Hold KanjiConversionMode property, you can designate whether or not the Kanji Conversion Mode is maintained when the control loses the focus. If this property is set to Yes, the Kanji Conversion Mode setting is maintained when the control loses the focus and once that control regains the focus, the Kanji Conversion Mode setting for that control is restored. If this property is set to No (default setting), the Kanji Conversion Mode will be set by the IMEMode/KanjiConversionMode property for that control.

Note To set the Kanji Conversion Mode when the focus shifts to the control, set the IMEMode/KanjiConversionMode property.


 IMEMode/KanjiConversion Property

IMEMode/KanjiConversionMode Property

Language-specific information

You can use the IMEMode/KanjiConversionMode property to set a control's Kanji Conversion Mode when the focus shifts to the control.

Settings

The IMEMode/KanjiConversionMode property uses the following settings.

Setting | Description | Visual Basic
No Control | Kanji Conversion Mode not set (default). | 0
On | Turns on Kanji Conversion Mode. | 1
Off | Turns off Kanji Conversion Mode. | 2
Disable | Disables Kanji Conversion Mode. | 3
Hiragana | Sets full pitch hiragana | 4
Full pitch Katakana | Sets full pitch katakana. | 5
Half pitch Katakana | Sets half pitch katakana. | 6
Full pitch Alpha/Num | Sets full pitch letters/numbers. | 7
Half pitch Alpha/Num | Sets half pitch letters/numbers. | 8

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

Remarks

You can specify the Kanji Conversion Mode when the focus shifts to control by setting the IMEMode/KanjiConversionMode property. If set to No Control (default) the setting before the focus shifted to that control is used. For any other setting, the Kanji Conversion Mode setting for that control is used. For example, if the IMEMode/KanjiConversionMode property is set to Off, the Kanji Conversion Mode is turned off, and if the IMEMode/KanjiConversionMode property is set to On, the Kanji Conversion Mode is turned on. The Kanji Conversion Mode automatically changes each time the focus shifts between controls.

Note If set to Disable, the Kanji Conversion Mode settings cannot be changed. If any other setting is used, the Kanji Conversion Mode can be changed, but when the focus changes, the settings are lost. If you want to save the settings before the control loses the focus, set the IMEHold/HoldKanjiConversionMode property.


 Indexed Property

Indexed Property

You can use the Indexed property to set a single-field index. An index speeds up queries on the indexed fields as well as sorting and grouping operations. For example, if you search for specific employee names in a LastName field, you can create an index for this field to speed up the search for a specific name.

Setting

The Indexed property uses the following settings.

Setting | Description
No | (Default) No index.
Yes (Duplicates OK) | The index allows duplicates.
Yes (No Duplicates) | The index doesn't allow duplicates.

You can set this property only in the 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 ADO Append method of the Indexes collection 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.


 InputMask Property

InputMask Property

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.
Second | Specifies whether Microsoft Access stores the literal display characters in the table when you enter data. If you use 0 for this section, all literal display characters (for example, the parentheses in a phone number input mask) are stored with the value; if you enter 1 or leave this section blank, only characters typed into the control are stored.
Third | Specifies the character that Microsoft Access displays for the space where you should type a character in the input mask. For this section, you can use any character; to display an empty string, use a space enclosed in quotation marks (" ").

In Visual Basic you use a string expression to set this property. For example, the following specifies an input mask for a text box control used for entering 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.

Character | Description
0 | Digit (0 to 9, entry required, plus [+] and minus [–] signs not allowed).
9 | Digit or space (entry not required, plus and minus signs not allowed).
# | Digit or space (entry not required; spaces are displayed as blanks while in Edit mode, but blanks are removed when data is saved; plus and minus signs allowed).
L | Letter (A to Z, entry required).
? | Letter (A to Z, entry optional).
A | Letter or digit (entry required).
a | Letter or digit (entry optional).
& | Any character or a space (entry required).
C | Any character or a space (entry optional).
. , : ; - / | Decimal placeholder and thousand, date, and time separators. (The actual character used depends on the settings in the Regional Settings 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).

Note Setting the InputMask property to the word "Password" creates a password-entry control. Any character typed in the control is stored as the character but is displayed as an asterisk (*). You use the Password input mask to prevent displaying the typed characters on the screen.

For a control, you can set this property in the control's property sheet. For a field in a table, you can set the property in table Design view (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.


 InputParameters Property

InputParameters Property

You can use the InputParameters property to specify or determine the input parameters that are passed to a SQL statement in the RecordSource property of a form or report or a stored procedure when used as the record source within a Microsoft Access project (.adp).

Setting

<name> <type> = <expression> [,<name> <type> = <expression> ] ...

The InputParameters property has the following arguments.

Argument | Description
name | The name of the parameter. If it is a stored procedure parameter, it requires a leading @ sign. Spaces are not allowed in parameter names.
type | The SQL Server datatype of the parameter.
expression | A Microsoft Access expression that is passed to the expression service to resolve. Like other expressions, it can refer to another control on the form, it can supply a prompt text for user input, or it can be a literal.
 | If the = sign is followed by nothing or immediately by a comma, the proc is executed using the default parameter value as defined in the query or CREATE PROC command. This is also true if the parameter is not listed in the string at all.

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

Remarks

When used with a RecordSource property:

An example InputParameter property string used with a SQL statement in the RecordSource property would use the following syntax.

state char=[Form]![StateList], salesyear smallint=[Enter year of interest]

This would result in the state parameter being set to the current value of the StateList control, and the user getting prompted for the salesyear parameter. If there were any other parameters that were not in this list, they would get default values assigned.

The query should be executed with one ? marker for each non-default parameter in the InputParameter list.

A refresh or requery command (via menu, keyboard, or Navigation Bar) in Access should trigger a reexecute of the query. Users can do this in code by calling the standard Recordset.Requery method. If the value of a parameter is bound to a control on the form, the current value of the control is used at requery time. The query is not automatically reexecuted when the value of the control changes.

When used with a stored procedure:

An example InputParameter property string used with stored procedure would be:

@state char=[Form]![StateList], @salesyear smallint=[Enter year of interest]

This would result in the @state parameter being set to the current value of the StateList control, and the user getting prompted for the @salesyear parameter. If there were any other parameters to the stored proc that were not in this list, they would get default values assigned.

The stored procedure should be executed using a command string containing the {call } syntax with one ? marker for each non-default parameter in the InputParameter list.

A refresh or requery command (via menu, keyboard, or Navigation Bar) in Access should trigger a reexecute of the stored procedure. Users can do this in code by calling the standard Recordset.Requery method. If the value of a parameter is bound to a control on the form, the current value of the control is used at requery time. The stored procedure is not automatically reexecuted when the value of the control changes.

This builder dialog is invoked when a stored procedure is first selected as the record source of a form if the stored procedure has any parameters. After initial creation of the InputParameters string, this same dialog is used as a builder for changing the string. In this case however the list of parameters comes from what already exists in the string.

Parameter values are also settable in code using the ActiveX Data Object's (ADO) Command and Parameter objects. If the result returns a result set, a form can be bound to it by setting the form's Recordset property. ADO coding is the only way to handle stored procedures that do not return result sets such as action queries, those that return output parameters, or those that return multiple result sets.


 InSelection Property

InSelection Property

You can use the InSelection property to determine or specify whether a control on a form in Design view is selected.

Setting

The InSelection property uses the following settings.

Setting | Description
True (–1) | The control is selected.
False (0) | The control isn't selected.

This property is available only 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.


 InsideHeight, InsideWidth Properties

InsideHeight, InsideWidth Properties

You can use the InsideHeight and InsideWidth properties to determine the height and width (in twips) of the window containing a form.

Setting

  • The InsideHeight property. An Integer value expressed in twips that represents the height of a form window.

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

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.


 IsBroken Property

IsBroken Property

The IsBroken property returns a Boolean value indicating whether a Reference object points to a valid reference in the Windows Registry.

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.


 IsCompiled Property

IsCompiled Property

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.


IsConnected Property

You can use the IsConnected property to determine if the CurrentProject or CodeProject object is currently connected.

Setting

The IsConnected property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The CurrentProject or CodeProject object is currently connected.
No | False (0) | The CurrentProject or CodeProject object is not connected

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


 IsHyperlink Property

IsHyperlink Property

You can use the IsHyperlink property to specify or determine if the data contained in a text box or combo box is a hyperlink.

Setting

The IsHyperlink property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The data displayed is a hyperlink.
No | False (0) | The data displayed is not a hyperlink.

You can set the IsHyperlink property by using the property sheet, a macro, or Visual Basic.


IsLoaded Property

You can use the IsLoaded property to determine if an AccessObject is currently loaded.

Setting

The IsLoaded property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The specified AccessObject is loaded.
No | False (0) | The specified AccessObject is not loaded..

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


 IsVisible Property

IsVisible Property

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.

Setting | Description
True (–1) | (Default) The control is visible.
False (0) | The control isn't visible.

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.


 Item Property (Collections)

Item Property (Collections)

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.

Setting | Description
object | One of the following collections:
 | Controls Forms Modules Pages Reports Properties AccessObjectProperties DataAccessPages AllForms AllReports | AllDataAccessPages AllMacros AllModules AllTables AllQueries AllViews AllStoredProcedures AllDatabaseDiagrams FormatConditions
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.

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)


 Item Property (ObjectFrame Control)

Item Property (ObjectFrame Control)

You can use the Item property to get a description of the linked data displayed in a chart control or unbound object frame.

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.

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


 ItemData Property

ItemData Property

The ItemData property returns the data in the bound column for the specified row in a combo box or list box.

Syntax

control.ItemData(rowindex)

The ItemData property has the following arguments.

Argument | Description
control | A Control object that represents a combo box or list box.
rowindex | The row in the combo box or list box containing the data you want to return. Rows in combo and list boxes are indexed starting with zero. For example, to return the item in the sixth row of a combo box, you'd specify 5 for the rowindex argument.

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.


 ItemsSelected Property

ItemsSelected Property

You can use the ItemsSelected property to return a reference to the hidden ItemsSelected collection. This hidden collection can be used to access data in the selected rows of a multiselect 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 two properties, the Count and Item properties.


 KeepTogether Property - Groups

KeepTogether Property — Groups

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 | Visual Basic | Description
No | 0 | (Default) Prints the group without keeping the group header, detail section, and group footer on the same page.
Whole Group | 1 | Prints the group header, detail section, and group footer on the same page.
With First Detail | 2 | Prints the group header on a page only if it can also print the first detail record.

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


 KeepTogether Property - Sections

KeepTogether Property — Sections

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.

Setting | Visual Basic | Description
Yes | True (–1) | 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.
No | False (0) | (Default) Microsoft Access prints as much of the section as possible on the current page and prints the rest on the next page.

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

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.


KeyboardLanguage Property

Language-specific information

You can use the KeyboardLanguage property to specify or determine the keyboard language on entry into a control.

Setting

The KeyboardLanguage uses the following settings.

Setting | Visual Basic | Description
System | 0 | Sets the initial keyboard language to the most recently used keyboard language.
English | 11 | Sets the initial keyboard language to English.
Arabic | 3 | Sets the initial keyboard language to Arabic.
Hebrew | 15 | Sets the initial keyboard language to Hebrew.

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

For more information about right-to-left properties, see Learn more about right-to-left properties in Microsoft Access 2000.


 KeyPreview Property

KeyPreview Property

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 | Visual Basic | Description
Yes | True (–1) | The form receives keyboard events first, then the active control receives keyboard events.
No | False (0) | (Default) Only the active control receives keyboard events.

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.


Kind Property

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:

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.


 LabelAlign, TextAlign Properties

LabelAlign, TextAlign Properties

  • The LabelAlign property specifies the text alignment within attached labels on new controls.

  • The TextAlign property specifies the text alignment in new controls.

Setting

The LabelAlign property uses the following settings.

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.

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.

Setting | Visual Basic | Description
General | 0 | (Default) The text aligns to the left; numbers and dates align to the right.
Left | 1 | The text, numbers, and dates align to the left.
Center | 2 | The text, numbers, and dates are centered.
Right | 3 | The text, numbers, and dates align to the right.

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 Align Left [image] , Center [image] , and Align Right [image] 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.

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. To change the default control style for all new forms or reports that you create without using a Microsoft Access wizard, see Specify a new template for forms and reports.


 LabelX, LabelY Properties

LabelX, LabelY Properties

You can use the LabelX and LabelY properties to change the placement of labels attached to new controls. For example, you might want an attached label to appear to the right of a control instead of to the left.

Setting

Enter a positive or negative number that specifies the distance of label text from the upper-left corner of the label's attached control. To use a unit of measurement different from the setting in the Regional Settings 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.

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.


 LanguageSettings Property (Microsoft Access)

LanguageSettings Property

You can use the LanguageSettings property to return a reference to the current LanguageSettings object and its related properties

Setting

[application.]LanguageSettings[.property]

The ComAddIns property uses the following settings.

Setting | Description
application | The Application object.
LanguageSettings | Required. When used without specifying a method or property, returns the LanguageSettings object.
property | A property of the LanguageSettings object.

The LanguageSettings property is available only by using Visual Basic.

Remarks

Once you establish a reference to the LanguageSettings object, you can access all the properties and methods of the object. You can set a reference to the LanguageSettings object by clicking References on the Tools menu while in module Design view. Then set a reference to the Microsoft Office 9.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 9.0 Object Library constant to set a LanguageSettings object's property or as an argument to a LanguageSettings object's method.


 LayoutForPrint Property

LayoutForPrint Property

You can use the LayoutForPrint property to specify whether the form or report uses printer or screen fonts.

Setting

The LayoutForPrint property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default for reports) Uses printer fonts.
No | False (0) | (Default for forms) Uses screen fonts.

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.


 Left, Top Properties (Microsoft Access)

Left, Top Properties

You can use the Left and Top properties to specify an object's location on a form or report. For example, you might want a control to be always 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.


 LineSlant Property

LineSlant Property

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.

Setting | Visual Basic | Description
\ | False (0) | (Default) Upper left to lower right
/ | True (–1) | Upper right to lower left

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.


 ListCount Property (Microsoft Access)

ListCount Property

You can use the ListCount property to determine the number of rows in a list box or the list box portion of a combo box.

Setting

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.


 LinkChildFields, LinkMasterFields Properties

LinkChildFields, LinkMasterFields Properties

You can use the LinkChildFields and LinkMasterFields properties together to specify how Microsoft Access links records in a form or report to records in a subform, subreport, or embedded object, such as a chart. If these properties are set, Microsoft Access automatically updates the related record in the subform when you change to a new record in a main form.

Setting

You can set the LinkChildFields and LinkMasterFields properties for the subform, subreport, or embedded object as follows:

  • The LinkChildFields property. Enter the name of one or more linking fields in the subform, subreport, or embedded object.

  • 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 [image] 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:

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

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


 LimitToList Property

LimitToList Property

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.

Setting | Visual Basic | Description
Yes | True (–1) | 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.
No | False (0) | (Default) Microsoft Access accepts any text that conforms to the ValidationRule property.

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

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.


 Lines Property

Lines Property

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.

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.

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 string containing the text of the first line in the module.

To insert a line of text into a module, use the InsertLines method.


 LineSpacing Property

LineSpacing Property

You can use the LineSpacing property to specify or determine the location of information displayed within a label or text box control. For example, you might want display information in a text box control with 0.25 inches of space between each line of text within the control.

Setting

A control's displayed information location is the distance measured betwwen each line of the displayed information. 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.

You can set these properties by using the property sheet, a macro, or Visual Basic.


 ListIndex Property (Microsoft Access)

ListIndex Property

You can use the ListIndex property to determine which item is selected in a list box or combo box.

Setting

The ListIndex property is an integer from 0 to the total number of items in a list box or combo box 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.


 ListRows Property

ListRows Property

You can use the ListRows property to set the maximum number of rows to display in the list box portion of a combo box.

Setting

The ListRows property holds an integer that indicates the maximum number of rows to display. The default setting is 8. 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.


 ListWidth Property

ListWidth Property

You can use the ListWidth property to set the width of the list box portion of a combo box.

Setting

The ListWidth property holds 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.


 LocationOfComponents Property

LocationOfComponents Property

You can use the LocationOfComponents property to specify or determine the central URL or path where Microsoft Office controls can be downloaded by authorized users viewing your saved database.

Setting

The LocationOfComponents property is a string expression and is available only by using Visual Basic .

Remarks

The Microsoft Office controls are automatically downloaded with the Web page if the DownloadComponents property is True, the components are not already installed, the path is valid and points to a location that contains the necessary components, and the user has a valid Microsoft Office 2000 license.


 LogMessages Property (Microsoft Access)

LogMessages Property

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 | Visual Basic | Description
Yes | True (–1) | Microsoft Access stores messages returned from the SQL database in a messages table.
No | False (0) | (Default) Microsoft Access doesn't store messages returned from the SQL database.

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.


 lpOLEObject Property

lpOLEObject Property

You can use the lpOLEObject property in Visual Basic to determine the memory address of an OLE object. The lpOLEObject property returns a pointer to IOLEObject.

Setting

You can use the lpOLEObject property to refer to the address of the active OLE object. If no object is displayed, the setting is 0. The lpOLEObject property setting is a Long data type value specified by Microsoft Access.

This property setting isn't available in Design view and is read-only in other views.

Remarks

In the OLE dynamic link libraries (DLLs), many function calls require the address of the OLE object as an argument. You can pass the value specified by the lpOLEObject property when making application programming interface (API) calls to the OLE DLLs.

Note If an API call is made to a function that makes a callback to the control, the results will be unpredictable.


 Major Property

Major Property

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.


 MaxRecButton Property

MaxRecButton Property

You can use the MaxRecButton property to specify or determine if the maximum record limit button is available on the navigation bar of a form in Datasheet view or Form view.

Note This property is only available for forms within a Microsoft Access project (.adp).

Setting

The MaxRecButton property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) The maximum record limit button is available to the user.
No | False (0) | The maximum record limit button is unavailable to the user.

You can set this property by using the property sheet, or Visual Basic.


 MaxRecords Property (Microsoft Access)

MaxRecords Property

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 in an Microsoft Access database (.mdb).

  • A view that returns data from a SQL database in an Access project (.adp).

Setting

The MaxRecords property setting is a Long Integer value representing the number of records that will be returned.

In an Microsoft Access database, 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 ADO 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.


 MDE Property

MDE Property

You can use the MDE property to determine whether a database has been saved as a .mde file.

Note This property is only available with a Microsoft Access database (.mdb)

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


 Me Property

Me Property

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.


 MenuBar Property

MenuBar Property

You can use the MenuBar property to specify the menu bar to use for a Microsoft Access database (.mdb), Access project (.adp), form, or report. You create these menu bars by using the Customize subcommand of the Toolbars command on the View menu. For more information on creating customized toolbars, see Create a custom menu bar for the current database.

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

Note You can switch between a database's custom menu bar and the built-in menu bar by pressing CTRL+F11.


 MinMaxButtons Property

MinMaxButtons Property

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.

Setting | Visual Basic | Description
None | 0 | The Maximize and Minimize buttons aren't visible.
Min Enabled | 1 | Only the Minimize button is visible.
Max Enabled | 2 | Only the Maximize button is visible.
Both Enabled | 3 | (Default) Both the Minimize and Maximize buttons are visible.

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.


 Minor Property

Minor Property

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.


 Modal Property

Modal Property

You can use the Modal property to specify whether a form opens as a modal form. When a form opens as a modal form, you must close the form before you can move the focus to another object.

Setting

The Modal property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The form opens as a modal form in Form view.
No | False (0) | (Default) The form opens as a non-modal form in Form view.

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:

  • Open it in Form view from the Database window.

  • Open it in Form view by using a macro or Visual Basic.

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


 Module Property

Module Property

You can use the Module property to specify a form module or report module.

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.


 Modules Property

Modules Property

You can use the Modules property to access the Modules collection and its related properties.

Setting

This property is available only by using Visual Basic.

Remarks

Use the properties of the Modules collection in Visual Basic to refer to all open standard modules and class modules.


 MousePointer Property

MousePointer Property

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)
7 | Vertical Resize (Size N, S)
9 | Horizontal Resize (Size E, W)
11 | Busy (Hourglass)

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.


MoveLayout, NextRecord, PrintSection Properties

You can use combinations of these property settings in Visual Basic to specify or change a report's layout when the report is previewed, printed, or saved to a file:

  • The MoveLayout property specifies whether Microsoft Access should move to the next printing location on the page.

  • The NextRecord property specifies whether a section should advance to the next record.

  • The PrintSection property specifies whether a section should be printed.

Setting

The MoveLayout property uses the following settings.

Setting | Description
True (–1) | (Default) The section's Left and Top properties are advanced to the next print location.
False (0) | The section's Left and Top properties are unchanged.

The NextRecord property uses the following settings.

Setting | Description
True | (Default) The section advances to the next record.
False | The section doesn't advance to the next record.

The PrintSection property uses the following settings.

Setting | Description
True | (Default) The section is printed.
False | The section isn't printed.

To set these properties, specify a macro or event procedure for a section's OnFormat property.

Microsoft Access sets these properties to True before each section's Format event.

Remarks

These properties are useful when you want to use a report as a template into which you write data from a macro or Visual Basic as you print.

The following table shows the result of different setting combinations for these properties.

MoveLayout | NextRecord | PrintSection | Description
True | True | True | (Default) Move to the next print location, get the next record, and print the data.
True | False | True | Move to the next print location, don't advance to the next record, but print the data. This combination is typically used when the data in a section requires more space than the layout allows and you want to print the remaining data in the space that would otherwise be occupied by the next section.
False | True | False | Skip a record without leaving a blank space on the page.
True | True | False | Skip a record and leave a blank space on the page.
True | False | False | Leave a blank space without skipping a record.
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.


 MultiRow Property

MultiRow Property

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.

Setting | Visual Basic | Description
Yes | True (–1) | Multiple rows are allowed.
No | False (0) | (Default) Multiple rows aren't allowed.

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


 MultiSelect Property

MultiSelect Property

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.

Setting | Visual Basic | Description
None | 0 | (Default) Multiple selection isn't allowed.
Simple | 1 | Multiple items are selected or deselected by clicking them with the mouse or pressing the SPACEBAR.
Extended | 2 | 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.

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

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. In addition, when the MultiSelect property is set to Extended or Simple, 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.


 Name Property (Microsoft Access)

Name Property

You can use the Name property to specify or determine the string expression that identifies the name of a AccessObject object, control, or Reference object.

Setting

A valid name must conform to the object-naming rules for Microsoft Access. For Microsoft Access objects the name may be up to 64 characters long. For controls, the name may be as long as 255 characters.

For objects, 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 object 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 object 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 objects.

You can set this property only in Design view.

Note For a Reference object, this property is read-only in all views.

Remarks

The default name for new objects 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, report, or data access page can't have the same name, but controls on different forms, reports or data access pages can have the same name. A control and a section on the same form can't share the same name.


 NavigationButtons Property

NavigationButtons Property

You can use the NavigationButtons property to specify whether navigation buttons and a record number box are displayed on a form.

Setting

The NavigationButtons property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) The form has navigation buttons and a record number box.
No | False (0) | The form doesn't have navigation buttons or a record number box.

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 owns means of navigation for the form, you can create custom navigation buttons and add them to the form. For more information on creating custom navigation buttons, see Navigate between controls, records, and form pages by using Visual Basic.


 NewRecord Property

NewRecord Property

You can use the NewRecord property to determine whether the current record is a new record.

Setting

The NewRecord property uses the following settings.

Setting | Description
True (–1) | The current record is new.
False (0) | The current record isn't new.

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.


 NewRowOrCol Property

NewRowOrCol Property

You can use the NewRowOrCol property to specify whether a section and its associated data is printed in a new row or column within a multiple-column report 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 | Visual Basic | Description
None | 0 | (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.
Before Section | 1 | 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.
After Section | 2 | 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.
Before & After | 3 | 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.

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.

Sample setting | Result
Before Section | The group header is printed at the top of a new column.
After Section | The detail section is printed at the top of a new column.
Before & After | The group header is printed in a column by itself, and the detail section is printed at the top of a new column.

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.


 NewValues Property

NewValues Property

You can use the NewValues property to specify how AutoNumber fields increment when new records are added to a table.

Note The NewValues property applies only to AutoNumber fields.

Setting

The NewValues property uses the following settings.

Setting | Description
Increment | (Default) AutoNumber field values increment by 1 for new records.
Random | AutoNumber field values are assigned a random Long Integer value for new records.

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.


 NumeralShapes Property

NumeralShapes Property

Language-specific information

You can use the NumeralShapes property to specify or determine numeral shapes to be displayed and printed in a combo box, label, list box, or text box.

Setting

The NumeralShapes property uses the following settings.

Setting | Visual Basic | Description
System | 0 | Numeral shapes determined by the Numeral Shapes system setting.
Arabic | 1 | Arabic digit shapes will be used to display and print numerals.
Hindi | 2 | Hindi digit shapes will be used to display and print numerals.
Context | 3 | Numeral shapes determined by Unicode context rules for adjacent text.

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

For more information about right-to-left properties, see Learn more about right-to-left properties in Microsoft Access 2000.


 Object Properties

Object Properties

The Object properties provide general information about objects contained in the Database window.

Note The Object properties are available for all objects in a Microsoft Access database (.mdb) and only for forms, data access pages, macros, modules, and reports in an Access project (.adp).

Setting

You can view the Object properties, and set the Description or Attributes properties, in the following ways:

  • Click an object in the Database window, and then click Properties [image] on the Database toolbar.

  • Click an object in the Database window, and then click Properties on the View menu.

  • 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 in an Access database (.mdb) by using Visual Basic. The Object properties of an Access project (.adp) are not available 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 for which you can display properties in the Database window are tables, queries, forms, data access pages, reports, macros, and modules. Each class of objects in the database is represented by a separate DAO Document object within the DAO 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, Data Access Pages, 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. 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.
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.


 Object Property

Object Property

You can use the Object property in Visual Basic to return a reference to the ActiveX 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 ActiveX object. You can use the Set statement to assign this ActiveX 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 COM 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.

For information on which properties and methods an ActiveX object supports, see the documentation for the application that was used to create the OLE object.


 ObjectPalette Property

ObjectPalette Property

The ObjectPalette property specifies the palette in the application used to create:

  • An OLE object contained in a bound object frame, chart, or unbound object frame.

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

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.

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


 ObjectVerbs Property

ObjectVerbs Property

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.

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.


 ObjectVerbsCount Property

ObjectVerbsCount Property

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.


 ODBCConnectStr Property

ODBCConnectStr Property

You can use the ODBCConnectStr property in an SQL pass-through query to specify the Open Database Connectivity (ODBC) connection string for the query.

Note The ODBCConnectStr property applies only to pass-through queries.

Setting

Enter the ODBC connection string that defines the connection to the SQL database you want to use.

You can set this property 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 15, "Retrieving and Analyzing Data," in the Microsoft Office 2000/Visual Basic Programer's Guide. For information about how to obtain the Microsoft Office 2000/Visual Basic Programer's Guide, click [image] .


 ODBCTimeout Property (Microsoft Access)

ODBCTimeout Property

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.

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 15, "Retrieving and Analyzing Data," in the Microsoft Office 2000/Visual Basic Programer's Guide. For information about how to obtain the Microsoft Office 2000/Visual Basic Programer's Guide, click [image] .


 OldValue Property

OldValue Property

You can use the OldValue property to determine the unedited value of a bound control.

Setting

The OldValue property contains the unedited data from a bound control and is read-only in all views.

You can access this property only 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:

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 ctlTextbox
End 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.


 OLEClass Property

OLEClass Property

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

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.


 OLEData Property

OLEData Property

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.

Setting | Description
controlname | Required. The name of the unbound object frame control.
OLEData | Required. The data contained in an unbound object frame or ActiveX control.

The OLEData property is available only by using Visual Basic. For ActiveX controls, the OLEData 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


 OLEType Property

OLEType Property

You can use the OLEType property to determine if a control contains an OLE object, and, if so, whether the object is linked or embedded.

Setting

The OLEType property uses the following settings.

Setting | Constant | Description
Linked | acOLELinked (0) | The control contains a linked object. All the object's data is managed by the application that created it.
Embedded | acOLEEmbedded (1) | The control contains an embedded object. All the object's data is managed by Microsoft Access.
None | acOLENone (3) | The control doesn't contain an OLE object.

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.


 OLETypeAllowed Property

OLETypeAllowed Property

You can use the OLETypeAllowed property to specify the type of OLE object a control can contain.

Setting

The OLETypeAllowed property uses the following settings.

Setting | Constant | Description
Linked | acOLELinked (0) | The control can contain only a linked object.
Embedded | acOLEEmbedded (1) | The control can contain only an embedded object.
Either | acOLEEither (2) | (Default) The control can contain either a linked or an embedded object.

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.


 OpenArgs Property

OpenArgs Property

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


 Operator Property (FormatCondition Object)

Operator Property (FormatCondition Object)

You can use the Operator property to return the operator value for the conditional format or data validation of a FormatCondition object.

Setting

The Operator property returns one of the following intrinsic constants.

acBetween (0) | acLessThan (5)
acEqual (2) | acLessThanOrEqual (7)
acGreaterThan (4) | acNotBetween (1)
acGreaterThanOrEqual (6) | acNotEqual (3)

The Operator property is available only by using Visual Basicand is read-only.

Remarks

The Operator property's intrinsic constants are used in conjunction with the Expression1 and Expression2 properties and the Add method of the FormatConditions object for conditional formatting and data validation.


 OptionValue Property

OptionValue Property

Each control in an option group has a numeric value that you can set with the OptionValue property. When the control is selected, the number is assigned to the option group. If the option group is bound to a field, the value of the selected control's OptionValue property is stored in the field.

For example, this Region option group is bound to the Region field in a table. The Europe button has an OptionValue property setting of 1, the Asia button has a setting of 2, and the Africa button has a setting of 3. When one of these buttons is selected, the Region option group value will be the same as the OptionValue property setting for the selected control. In this case, because the Region option group is bound to the Region field, the value of this field in the table also equals 2.

Note The OptionValue property applies only to the check box, option button, and toggle button controls in an option group.

Setting

The OptionValue property holds a Long Integer 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.


 OrderBy Property

OrderBy Property

You can use the OrderBy property to specify how you want to sort records in a form, query, report, or table.

Note In a Microsoft Access project (.adp), this property is ignored. To set the sort order, you must use the ServerFilter property.

Setting

The OrderBy property is a string expression that is the name of the field or fields on which you want to sort records. When you use more than one field name, separate the names with a comma (,).

When you set the OrderBy property by entering one or more field names, the records 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.


 OrderByOn Property

OrderByOn Property

You can use the OrderByOn property to specify whether an object's OrderBy property setting is applied.

Note In a Microsoft Access project (.adp), this property is ignored. To set the sort order, you must use the ServerFilter property.

Setting

The OrderByOn property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The OrderBy property setting is applied when the object is opened.
No | False (0) | (Default) The OrderBy property setting isn't applied when the object is opened.

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.


 OrganizeInFolder Property

OrganizeInFolder Property

You can use the OrganizeInFolder property to specify or determine if all supporting files, such as image files are stored in their own folder or with the data access page.

Setting

The OrganizeInFolder property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) The supporting files are organized in a folder when you save the document as a data access page.
No | False (0) | The supporting files are saved in the same folder as the data access page.

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

Remarks

The new folder is created in the folder where you have saved the Web page, and is named after the document. If long file names are used, a suffix is added to the folder name. The FolderSuffix property returns the folder suffix for the language support you have selected or installed, or the default folder suffix.

If you save a document that was previously saved with the OrganizeInFolder property set to a different value, Microsoft Access automatically moves the supporting files into or out of the folder, as appropriate.

If you don't use long file names (that is, if the UseLongFileNames property is set to False), Microsoft Access automatically saves any supporting files in a separate folder. The files cannot be saved in the same folder as the Web page.


 Orientation Property

Orientation Property

Language-specific information

You can use the Orientation property to specify or determine the view orientation for tables, queries, forms, and reports.

Setting

The Orientation property uses the following settings.

Setting | Visual Basic | Description
Left-to-Right | 0 | Sets the view orientation to left to right.
Right-to-Left | 1 | Sets the view orientation to right to left.

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

Remarks

The Orientation property directly influences how tables and queries are displayed, The appearance of forms and reports is initially determined by the Orientation property, but you can subsequently change controls and the layout of menu bars.


 OutputAllFields Property

OutputAllFields Property

You can use the OutputAllFields property to show all fields in the query's underlying data source and in the field list of a form or report. Setting this property is an easy way to show all fields without having to 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
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.

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.


 Page, Pages Properties

Page, Pages Properties

You can use the Page and Pages properties to return information needed to print page numbers in a form or report. For example, you could use these properties to print "Page n of nn" in the page footer of a report.

  • The Page property specifies the current page number when a form or report is being printed.

  • 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 " & 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).


 PageCount Property

PageCount Property

You can use the PageCount property to determine the number of pages in a snapshot.

Setting

The PageCount property is a Long value representing the number of pages in a snapshot.

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

Remarks

If you try to determine the PageCount property while no valid snapshot file is open, an error occurs.


 PageHeader, PageFooter Properties

PageHeader, PageFooter Properties

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.

Setting | Visual Basic | Description
All Pages | 0 | (Default) The page header or footer is printed on all pages of a report.
Not With Rpt Hdr | 1 | The page header or footer isn't printed on the same page as the report header.
Not With Rpt Ftr | 2 | 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.
Not With Rpt Hdr/Ftr | 3 | 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 footer on a new page.

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.


 PageIndex Property

PageIndex Property

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.


 Painting Property

Painting Property

You can use the Painting property to specify whether forms or reports are repainted.

Setting

The Painting property uses the following settings.

Setting | Description
True (–1) | (Default) The form or report is repainted.
False (0) | The form or report isn't repainted.

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.


 PaintPalette Property

PaintPalette Property

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


 PaletteSource Property

PaletteSource Property

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:

  • .dib (device-independent bitmap file)

  • .pal (Windows palette file)

  • .ico (Windows icon file)

  • .bmp (Windows bitmap file)

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


 Parent Property (Microsoft Access)

Parent Property

You can use the Parent property to refer to the parent of a control, section, or control that contains other controls. The Parent property returns a control object if the parent is a control; it returns a AccessObject object if the parent is an Microsoft Access object.

Setting

The Parent property refers to a AccessObject object 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.


 Path Property

Path Property

You can use the Path property to determine the location where data is stored for a Microsoft Access project (.adp) or Microsoft Access database (.mdb).

Setting

The Path property is a string expression that is the pathname to the disk location where data is stored for an Access database.

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

Remarks

You can use the Path property to determine the location of information stored through the CurrentProject or CodeProject objects of a project or database.


 Picture Property

Picture Property

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:

  • The property sheet. Click the Build button [image] 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).

  • A macro.

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

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


 PictureAlignment Property

PictureAlignment Property

You can use the PictureAlignment property to specify where a background picture will appear in an image control or on a form or report.

Setting

The PictureAlignment property uses the following settings.

Setting | Visual Basic | Description
Top Left | 0 | The picture is displayed in the top-left corner of the image control, Form window, or page of a report.
Top Right | 1 | The picture is displayed in the top-right corner of the image control, Form window, or page of a report.
Center | 2 | (Default) The picture is centered in the image control, Form window, or page of a report.
Bottom Left | 3 | The picture is displayed in the bottom-left corner of the image control, Form window, or page of a report.
Bottom Right | 4 | The picture is displayed in the bottom-right corner of the image control, Form window, or page of a report.
Form Center | 5 | (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.

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.


 PictureData Property

PictureData Property

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.


PicturePages Property

You can use the PicturePages property to specify on which page or pages of a report a picture will be displayed.

Setting

The PicturePages property uses the following settings.

Setting | Visual Basic | Description
All Pages | 0 | (Default) The picture appears on all pages of the report.
First Page | 1 | The picture appears only on the first page of the report.
No Pages | 2 | The picture doesn't appear on the report.

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


PictureSizeMode Property

You can use the PictureSizeMode property to specify how a picture for a form or report is sized.

Setting

The PictureSizeMode property uses the following settings.

Setting | Visual Basic | Description
Clip | 0 | (Default) The picture is displayed in its actual size. If the picture is larger than the form or report, then the picture is clipped.
Stretch | 1 | The picture is stretched horizontally and vertically to fill the entire form, even if its original ratio of height to width is distorted.
Zoom | 3 | The picture is enlarged to the maximum extent possible while keeping its original ratio of height to width.

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.


 PictureTiling Property

PictureTiling Property

You can use the PictureTiling property to specify whether a background picture is tiled across the entire image control, Form window, form, or page of a report.

Setting

The PictureTiling property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The picture is tiled.
No | False (0) | (Default) The picture isn't tiled.

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.


 PictureType Property

PictureType Property

You can use the PictureType property to specify whether Microsoft Access stores an object's picture as a linked or an embedded object.

Setting

The PictureType property uses the following settings.

Setting | Visual Basic | Description
Embedded | 0 | (Default) The picture is embedded in the object and becomes part of the database file.
Linked | 1 | The picture is linked to the object. Microsoft Access stores a pointer to the location of the picture on the disk.

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.


 PopUp Property

PopUp Property

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.

Setting | Visual Basic | Description
Yes | True (–1) | The form opens as a pop-up form in Form view. It remains on top of all other Microsoft Access windows.
No | False (0) | (Default) The form isn't a pop-up form.

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:

  • Open it in Form view from the Database window.

  • Open it in Form view by using a macro or Visual Basic.

  • Switch from Design view to Form view.

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.


 PreviousControl Property

PreviousControl Property

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.


 Primary Property (Microsoft Access)

Primary Property

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 | Visual Basic | Description
Yes | True (–1) | The selected index is the primary key.
No | False (0) | The selected index isn't the primary key.

You can set the Primary property in three ways:

  • In table Design view, select the field or fields in the order you want for the primary key and then click Primary Key [image] on the toolbar.

  • In the Indexes window, select or enter the name of an index in the Index Name column and set the Primary property to Yes in the Index Properties section.

  • In Visual Basic, to access the Primary property of an index, use the ADO PrimaryKey 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.


 PrintCount Property

PrintCount Property

You can use the PrintCount property to identify the number of times the OnPrint property has been evaluated for the current section of a report.

Setting

You can use this property only in a macro or an event procedure specified by a section's OnPrint property setting.

The PrintCount property setting has a Long data type value.

This property isn't available in 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 If
End 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.


 ProcBodyLine Property

ProcBodyLine Property

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:

  • A Sub statement.

  • A Function statement.

  • A Property Get statement.

  • A Property Let statement.

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

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.


 ProcCountLines Property

ProcCountLines Property

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:

  • A Sub statement.

  • A Function statement.

  • A Property Get statement.

  • A Property Let statement.

  • A Property Set statement.

Setting

object.ProcCountLines(procname, prockind)

The ProcCountLines 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.
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.

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

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.


 ProcOfLine Property

ProcOfLine Property

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:

  • A Sub statement.

  • A Function statement.

  • A Property Get statement.

  • A Property Let statement.

  • A Property Set statement.

Setting

object.ProcOfLine(line, pprockind)

The ProcOfLine property uses the following settings.

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

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.


 ProcStartLine Property

ProcStartLine Property

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:

  • A Sub statement.

  • A Function statement.

  • A Property Get statement.

  • A Property Let statement.

  • A Property Set statement.

Setting

object.ProcStartLine(procname, prockind)

The ProcStartLine 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.
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.

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

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

  • The ProcStartLine property treats Sub and Function procedures similarly, but distinguishes between each type of Property procedure.


 ProductCode Property

ProductCode Property

You can use the ProductCode property to determine the Microsoft Access globally unique identifier (GUID).

Setting

The ProductCode property is a string expression that is the GUID of the Microsoft Access product.

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


 ProjectName Property

ProjectName Property

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

You can set the ProjectName property on the Advanced tab of the Options dialog box (available 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 String
strLastName = 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.


 ProjectType Property

ProjectType Property

You can use the ProjectType property to determine the type of project that is currently open through the CurrentProject or CodeProject objects.

Setting

The ProjectType property returns one of the following intrinsic constants.

acADP (1) | acNull (0)
acMDB (2) |

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


 Properties Property

Properties Property

You can use the Properties property to return a reference to a control's Properties collection object.

Note In Microsoft Access 2000, the Properties property has been replaced by the Properties property (Properties Collection) and the Properties property (AccessObjectProperties Collection). The Properties property is included in this version of Microsoft Access only for compatibility with previous versions.

Setting

controlname.Properties[.method or property]

The Properties property uses the following settings.

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.

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.


Properties Property (AccessObjectProperties Collection)

You can use the Properties property to return a reference to an AccessObject, CurrentProject, or CodeProject object's AccessObjectProperties collection.

Setting

The AccessObjectProperties property is available only by using Visual Basic.

Remarks

The AccessObjectProperties collection object is the collection of all the properties related to an AccessObject, CurrentProject, or CodeProject object. 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 AccessObjectProperties collection's Count property minus 1.


 Properties Property (Properties Collection)

Properties Property (Properties Collection)

You can use the Properties property to return a reference to a form, report or control's Properties collection.

Setting

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

Remarks

The Properties collection object is the collection of all the properties related to a form, report, or 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 last member object in the collection has an index value that is the Properties collection's Count property minus 1.


 PrtDevMode Property

PrtDevMode Property

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.
SpecVersion | An Integer that specifies the version number of the DEVMODE structure in the Win32 Software Development Kit.
DriverVersion | An Integer that specifies the printer driver version number assigned by the printer driver developer.
Size | An Integer that specifies the size, in bytes, of the DEVMODE structure. (This value doesn't include the optional dmDriverData member for device-specific data, which can follow this structure.) If an application manipulates only the driver-independent portion of the data, you can use this member to find out the length of this structure without having to account for different versions.
DriverExtra | An Integer that specifies the size, in bytes, of the optional dmDriverData member for device-specific data, which can follow this structure. If an application doesn't use device-specific information, you set this member to 0.
Fields | A Long value that specifies which of the remaining members in the DEVMODE structure have been initialized. It can be any combination of specific constants or none of them. For available constants, see the Fields member constants.
Orientation | An Integer that specifies the orientation of the paper. It can be either 1 (portrait) or 2 (landscape).
PaperSize | An Integer that specifies the size of the paper to print on. 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 the PaperSize member values.
PaperLength | An Integer that specifies the paper length in units of 1/10 of a millimeter. This member overrides the paper length specified by the PaperSize member for custom paper sizes or for devices such as dot-matrix printers that can print on a variety of paper sizes.
PaperWidth | An Integer that specifies the paper width in units of 1/10 of a millimeter. This member overrides the paper width specified by the PaperSize member.
Scale | An Integer that specifies the factor by which the printed output will be scaled. The apparent page size is scaled from the physical page size by a factor of scale/100. For example, a piece of paper measuring 8.5 by 11 inches (letter-size) with a Scale value of 50 would contain as much data as a page measuring 17 by 22 inches because the output text and graphics would be half their original height and width.
Copies | An Integer that specifies the number of copies printed if the printing device supports multiple-page copies.
DefaultSource | An Integer that specifies the default bin from which the paper is fed. For available values, see the DefaultSource member values.
PrintQuality | An Integer that specifies the printer resolution. The values are –4 (high), –3 (medium), –2 (low), and –1 (draft).
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.
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.

You can set the PrtDevMode property using Visual Basic.

This property setting is read/write in Design view and read-only in other views.

Caution Printer drivers can add device-specific data immediately following the 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.


PrtDevNames Property

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:".
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.

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.


 PrtMip Property

PrtMip Property

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.

Member | Description
LeftMargin, RightMargin, TopMargin, BottomMargin | A Long that specifies the distance between the edge of the page and the item to be printed in twips.
DataOnly | A Long 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 | A Long 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 | A Long that specifies the horizontal space between detail sections in units of 1/20 of a point.
ColumnSpacing | A Long that specifies the vertical space between detail sections in twips.
DefaultSize | A Long. 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 | A Long 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 | A Long 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.
ItemLayout | A Long 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.

The PrtMip property setting is read/write in Design view and read-only in other views.


ReadingOrder Property

Language-specific information

You can use the ReadingOrder property to specify or determine the reading order of words in text.

Setting

The ReadingOrder property uses the following settings.

Setting | Visual Basic | Description
Context | 0 | Reading order is determined by the language of the first character entered. If a right-to-left language character is entered first, reading order is right to left. If a left-to-right language character is entered first, reading order is left to right.
Left-to-Right | 1 | Sets the reading order to left to right.
Right-to-Left | 2 | Sets the reading order to right to left.

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

Remarks

In a combo box or list box, the ReadingOrder property determines reading order behavior for both the text box and list box components of the control.

For more information about right-to-left properties, see Learn more about right-to-left properties in Microsoft Access 2000.


 ReadyState Property

ReadyState Property

You can use the ReadyState property to determine the status of the file being loaded into a snapshot control.

Setting

The ReadyState property is an Integer value representing the loading status of a snapshot file.

Setting | Description
0 | The snapshot control has not been initialized.
1 | The snapshot control is loading.
2 | The snapshot control is loaded, but the snapshot file is being downloaded.
4 | The snapshot control has finished downloading the snapshot file.

The ReadyState property is available only by using Visual Basic.

Remarks

If the SnapshotPath property has been set using the control's property sheet, then the ReadyState property will always be at least 2 even if the SnapshotPath property is later set to a zero-length string programmatically.

This property is useful when the SnapshotPath property contains an HTTP or FTP address to a snapshot file. In this case, the file is downloaded asynchronously and you can use the ReadyState property to determine when the download is complete and the snapshot is displayed.


 RecordLocks Property

RecordLocks Property

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.

  • Forms. Specifies how records in the underlying table or query are locked when data in a multiuser database is updated.

  • Reports. Specifies whether records in the underlying table or query are locked while a report is previewed or printed.

  • Queries. Specifies whether records in a query (typically an action query in a multiuser database) are locked while the query is run.

Note The RecordLocks property only applies to forms, reports, or queries in a Microsoft Access database (.mdb).

Setting

The RecordLocks property uses the following settings.

Setting | Visual Basic | Description
No Locks | 0 | (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.
All Records | 1 | 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.
Edited Record | 2 | (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 user at a time. This is also called "pessimistic" locking.

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

Note Changing the RecordLocks property of an open form or report causes an automatic recreation of the recordset.

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 [image] 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

RecordSelectors Property

You can use the RecordSelectors property to specify whether a form displays record selectors in Form view.

Setting

The RecordSelectors property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) Each record has a record selector.
No | False (0) | No record has a record selector.

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 [image] 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.


 Recordset Property

Recordset Property

You can use the Recordset property to specify or retrieve the ADO Recordset or DAO Recordset object representing a form's record source.

Note You cannot use this property with ODBCDirect recordset types in DAO.

Setting

The Recordset property returns the recordset object that provides the data being browsed in a form. If a form is based on a query, for example, referring to the Recordset property is the equivalent of cloning a Recordset object by using the same query. However, unlike using the RecordsetClone property, currency changes made to the Form.Recordset property are automatically reflected in the current record of the form.

This property is available only by using Visual Basic.

Remarks

When a recordset is asked for in a Microsoft Access database (.mdb), a DAO recordset is returned, in a Microsoft Access project (.adp), an ADO recordset is returned.

The read/write behavior of a form whose Recordset property has been set using Visual Basic is determined by the type of recordset (ADO or DAO) and the type of data (Jet or SQL) contained in the recordset identified by the property.

Recordset type | Based on SQL data | Based on Jet data
ADO | Read/Write (1) | Read Only
DAO | N/A | Read/Write

(1) Note The ADO Recordset.CursorLocation property must be set to adUseClient. The UniqueTable property is available in client/server on the property sheet, but not for Access databases (.mdb). This property must be set in Visual Basic code.

Global rstSuppliers As ADODB.Recordset
Sub MakeRW()
    DoCmd.OpenForm "Suppliers"
    Set rstSuppliers = New ADODB.Recordset
    rstSuppliers.CursorLocation = adUseClient
    rstSuppliers.Open "Select * From Suppliers", CurrentProject.Connection, adOpenKeyset, adLockOptimistic
    Set Forms("Suppliers").Recordset = rstSuppliers
    Forms("Suppliers").UniqueTable = "Suppliers"
End Sub

You use the Recordset property:

  • To bind multiple forms to a common data set. This allows the synchronizing of multiple forms. For example
    Set Me.Recordset = Forms!Form1.Recordset

  • To use methods on the Recordset object that aren't directly supported on forms. For example, you can use the Recordset property when you want to use the ADO Find method or DAO Find methods to use a custom dialog for finding a record.

  • To wrap a transaction (which can be rolled back) around a set of edits that affect multiple forms.

When a new Recordset object is opened, its first record is the current record.

ADO methods and properties | DAO methods and properties
Find, Move or other Move methods | FindFirst, FindNext, FindLast, FindPrevious, Move or other Move methods.

Note If you change the form's RecordSource property, you must use the Set statement. Changing a form's Recordset property may also change the RecordSource, RecordsetType, and RecordLocks properties. Also, some data-related properties may be overridden; for example, the Filter, FilterOn, OrderBy, and OrderByOn properties.


 RecordsetClone Property

RecordsetClone Property

You can use the RecordsetClone property to refer to a form's Recordset object specified by the form's RecordSource property.

Setting

The RecordsetClone property setting is a copy of the underlying query or table specified by the form's RecordSource property. If a form is based on a query, for example, referring to the RecordsetClone property is the equivalent of cloning a Recordset object 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

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 DAO Find methods, that can't be used with forms.

When a new Recordset object is opened, its first record is the current record. If you one of the Find method or one of the 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.MoveLast
MsgBox "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.


 RecordsetType Property

RecordsetType Property

You can use the RecordsetType property to specify what kind of recordset is made available to a form. For example, if you don't want data in bound controls to be edited when a form is in Form view or Datasheet view, you can set the RecordsetType property to Snapshot.

Setting

The RecordsetType property uses the following settings in a Microsoft Access database (.mdb).

Setting | Visual Basic | Description
Dynaset | 0 | (Default) You can edit bound controls based on a single table or tables with a one-to-one relationship. For controls bound to fields based on tables with a one-to-many relationship, you can't edit data from the join field on the "one" side of the relationship unless cascade update is enabled between the tables. For more information, see the topic that explains when you can update records from a query.
Dynaset (Inconsistent Updates) | 1 | All tables and controls bound to their fields can be edited.
Snapshot | 2 | No tables or the controls bound to their fields can be edited.

The RecordsetType property uses the following settings in a Microsoft Access project (.adp).

Setting | Visual Basic | Description
Snapshot | 3 | No tables or the controls bound to their fields can be edited.
Updatable Snapshot | 4 | (Default) All tables and controls bound to their fields can be edited.

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

Note Changing the RecordsetType property of an open form or report causes an automatic recreation of the recordset.

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.


 RecordSource Property

RecordSource Property

You can use the RecordSource property to specify the source of the data for a form or report. You can display data from a table, query, or SQL statement. For example, to display and edit data from the Employees table in a form, you set the form's RecordSource property to Employees. Then you can bind controls on the form or report to specific fields in the Employees table by setting the control's ControlSource property to the name of a field in the table. 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.

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.

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. If a form's Recordset property is set at runtime, the form's RecordSource property is updated.

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.


References Property

You can use the References property to access the References collection and its related properties, methods, and events.

Setting

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

Remarks

The References collection corresponds 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.


RepeatSection Property

You can use the RepeatSection property to specify whether a group header is repeated on the next page or column when a group spans more than one page or column.

Note The RepeatSection property only applies to group headers on a report.

Setting

The RepeatSection property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The group header is repeated.
No | False (0) | (Default) The group header isn't repeated.

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.


 ReplicationConflictFunction Property

ReplicationConflictFunction Property

The ReplicationConflictFunction property enables you to use custom conflict resolution code for resolving data conflicts that occur between replicas upon synchronization. When you set this property, Microsoft Access calls your conflict resolution function, rather than the 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.


 Reports Property

Reports Property

You can use the Reports property to access the Reports collection and its related properties.

Setting

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

Remarks

The Reports collection contains all of the currently open reports in a Microsoft Access database (.mdb) or Microsoft Access project (.adp).


 Required Property (Microsoft Access)

Required Property

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 | Visual Basic | Description
Yes | True (–1) | The field requires a value.
No | False (0) | (Default) The field doesn't require a value.

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 ENTER Presses SPACEBAR Enters a zero-length string | Null Null (not allowed)
No | Yes | Presses ENTER Presses SPACEBAR Enters a zero-length string | Null Null Zero-length string
Yes | No | Presses ENTER Presses SPACEBAR Enters a zero-length string | (not allowed) (not allowed) (not allowed)
Yes | Yes | Presses ENTER Presses SPACEBAR Enters a zero-length string | (not allowed) Zero-length string Zero-length string

If you set the Required property to Yes for a field in a table that already contains data, Microsoft Access gives you the option 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.


 ResyncCommand Property

ResyncCommand Property

You can use the ResyncCommand property to specify or determine the SQL statement or stored procedure that will be used in an updateable snapshot of a table.

Setting

The ResyncCommand property is a string expression representing a SQL statement or stored procedure that is parameterized by the key columns from the Unique Table in the output cursor, using ? as parameter markers.

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

Remarks

The parameters must match in number and ordering to the set of key columns for the table identified by the UniqueTable property. The purpose of the ResyncCommand property is to pull in the "fixed up" values of a row in a recordset after an update has been made, including an update to a join column. For an example, see item #1 in the example topic.

For data access pages and for forms based on views or non-parameterized SQL queries containing a join, if the ResyncCommand property is null, Microsoft Access determines an appropriate query to use for the resync operation. For data access pages and forms based on stored procedures or parameterized SQL statements, Access cannot determine an appropriate resync query at run time, so the user must supply the ResyncCommand string in order to get the correct row fix up behavior. If the ResyncCommand property is empty and Access cannot determine an appropriate query to use, the default ADO resync operation (to display the current values) occurs after an update or insert.


 ReturnsRecords Property (Microsoft Access)

ReturnsRecords Property

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.

Setting

The ReturnsRecords property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) The query returns records (as a select query does).
No | False (0) | The query doesn't return records (as an action query does).

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.


 RowHeight Property

RowHeight Property

You can use the RowHeight property to specify the height of all rows in Datasheet view.

Note The RowHeight property applies to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

You 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 (–1).


 RowSourceType, RowSource Properties

RowSourceType, RowSource Properties

You can use the RowSourceType and RowSource properties together to tell Microsoft Access how to provide data to a list box, a combo box, or an unbound OLE object such as a chart. For example, to display rows of data in a list box from a query named CustomerList, set the list box's RowSourceType property to Table/Query and its RowSource property to the query named CustomerList.

Setting

The RowSourceType property uses the following settings.

Setting | Description
Table/Query | (Default) The data is from a table, query, or SQL statement specified by the RowSource setting.
Value List | The data is a list of items specified by the RowSource setting.
Field List | The data is a list of field names from a table, query, or SQL statement specified by the RowSource setting.

Note You can also set the RowSourceType property with a user-defined function. The function name is entered without a preceding equal sign (=) and without the trailing pair of parentheses. You must provide specific function code arguments to tell Microsoft Access how to fill the control.

The RowSource property setting depends on the RowSourceType property setting.

For this RowSourceType setting | Enter this RowSource setting
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.

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.


 RunningSum Property

RunningSum Property

You can use the RunningSum property to calculate record-by-record or group-by-group totals in a report. The RunningSum property specifies whether a text box on a report displays a running total and lets you set the range over which values are accumulated. For example, 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.

Setting | Visual Basic | Description
No | 0 | (Default) The text box displays the data from the underlying field for the current record.
Over Group | 1 | The text box displays a running sum of values in the same group level. The value accumulates until another group level section is encountered.
Over All | 2 | The text box displays a running sum of values in the same group level. The value accumulates until the end of the report.

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.

You can have up to 10 nested group levels in a report.


 ScaleHeight, ScaleWidth Properties

ScaleHeight, ScaleWidth Properties

You can use the ScaleHeight and ScaleWidth properties to specify the number of units for the vertical or horizontal measurement of the page when the Circle, Line, Pset, or Print method is used while a report is printed or previewed, or its output is saved to a file.

Setting

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

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

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:

  • Setting any other Scale property to any value automatically sets the ScaleMode property to 0.

  • Setting the ScaleMode property to a number greater than 0 changes 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.


 ScaleLeft, ScaleTop Properties

ScaleLeft, ScaleTop Properties

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

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

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

  • Setting any other Scale property to any value automatically sets the ScaleMode property to 0.

  • Setting the ScaleMode property to a number greater than 0 changes 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.


 ScaleMode Property

ScaleMode Property

You can use the ScaleMode property in Visual Basic to specify the unit of measurement for coordinates on a page when the Circle, Line, Pset, or Print method is used while a report is previewed or printed, or its output is saved to a file.

Setting

The ScaleMode property uses the following settings.

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

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:

  • Setting any other Scale property to any value automatically sets the ScaleMode property to 0.

  • Setting the ScaleMode property to a number greater than 0 changes 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.


 Screen Property

Screen Property

You can use the Screen property to return a reference the Screen object and its related properties.

Setting

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

Remarks

Use the Screen object to refer to a particular form, report, or control that has the focus.


 ScreenTip Property

ScreenTip Property

You can use the ScreenTip property to specify or determine the text that is displayed when you move the cursor over a hyperlink control.

Setting

The ScreenTip property is a string expression displayed as a screen tip.

You can set the HyperlinkSubAddress property with the SubAddress property by using Visual Basic.

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

Remarks

When you move the cursor over a hyperlink control whose HyperlinkSubAddress property is set, Microsoft Access changes the cursor to an upward-pointing hand and displays the text string defined by the ScreenTip property. Clicking the control displays the object or Web page specified by the link.

For more information about hyperlink addresses and their format, see the HyperlinkAddress and HyperlinkSubAddress property topics.


ScrollBarAlign Property

Language-specific information

You can use the ScrollBarAlign to specify or determine the alignment of a vertical scroll bar.

Setting

The ScrollBarAlign property uses the following settings.

Setting | Visual Basic | Description
System | 0 | Vertical scroll bar is placed on the left if the form or report Orientation property is right to left; and on the right if the form or report Orientation property is left to right.
Right | 1 | Aligns vertical scroll bar on the right side of the control.
Left | 2 | Aligns vertical scroll bar on the left side of the control.

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

Remarks

For combo and list boxes, ScrollBarAlign also controls the placement of the box button above the scroll bar.

For more information about right-to-left properties, see Learn more about right-to-left properties in Microsoft Access 2000.


 ScrollBars Property

ScrollBars Property

You can use the ScrollBars property to specify whether scroll bars appear on a form or in a text box control.

Setting

The ScrollBars property uses the following settings.

Setting | Visual Basic | Description
Neither (forms) None (text boxes) | 0 | (Default for text boxes) No scroll bars appear on the form or text box.
Horizontal Only (forms) | 1 | Horizontal scroll bar appears on the form. Not applicable to text boxes.
Vertical Only (forms) Vertical (text boxes) | 2 | Vertical scroll bar appears on the form or text box.
Both (forms) | 3 | (Default for forms) Vertical and horizontal scroll bars appear on the form. Not applicable to text boxes.

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.


 Section Property

Section Property

You can use the Section property to identify a section of a form or report and provide access to the properties of that section. You can also identify controls by the section of a form or report where the control appears.

Setting

The Section property is an Integer data type value corresponding to a particular section. 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)
8 | acGroupLevel2Footer | Group-level 2 footer section (reports only)

If a report has additional group-level sections, the header/footer pairs are numbered consecutively beginning with 9.

The Section property is read-only in all views.

For forms and reports, the Section property is an array of all existing sections in the form or report specified by the section number. For example, Section(0) refers to a form's detail section and Section(3) refers to a form's 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).Visible
Forms!Customers.Section(0).Visible
Forms!Customers.Detail0.Visible

Remarks

For forms and reports, you must combine the Section property with other properties that apply to form or report sections. The following example shows how to refer to the Visible property of the page header section of the Customers form.

Forms!Customers.Section(acPageHeader).Visible
Forms!Customers.Section(3).Visible

For controls, you can use the Section property to determine which section of a form or report a control is in. The following example uses the Section property to determine which section contains the CustomerID control.

Dim intSectionNumber As Integer
intSectionNumber = Forms!Customers!CustomerID.Section


 Selected Property

Selected Property

You can use the Selected property in Visual Basic to determine if an item in a list box is selected.

Setting

The Selected property is a zero-based array that contains the selected state of each item in a list box.

Setting | Description
True (–1) | The list box item is selected.
False (0) | The list box item isn't selected.

You can get or set the Selected property 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


 SelHeight, SelWidth Properties

SelHeight, SelWidth Properties

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

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

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


 SelTop, SelLeft Properties

SelTop, SelLeft Properties

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

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

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


 SelLength, SelStart, SelText Properties

SelLength, SelStart, SelText Properties

You can use these properties for tasks such as positioning the insertion point, establishing an insertion range, selecting parts of strings in a text box or combo box control, and deleting text.

  • The SelLength property specifies or determines the number of characters selected in a text box or the text box portion of a combo box.

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

  • The SelText property returns a string containing the selected text. If no text is selected, the SelText property contains a Null value.

Setting

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

  • The SelText property uses a string expression that contains the text selected in the 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.


 ServerFilter Property

ServerFilter Property

You can use the ServerFilter property to specify a subset of records to be displayed when a server filter is applied to a form or report within a Microsoft Access project (.adp) or a data access page in a Microsoft Access project (.adp) or database (.mdb).

Setting

The ServerFilter property is a string expression consisting of a WHERE clause without the WHERE keyword. For example, the following Visual Basic code defines and applies a filter to show only customers from the USA:

Me.ServerFilter = "Country = 'USA'"
Me.ServerFilterByForm = True

The easiest way to set this property is by using a form or report's property sheet. You can also set this property on a form or report by using Visual Basic.

To set the ServerFilter property, you must first either:

  • Set the property value in the form's property sheet.

  • Set the property in Visual Basic by typing
    Forms(0).ServerFilter = "fieldname = value"

Note Setting the ServerFilter property has no effect on the ADO Filter property.

Remarks

You can use the ServerFilter property to save a filter and apply it at a later time. Filters are saved with the objects in which they are created. They are automatically loaded when the object is opened, but they aren't automatically applied.

To apply a saved filter to a form, you can click Apply Server Filter [image] on the toolbar, click Apply Filter/Sort on the Records menu, or use a macro or Visual Basic to set the ServerFilterByForm property to True (–1).

The Apply Server Filter button indicates the state of the ServerFilter and ServerFilterByForm properties. The button remains disabled until there is a filter to apply. If an existing filter is currently applied, the Apply Server Filter button appears pressed in.

To apply a filter automatically when a form is opened, specify in the OnOpen event property setting of the form either a macro that uses the ApplyFilter action or an event procedure that uses the ApplyFilter method of the DoCmd object. In either case, the form opens in the Server Filter By Form window.

You can only remove a server filter by using Visual Basic to set the ServerFilterByForm property to False (0) or clear all filter criteria in the Server Filter By Form window and then click Apply Server Filter.

When the ServerFilter property is set in form Design view, Microsoft Access does not attempt to validate the SQL expression. If the SQL expression is invalid, an error occurs when the filter is applied.

Notes

  • When a new object is created, it inherits the RecordSource, Filter, ServerFilter, OrderBy, and OrderByOn properties of the table or query it was created from.

  • The ServerFilter property setting is ignored if the form's record source is a stored procedure.


 ServerFilterByForm Property

ServerFilterByForm Property

You can use the ServerFilterByForm property to specify or determine whether a form is opened in the Server Filter By Form window.

Setting

The ServerFilterByForm property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The form is opened in the Server Filter By Form window.
 |  | Note When the ServerFilterByForm property is True, the Filter By Form feature is disabled.
No | False (0) | (Default) The form is not opened in the Server Filter By Form window.

The easiest way to set the ServerFilterByForm property is by using a form's property sheet. You can set this property by using Visual Basic.

To set the ServerFilterByForm property, you must first either:

  • Set the property in the form's property sheet.

  • Set the property in Visual Basic by typing
    Forms(0).ServerFilterByForm = True

If the ServerFilter property has been set, you can also set this property by clicking Apply Server Filter [image] on the Form View toolbar or the Filter/Sort toolbar.

Remarks

To apply a saved filter to a form, press the Apply Server Filter button, or apply the filter by using a macro or Visual Basic by setting the ServerFilterByForm property to True (-1).

The Apply Server Filter button indicates the state of the ServerFilter and ServerFilterByForm properties. The button remains disabled until there is a filter to apply. If an existing filter is currently applied, the Apply Server Filter button appears pressed in. To apply a filter automatically when a form opened, specify in the OnOpen event property setting of the form either a macro that uses the ApplyFilter action or an event procedure that uses the ApplyFilter method of the DoCmd object.

You can remove a filter by using Visual Basic to set the ServerFilterByForm property to False (0) or clear all filter criteria in the Server Filter By Form window and then click Apply Server Filter.

Notes

  • When a new object is created, it inherits the RecordSource, Filter, ServerFilter, 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.

  • The ServerFilterByForm property setting is ignored if the form's record source is a stored procedure.


 ShortcutMenu Property

ShortcutMenu Property

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 commands on the form's shortcut menu.

Setting

The ShortcutMenu property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) Shortcut menus are displayed.
No | False (0) | Shortcut menus aren't displayed.

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.


 ShortcutMenuBar Property

ShortcutMenuBar Property

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. For more information about creating custom toolbars, see Create a custom shortcut menu for the current database.

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 versions of Microsoft Access prior to Microsoft Access 97, 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 2000. 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 (0).


 ShowNavigationButtons Property

ShowNavigationButtons Property

You can use the ShowNavigationButtons property to specify or determine whether navigation buttons are available in the Snapshot Viewer control.

Setting

The ShowNavigationButtons property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) The control's navigation buttons are displayed.
No | False (0) | The control's navigation buttons are not displayed.

You can set the ShowNavigationButtons property by using the control's property sheet or Visual Basic.

Remarks

When this property is set to No, the only way to navigate between pages in a snapshot is by using the snapshot control's pop-up menu or by setting the CurrentPage property using Visual Basic for Applications.


 SizeMode Property

SizeMode Property

You can use the SizeMode property to specify how to size a picture or other object in a bound object frame, an unbound object frame, or an image control.

Setting

The SizeMode property uses the following settings.

Setting | Visual Basic | Description
Clip | acOLESizeClip (0) | (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.
Stretch | acOLESizeStretch (1) | Sizes the object to fill the control. This setting may distort the proportions of the object.
Zoom | acOLESizeZoom (3) | 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.

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.


 SnapshotPath Property

SnapshotPath Property

You can use the SnapshotPath property to specify or determine the path to the snapshot file to be displayed in the Snapshot Viewer control.

Setting

The SnapshotPath property is a String value representing the fully qualified path and file name to the snapshot file to be displayed in the control. The property can be set to the name of a snapshot file on a local computer, a file on a network, or a file located on at an HTTP or FTP address.

You can set the SnapshotPath property by using the control's property sheet or Visual Basic.

Remarks

If you set the SnapshotPath property to a zero-length string or the name of a nonexistent file, then nothing is displayed in the control. If you set this property to the name of a file that is not a snapshot file, then a snapshot file icon with a red "X" is displayed in the control.

Because the control supports HTTP and FTP addresses, the control may not know if the SnapshotPath property is valid at the time it is set. You can use the ReadyState property to determine if a valid snapshot file has been loaded into the control.


 SortOrder Property

SortOrder Property

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.

Setting | Visual Basic | Description
Ascending | False (0) | (Default) Sorts values in ascending (A to Z, 0 to 9) order.
Descending | True (–1) | Sorts values in descending (Z to A, 9 to 0) order.

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.


 Source Property (Microsoft Access)

Source Property

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 ADO Connect property. | dBASE IV;DatabaseTable=C:\DBDATA
SQL Server (ODBC) The name of the source database and any additional information required by the product, such as a logon identification (ID) and password. You can also use the ODBC Connection String Builder to create the connection string. ODBC;DSN=salessrv;UID=jace;
PWD=password;DATABASE=sales;

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


 SourceConnectStr, SourceDatabase Properties

SourceConnectStr, SourceDatabase Properties

You can use these properties to access external data when you can't link the external tables to your database.

  • The SourceConnectStr property specifies the name of the application used to create an external database.

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

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

  • 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 ADO Connect property.

  • 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
FROM Customer INNER JOIN Orders
ON Customer.CUSTOMERID = Orders.CUSTOMERID
IN 'C:\Dbdata'[dBASE IV;];

  • For an Open Database Connectivity (ODBC) database, the SourceConnectStr property setting is the name of the source database and any additional information required by the product, such as a logon identification (ID) and password. For example, for a Microsoft SQL Server database the setting might be:
    ODBC;DSN=salessrv;UID=jace;PWD=password;DATABASE=sales;

The SourceDatabase property doesn't have a value for an ODBC database.

For more information about accessing data in ODBC databases, see Chapter 15, "Retrieving and Analyzing Data," in the Microsoft Office 2000/Visual Basic Programmer's Guide. For information about how to obtain the Microsoft Office 2000/Visual Basic Programmer's Guide, click [image] .


 SourceDoc Property

SourceDoc Property

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:

"C:\Work\Qtr1\Revenue.xls!R1C1:R30C15"


 SourceItem Property

SourceItem Property

You can use the SourceItem property to specify the data within a file to be linked when you create a linked OLE object.

Setting

You can set the SourceItem property by specifying data in units recognized by the application supplying the object. For example, when you link to Microsoft Excel, you specify the SourceItem property setting 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.


 SourceObject Property

SourceObject Property

You can use the SourceObject property to identify the form or report that is the source of the subform or subreport on a form or report. You can also use this property for linked unbound object frames to determine the complete path and 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.


 SpecialEffect Property

SpecialEffect Property

You can use the SpecialEffect property to specify whether special formatting will apply to a section or control.

Setting

The SpecialEffect property uses the following settings.

Setting | Example | Visual Basic | Description
Flat |  | 0 | The object appears flat and has the system's default colors or custom colors that were set in Design view.
Raised |  | 1 | The object has a highlight on the top and left and a shadow on the bottom and right.
Sunken |  | 2 | The object has a shadow on the top and left and a highlight on the bottom and right.
Etched |  | 3 | The object has a sunken line surrounding the control.
Shadowed |  | 4 | The object has a shadow below and to the right of the control.
Chiseled |  | 5 | The object has a sunken line below the control.

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.


 StartupForm Property

StartupForm Property

You can use the StartupForm property to specify the name of the form that opens when your database first opens. For example, you can use this property to display a specified form that contains a menu of all available forms, queries, and reports within a Microsoft Access application when the database opens.

Setting

The StartupForm property is a string expression that'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 in the following ways:

  • In a Microsoft Access database (.mdb), you can add it by using the CreateProperty method and append it to the Properties collection of the Database object.

  • In a Microsoft Access project (.adp), you can add it to the AccessObjectProperties collection of the CurrentProject object by using the Add method.

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.


 StartupMenuBar Property

StartupMenuBar Property

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 or create the property in the following ways:

  • In a Microsoft Access database (.mdb), you can add it by using the CreateProperty method and append it to the Properties collection of the Database object.

  • In a Microsoft Access project (.adp), you can add it to the AccessObjectProperties collection of the CurrentProject object by using the Add method.

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.

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


 StartupShortcutMenuBar Property

StartupShortcutMenuBar Property

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 in the following ways:

  • In a Microsoft Access database (.mdb), you can add it by using the CreateProperty method and append it to the Properties collection of the Database object.

  • In a Microsoft Access project (.adp), you can add it to the AccessObjectProperties collection of the CurrentProject object by using the Add method.

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


 StartupShowDBWindow Property

StartupShowDBWindow Property

You can use the StartupShowDBWindow property to specify whether or not the Database window is displayed when your application database opens. For example, you can open a main form when your application database opens and hide the Database window.

Setting

The StartupShowDBWindow property uses the following settings.

Setting | Description
True (–1) | Display the Database window at startup.
False (0) | Don't display the Database window at startup.

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. ou 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 in the following ways:

  • In a Microsoft Access database (.mdb), you can add it by using the CreateProperty method and append it to the Properties collection of the Database object.

  • In a Microsoft Access project (.adp), you can add it to the AccessObjectProperties collection of the CurrentProject object by using the Add method.

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.

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.


 StartupShowStatusBar Property

StartupShowStatusBar Property

You can use the StartupShowStatusBar property to specify whether or not the status bar should appear when the application database opens. For example, you can use the StartupShowStatusBar property to prevent display of the status bar if you 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.

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 in the following ways:

  • In a Microsoft Access database (.mdb), you can add it by using the CreateProperty method and append it to the Properties collection of the Database object.

  • In a Microsoft Access project (.adp), you can add it to the AccessObjectProperties collection of the CurrentProject object by using the Add method.

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.


 StatusBarText Property

StatusBarText Property

You can use the StatusBarText property to specify the text that is displayed in the status bar when a control is selected.

Note The StatusBarText property applies only to controls on a form, not controls on a report.

Setting

You set the StatusBarText property by using a string expression up to 255 characters long.

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.


 Style Property (Microsoft Access)

Style Property

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.

Setting | Visual Basic | Description
Tabs | acTabs | (Default) Tabs appear as tabs.
Buttons | acButtons | Tabs appear as buttons.
None | acNone | No tabs appear in the control.

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.


 SubAddress Property

SubAddress Property

You can use the SubAddress property to specify or determine a location within the target document specified by the Address property. The SubAddress 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 SubAddress property is a string expression representing the HyperlinkSubAddress property of a named location within the target document specified by the HyperlinkAddress property

You can set the HyperlinkSubAddress property with the SubAddress property by using Visual Basic.

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

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.

For more information about hyperlink addresses and their format, see the HyperlinkAddress and HyperlinkSubAddress property topics.


 SubdatasheetExpanded Property

SubdatasheetExpanded Property

You can use the SubdatasheetExpanded property to specify or determine the saved state of all subdatasheets within a table or query.

Note The SubdatasheetExpanded property applies only to tables and queries within a Microsoft Access database (.mdb).

Setting

The SubdatasheetExpanded property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The saved state of all subdatasheets in the table is expanded.
No | False (0) | (Default) The saved state of all subdatasheets in the table is closed.

The easiest way to set the SubdatasheetExpanded property is by using a table's property sheet. You can set this property by using Visual Basic.

To set the SubdatasheetExpanded property by using Visual Basic, you must first either:

  • Set the property in table Design view by pointing to Properties on the View menu.

  • Create the property by using the DAO CreateProperty method.

Remarks

The value of the SubdatasheetExpanded property is displayed in the Table Properties property sheet.

The SubdatasheetExpanded and SubdatasheetHeight properties take effect on the subform control when the form is in datasheet view.


 SubdatasheetHeight Property

SubdatasheetHeight Property

You can use the SubdatasheetHeight property to specify or determine the display height of a subdatasheet when expanded.

Note The SubdatasheetHeight property applies only to tables and queries within a Microsoft Access database (.mdb).

Setting

The SubdatasheetHeight property in a numeric expression representing the default height to display in the subdatasheet.

The easiest way to set the SubdatasheetHeight property is by using a table's property sheet. You can set this property by using Visual Basic. In Visual Basic, the property's value is expressed in twips.

To set the SubdatasheetHeight property by using Visual Basic, you must first either:

  • Set the property in table Design view by pointing to Properties on the View menu.

  • Create the property by using the DAO CreateProperty method.

Remarks

If the subdatasheet includes more records than the height setting can accommodate, a vertical scrollbar is displayed.

The SubdatasheetHeight property setting includes the New Record row if adding new records is supported. It does not include the column header row or scrollbar region.

The SubdatasheetHeight and SubdatasheetExpanded properties take effect on the subform control when the form is in datasheet view.


 SubdatasheetName Property

SubdatasheetName Property

You can use the SubdatasheetName property to specify or determine the table or query that is bound to the subdatasheet.

Note The SubdatasheetName property applies only to tables and queries within a Microsoft Access database (.mdb).

Setting

The SubdatasheetName property in a string expression representing the name of the table or query bound to the subdatasheet.

The easiest way to set the SubdatasheetName property is by using a table's property sheet. You can set this property by using Visual Basic.

To set the SubdatasheetName property by using Visual Basic, you must first either:

  • Set the property in table Design view by pointing to Properties on the View menu.

  • Create the property by using the DAO CreateProperty method.


 TabFixedHeight, TabFixedWidth Properties

TabFixedHeight, TabFixedWidth Properties

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.


 TabIndex Property

TabIndex Property

You can use the TabIndex property to specify a control's place in the tab order on a form.

Note The TabIndex property applies only to controls on a form, 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.


 TabStop Property

TabStop Property

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.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) You can move the focus to the control by pressing the TAB key.
No | False (0) | You can't move the focus to the control by pressing the TAB key.

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


 Tag Property (Microsoft Access)

Tag Property

You can use the Tag property to store any extra information about a form, report, data access page, 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, data access page, section, or control that is passed as a variable to a procedure.


 Text Property (Microsoft Access)

Text Property

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.


 TextToDisplay Property

TextToDisplay Property

You can use the TextToDisplay property to specify or determine the display text for a hyperlink.

Setting

The TextToDisplay property is a string expression representing the text displayed as a hyperlink.

The TextToDisplay property can be set by using the form's property sheet or Visual Basic.


 TimerInterval Property

TimerInterval Property

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.


 Toolbar Property

Toolbar Property

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. For more information on creating customized toolbars, see Create a custom toolbar for the current database.

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.


 TopValues Property

TopValues Property

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 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 Top value, list 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.

Sales | Salesperson
90,000 | Leverling
80,000 | Peacock
70,000 | Davolio
70,000 | King
60,000 | Suyama
50,000 | Buchanan

If you set the TopValues property to 3 with a descending sort on the Sales field, Microsoft Access returns the following four records.

Sales | Salesperson
90,000 | Leverling
80,000 | Peacock
70,000 | Davolio
70,000 | King

Note To return the topmost or bottommost values without displaying duplicate values, set the UniqueValues property in the query's property sheet to Yes.


 Transparent Property

Transparent Property

You can use the Transparent property to specify whether a command button is solid or transparent.

Tip Use the BackStyle property to make other controls solid or transparent.

Setting

The Transparent property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The button is transparent.
No | False (0) | (Default) The button is solid.

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.


 TripleState Property

TripleState Property

You can use the TripleState property to specify how a check box, toggle button, or option button will display Null values.

Note The TripleState property doesn't apply to the specified controls when they are used inside an option group control.

Setting

The TripleState property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | 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.
No | False (0) | (Default) The control will cycle through states for Yes and No values. Null values display as if they were No values.

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 (Microsoft Access)

Type Property

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.


 Type Property (AccessObject Object)

Type Property (AccessObject Object)

You can use the Type property to return the value of a AccessObject object type.

Setting

The Type property returns one of the following intrinsic constants.

acDataAccessPage (6) | acQuery (1)
acDiagram (8) | acReport (3)
acForm (2) | acServerView (7)
acMacro (4) | acStoredProcedure (9)
acModule (5) | acTable (0)

The Type property is available only by using Visual Basicand is read-only.


 Type Property (FormatCondition Object)

Type Property (FormatCondition Object)

You can use the Type property to return the value of a FormatCondition object type.

Setting

The Type property returns one of the following intrinsic constants.

acExpression (1) | acFieldHasFocus (2)
acFieldValue (0) |

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


 UnderlineHyperlinks Property

UnderlineHyperlinks Property

You can use the UnderlineHyperlink property to specify or determine if hyperlinks within the Application object should be underlined when displayed.

Setting

The UnderlineHyperlink property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) Hyperlinks will be underlined
No | False (0) | Hyperlinks will not be underlined.

You can set the UnderlineHyperlink property through the DefaultWebOptions property or the SetOption method by using Visual Basic.

You can set or change the underline hyperlink setting in the Web Options dialog box. To display this dialog box, click Options on the Tools menu. Click the General tab and click the Web Pages button.

Remarks

DefaultWebOptions property to identify or set the Application object's DefaultWebOptions object properties.


 Unique Property (Microsoft Access)

Unique Property

You can use the Unique property to specify that an index enforces uniqueness of the data in the table's key index.

Setting

The Unique property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | The index is a key (unique) index.
No | False (0) | The index is a non-key index.

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


 UniqueRecords Property

UniqueRecords Property

You can use the UniqueRecords property to specify whether to return only unique records based on all fields in the underlying data source, not just those fields present in the query itself.

Note The UniqueRecords property applies only to 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.
No | (Default) Returns duplicate records.

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.


 UniqueTable Property

UniqueTable Property

You can use the UniqueTable property to specify or determine the table to be updatable when:

  • A form or data access page is bound to a multiple table view or stored procedure within a Microsoft Access project (.adp).

  • A data access page is bound to a multiple table query or macro within a Microsoft Access project (.adp).

Setting

The UniqueTable property is a string expression representing the unique table to be updatable.

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

Remarks

The UniqueTable property identifies the "most many" table of a join. If you don't set the UniqueTable property, a form that is bound to a view or stored proc or SQL String containing a join is read only. Also, the datasheet produced by View.Open or StoredProc.Run is read only in the case of a join (because there's no way to set the UniqueTable property). Once you set the UniqueTable property, only fields from that table are updatable, and inserts and deletes can only be made to that table.

A form or data access page based on a join cursor must have a UniqueTable property string in order for the recordset to be an updatable snapshot. The Unique Table is the table in the underlying query whose rows have a 1-to-1 correspondence with rows in the cursor. In a simple Patients - Doctors join, Patients is the unique table because every row of the cursor corresponds to one row of the Patients table. Note that a Many-to-Many join does not have a valid UniqueTable property, and is thus read-only. The UniqueTable property will be exposed as a RecordsetDef object in the case of a data access page. The purpose of the UniqueTable property is:

To enforce the correct updatability semantics:

  • The key columns of the Unique Table must be present in the select list of the query that forms the cursor, even for SQL Server. (For other data sources, see the Remarks section in the ResyncCommand property topic.)

  • Deletion of a row in a join cursor deletes the row from the Unique Table only.

  • Insertion of a row in a join cursor is allowed for the Unique Table only

  • Update of a row in a join cursor is allowed for fields in the Unique Table only.

To provide the right parameter values for the Resync Query. The UniqueTable property of a form or a RecordsetDef supports the catalog.owner.tablename notation to fully qualify a base table from others in the same cursor, if this is required. For example, for example, if dbo.authors were joined to user1.authors in a cursor, then the UniqueTable would need to be specified as dbo.authors or user1.authors.

For a join cursor, if the UniqueTable property is empty, the recordset reverts to read only and any attempt to edit results in a beep and a status message, "This Recordset is not updatable because the UniqueTable property is not set." If there is a non-empty UniqueTable property, set the UniqueTable property (and UniqueSchema, UniqueCatalog properties if necessary) on the underlying Recordset or Rowset. Then, go through and mark each column that does not match the UniqueTable property as read only.

On insert and update operations, only the fields from the Unique Table are available for editing. When the user tries to type into them he gets a beep and the message "Only fields from the Unique Table can be edited." If the UniqueTable property has been set incorrectly, this will happen for all columns.

Set Unique Table in the single table case

If the case of a recordset based on a view or SQL String, we still want to provide our own ResyncCommand to handle the case of server expression columns. Also, in the case of a stored proc, the user may want to provide their own ResyncCommand property even in the single-table case. For these reasons we should always set the "Unique Table" provider property in the single table case. ( QBU will only allow the setting of a Resync Command if Unique Table has been set. )


 UniqueValues Property

UniqueValues Property

You can use the UniqueValues property when you want to omit records that contain duplicate data in the fields displayed in Datasheet view. For example, if a query's output includes more than one field, the combination of values from all fields must be unique for a given record to be included in the results.

Note The UniqueValues property applies only to append and make-table action queries and select queries.

Setting

The UniqueValues property uses the following settings.

Setting | Description
Yes | Displays only the records in which the values of all fields displayed in Datasheet view are unique.
No | (Default) Displays all records.

You can set the UniqueValues property in the query'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.


 UpdateOptions Property

UpdateOptions Property

You can use the UpdateOptions property to specify how a linked OLE object is updated.

Setting

The UpdateOptions property uses the following settings.

Setting | Visual Basic | Description
Automatic | acOLEUpdateAutomatic (0) | (Default) Updates the object each time the linked data changes.
Manual | acOLEUpdateManual (2) | 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.

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 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 = acOLEUpdateManual
OLE1.Action = acOLEUpdate


UseLongFileNames Property

You can use the UseLongFileNames property to specify or determine whether long file names are used when a document is stored as a data access page.

Setting

The UseLongFileNames property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) Use long file names whenever possible when you save the document as a data access page.
No | False (0) | Use the 8.3 DOS filename format.

The UseLongFileNames property is available only by using Visual Basic.

Remarks

If you don't use long file names and your data access page has supporting files, Microsoft Access automatically organizes those files in a separate folder. Otherwise, use the OrganizeInFolder property to determine whether supporting files are organized in a separate folder.


 UserControl Property

UserControl Property

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.

You can determine the UserControl property setting only by using Visual Basic.

This property is read-only in all views when user starts the Access application. If Microsoft Access is started by OLE Automation, the UserControl property can be set 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, the Visible and UserControl properties of the object are both set to False.


 UseTransaction Property

UseTransaction Property

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.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) The query runs as a single transaction.
No | False (0) | The query doesn't run as a single transaction.

You can set the UseTransaction property by using the query's property sheet or Visual Basic. To set this property in a Microsoft Access database (.mdb) with Visual Basic, you must first add it to a QueryDef object's Properties collection by using the CreateProperty method.

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 ADO RollbackTrans or DAO Rollback method in Visual Basic.


 ValidationRule, ValidationText Properties (Microsoft Access)

ValidationRule, ValidationText Properties

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

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 Eval function, or CurrentUser method, 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:

  • The Field Properties section of table Design view (for a field validation rule).

  • The property sheet for a table by clicking Properties on the View menu in table Design view (for a record validation rule).

  • The property sheet for a control on a form.

  • A macro or Visual Basic. In Visual Basic, use a string expression to set these properties.

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:

  • Validation rules you set for fields and controls are applied when you edit the data and the focus leaves the field or control.

  • Validation rules for records are applied when you move to another record.

  • If you create validation rules for both a field and a control bound to the field, both validation rules are applied when you edit data and the focus leaves the control.

The following table contains expression examples for the ValidationRule and ValidationText properties.

ValidationRule property | ValidationText property
<> 0 | Entry must be a 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).

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.


 Value Property (Microsoft Access)

Value Property

You can use the Value property to determine or specify if a control is selected, the selected value or option within the control, the text contained in a text box control, or the value of a custom property.

  • Check box, option button, and toggle button controls. Determines or specifies whether or not the control is selected.

  • Combo box, list box, and option group controls. Determines or specifies which value or option in the control is selected.

  • Text box controls. Determines or specifies the text in the text box.

  • Tab control. Determines or specifies the selected Page object.

  • Built-in properties. Determines or specifies the value of a built-in property of an AccessObject object.

Setting

The Value property uses the following setting depending on the specified control.

Control | Setting | Description | Visual Basic
Check box | True False | The check box is selected. (Default) The check box is cleared. | True (–1) False (0)
Combo box | [The text in the text box portion of the control] | This may or may not be the same as the setting for the Text property of the control. The current setting for the Text property is what is displayed in the text box portion of the combo box; the Value property is set to the Text property setting only after this text is saved. |
List box | [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. |
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 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. |
Custom properties | A Long or string expression representing the value of the custom property. | The Value property of a custom property contains the value of the specified custom property of an AccessObject object. For more information about custom properties, see the topics about the AccessObject object, AccessObjectProperty object, and the AccessObjectProperties collection. |

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 = True
Forms!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.

  • The Value property can also return or set a custom properties' default property, which is the property that is assumed when you don't explicitly specify a property name.This means that the following two statements are equivalent.
    CurrentProject.AllForms!optCreditApproved.Value = True
CurrentProject.AllForms!optCreditApproved = True


 VBE Property (Microsoft Access)

VBE Property

You can use the VBE property to return a reference to the current VBE object and its related properties. The VBE property of the Application object represents the Microsoft Visual Basic for Applications editor.

Setting

[application.]VBE[.property]

The VBE property uses the following settings.

Setting | Description
application | Optional. The Application object.
VBE | Required. When used without specifying a property, returns the VBE object'.
property | A property of the VBE object.

The VBE property is available only by using Visual Basic.

Remarks

Once you establish a reference to the VBE object, you can access all the properties and methods of the object. You can set a reference to the VBE object by clicking References on the Tools menu while in module Design view. Then set a reference to the Microsoft Visual Basic for Applications Extensibility 5.3 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 Visual Basic for Applications Extensibility 5.3 Object Library constant to set a VBE object's property or as an argument to a VBE object's method.


 Verb Property

Verb Property

You can use the Verb property to specify the operation to perform when an OLE object is activated, which is permitted when the control's Action property is set to acOLEActivate.

Setting

You can set the Verb property by specifying an Integer data type value indicating the position of a verb in the list of verbs returned by the ObjectVerbs property. 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.

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

With some applications' objects, you can use these additional values.

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

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.


Vertical Property

You can use the Vertical property to set a form control for vertical display and editing or set a report control for vertical display and printing.

Settings

The Vertical property uses the following settings.

Setting | Visual Basic | Description
Yes | True (-1) | Displays, edits, and prints vertical text.
No | False (0) | Does not display, edit, or print vertical text. (default)

You can set the Vertical property by using the property sheet, a macro, or Visual Basic.

Remarks

You can specify how vertical text will be displayed, edited, or printed in the control by setting the Vertical property. If set to Yes, the starting point for inputting text is the upper right corner of the control (the ending point is the lower left corner of the control). If using full pitch characters, the display and print directions are the same as the control for horizontal text. If using half pitch characters, it shifts 90 degrees to the right. The cursor is also rotated 90 degrees to the right in a vertical text control.

Note Text selection using key combinations is different for vertical text control and horizontal text control. Key combinations and their effect on range selection are described below.

Key combination | Selected range
Shift+Up | Vertical: One character before the cursor. Horizontal: One line before the cursor.
Shift+Down | Vertical: One character after the cursor. Horizontal: One line after the cursor.
Shift+Right | Vertical: One line after the cursor. Horizontal: One character before the cursor.
Shift+Left | Vertical: One line before the cursor. Horizontal: One character after the cursor.


 Visible Property (Microsoft Access)

Visible Property

You can use the Visible property to show or hide a form, report, form or report section, data access page, or control. This may be useful if you want to maintain access to information on a form without it being visible. For example, you could use the value of a control on a hidden form as the criteria for a query.

Setting

The Visible property uses the following settings.

Setting | Visual Basic | Description
Yes | True (–1) | (Default) The object is visible.
No | False (0) | The object is not visible.

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, reports, and data access pages, 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.


 Visible Property (Application Object)

Visible Property (Application Object)

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.

Setting | Description
True (–1) | The application is visible.
False (0) | The application isn't visible.

You can set the Visible property of the Application object only 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.


 WebOptions Property

WebOptions Property

You can use the WebOptions property to reference the WebOptions object and its related properties.

Setting

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

Remarks

Use the WebOptions object's properties to set web options for the active data access page.


 WhatsThisButton Property (Microsoft Access)

WhatsThisButton Property (Microsoft Access)

You can use the WhatsThisButton property to specify whether a What's This button [image] 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.

Setting | Visual Basic | Description
Yes | True (–1) | A What's This button appears on the title bar.
No | False (0) | (Default) A What's This button doesn't appear on the title bar.

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.


WillContinue Property

You can use the WillContinue property to determine if the current section will continue on the following page.

Setting

The WillContinue property is set by Microsoft Access and is read-only in all views.

Value | Description
True (–1) | The current section continues on the following page.
False (0) | The current section doesn't continue on the following page.

You can get the value of the WillContinue property 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.


 WindowHeight, WindowWidth Properties

WindowHeight, WindowWidth Properties

You can use these properties to return the height and width of a form or data access page 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 or data access page to its lower-left corner. The WindowWidth property is measured from the upper left corner of the form or data access page to its upper-right corner.


 Zoom Property

Zoom Property

You can use the Zoom property to specify or determine the display state for a snapshot.

Setting

The Zoom property is an Integer value between 0 and 8 representing the display state for a snapshot page as a percentage of the actual page size.

Constant | Description
snapZoomToFit | (Default) Zooms to a full page display.
snapZoomToFill | Zooms the page to fill the available space in the control.
snapZoom200Percent | Zooms the page by a factor of 200%.
snapZoom150Percent | Zooms the page by a factor of 150%.
snapZoom100Percent | Zooms the page by a factor of 100%.
snapZoom75Percent | Zooms the page by a factor of 75%.
snapZoom50Percent | Zooms the page by a factor of 50%.
snapZoom25Percent | Zooms the page by a factor of 25%.
snapZoom10Percent | Zooms the page by a factor of 10%.

You can set the Zoom property by using the control's property sheet or Visual Basic.

If you set this property to an invalid value, an error occurs.

Remarks

When the AllowContextMenu property is set to Yes, you can also specify the Zoom property from the control's pop-up menu.


Statements Reference

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

A–M

AppActivate (VBA) | DeleteControl
Beep (VBA) | DeleteReportControl
Call (VBA) | DeleteSetting (VBA)
ChDir (VBA) | Dim (VBA)
ChDrive (VBA) | Do...Loop (VBA)
Close (VBA) | End (VBA)
Const (VBA) | Erase (VBA)
Date (VBA) | Error (VBA)
DDE | Exit (VBA)
DDEExecute | FileCopy (VBA)
DDEPoke | For Each...Next (VBA)
DDETerminate | For...Next (VBA)
DDETerminateAll | Function (VBA)
Declare (VBA) | Get (VBA)
DefBool (VBA) | GoSub...Return (VBA)
DefByte (VBA) | GoTo (VBA)
DefCur (VBA) | If...Then...Else (VBA)
DefDate (VBA) | Input # (VBA)
DefDbl (VBA) | Kill (VBA)
DefInt (VBA) | Let (VBA)
DefLng (VBA) | Line Input # (VBA)
DefObj (VBA) | Lock (VBA)
DefSng (VBA) | LSet (VBA)
DefStr (VBA) | Mid (VBA)
DefType (VBA) | MidB (VBA)
DefVar (VBA) | MkDir (VBA)

N–Z

Name (VBA) | Resume (VBA)
On Error (VBA) | Return (VBA)
On...GoSub (VBA) | RmDir (VBA)
On...GoTo (VBA) | RSet (VBA)
Open (VBA) | SaveSetting (VBA)
Option Base (VBA) | Seek (VBA)
Option Compare (VBA) | SelectCase (VBA)
Option Explicit (VBA) | SendKeys (VBA)
Option Private (VBA) | Set (VBA)
Print # (VBA) | SetAttr (VBA)
Private (VBA) | Static (VBA)
Property Get (VBA) | Stop (VBA)
Property Let (VBA) | Sub (VBA)
Property Set (VBA) | Time (VBA)
Public (VBA) | Type (VBA)
Put (VBA) | Unlock (VBA)
Randomize (VBA) | While...Wend (VBA)
ReDim (VBA) | Width # (VBA)
Rem (VBA) | With (VBA)
Reset (VBA) | Write # (VBA)


 DDEExecute Statement

DDEExecute Statement

You can use the DDEExecute statement to send a command from a client application to a server application over an open dynamic data exchange (DDE) channel.

For example, suppose you'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.

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.

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. For information on sending commands to Microsoft Access from another application, see Use Microsoft Access as a DDE Server.

Tip If you need to manipulate another application's objects from Microsoft Access, you may want to consider using Automation.


 DDEPoke Statement

DDEPoke Statement

You can use the DDEPoke statement to supply text data from a client application to a server application over an open dynamic data exchange (DDE) channel.

For example, if you have an open DDE channel between Microsoft Access and Microsoft Excel, you can use the DDEPoke statement to transfer text from a Microsoft Access database to a Microsoft Excel spreadsheet. In this example, Microsoft Access acts as the client application, and Microsoft Excel acts as the server application.

Syntax

DDEPoke channum, item, data

The DDEPoke statement has the following arguments.

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.

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.


 DDETerminate Statement

DDETerminate Statement

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.


 DDETerminateAll Statement

DDETerminateAll Statement

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

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

  • If you need to manipulate another application's objects from Microsoft Access, you may want to consider using Automation.


About the Table Analyzer Wizard's query

1 2 3 4


About the Table Analyzer Wizard's query


ApplyFilter Action Arguments (1)

Argument | Setting
Filter Name |
Where Condition | [Company Name] Like "[AÀÁÂÃÄ]*"


ApplyFilter Action Arguments (2)

Argument | Setting
Filter Name |
Where Condition | [Company Name] Like "B*"


ApplyFilter Action Arguments (3)

Argument | Setting
Filter Name |
Where Condition | [Company Name] Like "[CÇ]*"


ApplyFilter Action Arguments (4)

Argument | Setting
Filter Name |
Where Condition | [Company Name] Like "[ZÆØÅ]*"


GoToControl Action Arguments

Argument | Setting
Control Name | CompanyName.


Apply a Filter by Using a Macro - Example

Apply a Filter by Using a Macro — Example

The following macro contains a set of actions, each of which filters the records for a Customer Phone List form. It shows the use of the ApplyFilter, ShowAllRecords, and GoToControls actions. It also shows the use of conditions to determine which toggle button in an option group has been selected on the form. Each action row is associated with a toggle button that selects the set of records starting with A, B, C, and so on, or all records.

Click the action name to see the arguments for each action.

Condition | Action | Comment
 |  | Attached to AfterUpdate event of CompanyNameFilter option group.
[Company Name Filters] =1 | ApplyFilter | Filter for company names that start with A, À, Á, Â, Ã, or Ä.
[Company Name Filters] =2 | ApplyFilter | Filter for company names that start with B.
[Company Name Filters] =3 | ApplyFilter | Filter for company names that start with C or Ç.
... Action rows for D through Y have the same format as those for A through C ...
[Company Name Filters] =26 | ApplyFilter | Filter for company names that start with Z, Æ, Ø, or Å.
[Company Name Filters] =27 | ShowAllRecords | Show all records.
[RecordsetClone].[RecordCount]>0 | GoToControl | If records are returned for the selected letter, move focus to the CompanyName control.


Validate Data by Using a Macro - Example

Validate Data by Using a Macro — Example

The following validation macro checks the postal codes entered in a Suppliers form. It shows the use of the StopMacro, MsgBox, CancelEvent, and GoToControl actions. A conditional expression checks the country and postal code entered in a record on the form. If the postal code is not in the right format for the country, the macro displays a message box and cancels saving the record. It then returns you to the Postal Code control, where you can correct the error.

Click the action name to see the arguments for each action.

Condition | Action | Comment
 |  | Attached to the BeforeUpdate property of the Suppliers form.
IsNull([Country]) | StopMacro | If Country is Null, postal code can't be validated
[Country] In ("France","Italy","Spain") And Len([Postal Code]) <> 5 | MsgBox | If the postal code isn't 5 characters, display a message and...
... | CancelEvent | ... cancel the event.
 | GoToControl |
[Country] In ("Australia","Singapore") And Len([Postal Code]) <> 4 | MsgBox | If the postal code isn't 4 characters, display a message and...
... | CancelEvent | ... cancel the event.
 | GoToControl |
([Country] = "Canada") And ([Postal Code] Not Like"[A-Z][0-9][A-Z] [0-9][A-Z][0-9]") | MsgBox | If the postal code isn't correct for Canada, display a message and...
... | CancelEvent | ... cancel the event.


MsgBox Action Arguments (1)

Argument | Setting
Message | The postal code must be 5 characters.
Beep | Yes
Type | Information
Title | Postal Code Error


MsgBox Action Arguments (2)

Argument | Setting
Message | The postal code must be 4 characters.
Beep | Yes
Type | Information
Title | Postal Code Error


MsgBox Action Arguments (3)

Argument | Setting
Message | The postal code not valid. Example of Canadian code: H1J 1C3
Beep | Yes
Type | Information
Title | Postal Code Error


 OpenDataAccessPage Action

OpenDataAccessPage Action

You can use the OpenDataAccessPage action to open a data access page in Page view or Design view.

Setting

The OpenDataAccessPage action has the following arguments.

Action argument | Description
Data Access Page Name | The name of the form to open. The Data Access Page 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 OpenDataAccessPage 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 data access page will open. Click Browse or Design in the view box. The default is Browse.

Remarks

This action is similar to clicking the Open button or Design button in the Database window after selecting a data access page on the Pages tab.

Tip You can select a data access page in the Database window and drag it to a macro action row. This automatically creates an OpenDataAccessPage action that opens the data access page in Page view.

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


Set the Value of a Control by Using a Macro - Example

Set the Value of a Control by Using a Macro — Example

The following macro opens the Add Products form from a button on the Suppliers form. It shows the use of the Echo, Close, OpenForm, SetValue, and GoToControl actions. The SetValue action sets the Supplier ID control on the Products form to the current supplier on the Suppliers form. Then the GoToControl action moves the focus to the Category ID field, where you can begin to enter data for the new product.

Click the action name to see the arguments for each action.

Action | Comment
 | Attached to the Add Products button on the Suppliers form.
Echo | Stop screen updating while the macro is running (echo is turned off).
Close | Close Product List form
OpenForm | Open the Products form.
SetValue | Set the Supplier ID control to the current supplier on the Suppliers form.
GoToControl | Go to the Category ID control.


MsgBox Action Arguments

Argument | Setting
Message | Move to the supplier record whose products you want to see, then press the Review Products button again.
Beep | Yes
Type | None
Title | Select a Supplier


OpenForm Action Arguments

Argument | Setting
Form Name | Product List
View | Datasheet
Filter Name |
Where Condition | [Supplier ID] = [Forms]![Suppliers]![SupplierID]
Data Mode | Read Only
Window Mode | Normal


MoveSize Action Arguments

Argument | Setting
Right | 0.7799"
Down | 1.8"
Width |
Height |


Close Action Arguments

Argument | Setting
Object Type | Form
Object Name | Product List
Save | No


OpenForm Action Arguments

Argument | Setting
Form Name | Products
View | Form
Filter Name |
Where Condition |
Data Mode | Add
Window Mode | Normal


SetValue Action Arguments

Argument | Setting
Item | [Forms]![Products]![SupplierID]
Expression | SupplierID


Synchronize Forms by Using a Macro - Example

Synchronize Forms by Using a Macro — Example

The following macro opens a Product List form in the lower-right corner of the Suppliers form, displaying the current supplier's products. It shows the use of the Echo, MsgBox, GoToControl, StopMacro, OpenForm, and MoveSize actions. It also shows the use of a conditional expression with the MsgBox, GoToControl, and StopMacro actions.

Click the action name to see the arguments for each action.

Condition | Action | Comment
 |  | Attached to the Review Products button on the Suppliers form.
 | Echo | Stop screen updating while the macro is running (echo is turned off).
IsNull([Supplier ID]) | MsgBox | If there is no current supplier on the Suppliers form, display a message...
 | GoToControl | Move focus to the CompanyName control.
... | StopMacro | ... and stop the macro.
 | OpenForm | Open the Product List form and show the current supplier's products.
 | MoveSize | Position the Product List form in the lower right of the Suppliers form.


AllDataAccessPages Collection Example

The following example prints the name of each open AccessObject object in the AllDataAccessPages collection.

Sub AllDataAccessPages()
    Dim obj As AccessObject, dbs As Object
    Set dbs = Application.CurrentProject
    ' Search for open AccessObject objects in
    ' AllDataAccessPages collection.
    For Each obj In dbs.AllDataAccessPages
        If obj.IsLoaded = TRUE then
            ' Print name of obj.
            Debug.Print obj.Name
        End If
    Next obj
End Sub


AllDatabaseDiagrams Collection Example

The following example prints the name of each open AccessObject object in the AllDatabaseDiagrams collection.

Sub AllDatabaseDiagrams()
    Dim obj As AccessObject, dbs As Object
    Set dbs = Application.CurrentData
    ' Search for open AccessObject objects in
    ' AllDatabaseDiagrams collection.
    For Each obj In dbs.AllDatabaseDiagrams
        If obj.IsLoaded = TRUE then
            ' Print name of obj.
            Debug.Print obj.Name
        End If
    Next obj
End Sub


AllForms Collection Example

The following example prints the name of each open AccessObject object in the AllForms collection.

Sub AllForms()
    Dim obj As AccessObject, dbs As Object
    Set dbs = Application.CurrentProject
    ' Search for open AccessObject objects in AllForms collection.
    For Each obj In dbs.AllForms
        If obj.IsLoaded = TRUE then
            ' Print name of obj.
            Debug.Print obj.Name
        End If
    Next obj
End Sub


AllMacros Collection Example

The following example prints the name of each open AccessObject object in the AllMacros collection.

Sub AllMacros()
    Dim obj As AccessObject, dbs As Object
    Set dbs = Application.CurrentProject
    ' Search for open AccessObject objects in AllMacros collection.
    For Each obj In dbs.AllMacros
        If obj.IsLoaded = TRUE then
            ' Print name of obj.
            Debug.Print obj.Name
        End If
    Next obj
End Sub


AllModules Collection Example

The following example prints the name of each open AccessObject object in the AllModules collection.

Sub AllModules()
    Dim obj As AccessObject, dbs As Object
    Set dbs = Application.CurrentProject
    ' Search for open AccessObject objects in AllModules collection.
    For Each obj In dbs.AllModules
        If obj.IsLoaded = TRUE then
            ' Print name of obj.
            Debug.Print obj.Name
        End If
    Next obj
End Sub


AllQueries Collection Example

The following example prints the name of each open AccessObject object in the AllQueries collection.

Sub AllQueries()
    Dim obj As AccessObject, dbs As Object
    Set dbs = Application.CurrentData
    ' Search for open AccessObject objects in AllQueries collection.
    For Each obj In dbs.AllQueries
        If obj.IsLoaded = TRUE then
            ' Print name of obj.
            Debug.Print obj.Name
        End If
    Next obj
End Sub


AllReports Collection Example

The following example prints the name of each open AccessObject object in the AllReports collection.

Sub AllReports()
    Dim obj As AccessObject, dbs As Object
    Set dbs = Application.CurrentProject
    ' Search for open AccessObject objects in AllReports collection.
    For Each obj In dbs.AllReports
        If obj.IsLoaded = TRUE then
            ' Print name of obj.
            Debug.Print obj.Name
        End If
    Next obj
End Sub


AllStoredProcedures Collection Example

The following example prints the name of each open AccessObject object in the AllProcedures collection.

Sub AllStoredProcedures()
    Dim obj As AccessObject, dbs As Object
    Set dbs = Application.CurrentData
    ' Search for open AccessObject objects in
    ' AllStoredProcedures collection.
    For Each obj In dbs.AllStoredProcedures
        If obj.IsLoaded = TRUE then
            ' Print name of obj.
            Debug.Print obj.Name
        End If
    Next obj
End Sub


AllTables Collection Example

The following example prints the name of each open AccessObject object in the AllTables collection.

Sub AllTables()
    Dim obj As AccessObject, dbs As Object
    Set dbs = Application.CurrentData
    ' Search for open AccessObject objects in AllTables collection.
    For Each obj In dbs.AllTables
        If obj.IsLoaded = TRUE then
            ' Print name of obj.
            Debug.Print obj.Name
        End If
    Next obj
End Sub


AllViews Collection Example

The following example prints the name of each open AccessObject object in the AllViews collection.

Sub AllViews()
    Dim obj As AccessObject, dbs As Object
    Set dbs = Application.CurrentData
    ' Search for open AccessObject objects in AllViews collection.
    For Each obj In dbs.AllViews
        If obj.IsLoaded = TRUE then
            ' Print name of obj.
            Debug.Print obj.Name
        End If
    Next obj
End Sub


 DataAccessPages Collection

DataAccessPages Collection

 DataAccessPages collection (DataAccessPage object)

The DataAccessPages collection contains all of the data access pages that are currently open in a Microsoft Access project (.adp) or Access database (.mdb).

Remarks

Use the DataAccessPages collection in Visual Basic or in an expression to refer to data access pages that are currently open. For example, you can enumerate the DataAccessPages collection to set or return the values of properties of individual data access pages in the collection.

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

You can refer to an individual DataAccessPage object in the DataAccessPages collection either by referring to the data access page by name, or by referring to its index within the collection. If you want to refer to a specific data access page in the DataAccessPages collection, it's better to refer to the data access page by name because a data access page's collection index may change.

The DataAccessPages collection is indexed beginning with zero. If you refer to a data access page by its index, the first data access page opened is DataAccessPages(0), the second form opened is DataAccessPages(1), and so on. If you opened Page1 and then opened Page2, Page2 would be referenced in the DataAccessPages collection by its index as DataAccessPages(1). If you then closed Page1, Page2 would be referenced in the DataAccessPages collection by its index as DataAccessPages(0).

Note To list all data access pages in the database, whether open or closed, enumerate the AllDataAccessPages collection of the CurrentProject object. You can then use the Name property of each individual AccessObject object to return the name of a data access page.

You can't add or delete a DataAccessPage object from the DataAccessPages collection.


Properties Collection Example

The next example enumerates the Forms collection and prints the name of each open form in the Forms collection. It then enumerates the Properties collection of each form and prints the name of each property and value.

Sub AllOpenForms()
    Dim frm As Form, prp As Property

    ' Enumerate Forms collection.
    For Each frm In Forms
        ' Print name of form.
        Debug.Print frm.Name
        ' Enumerate Properties collection of each form.
        For Each prp In frm.Properties
            ' Print name of each property.
            Debug.Print prp.Name; " = "; prp.Value
        Next prp
    Next frm
End Sub


About adding a bound object to a form or report

You can add a bound object to a form or report as an inserted object or as a linked object.

When you insert an object in a form or report, Microsoft Access stores the object in your database file — so an inserted object is always available. If you modify the object or the path to the graphic object from your form or report, the object is changed in your database file.

When you link to an object, you can look at the object and make changes to it from your form or report, but the changes are stored in the original object file, not in your database file. You can also modify the object file separately; in which case, the latest changes will appear the next time you open the form or report. Linking to an object is useful for very large files that you don't want to include in your database file, and for files that you want to use in several forms or reports, but if a linked object file is moved, you have to reconnect the link.

Return to Add a bound object to a form or report


About adding a picture or other object to a form, report or data access page

How you add a picture or object depends on whether you are working with a form or report, or with a data access page.

Forms and reports

You can add objects or parts of objects that you've created in other applications to a Microsoft Access form or report. For example, you can add a picture that you created with Microsoft Paint, a worksheet that you created with Microsoft Excel, or a Word document that you created with Microsoft Word. You can add all the information in a file or just selected information.

In forms and reports, a bound object is stored in a table. When you move to a new record, the object that is displayed in the form or report changes. For example, you might want to store a picture for each employee in your company. On the other hand, an unbound object is stored in the design of the form or report. When you move to a new record, the object doesn't change. For example, you might want to add a logo that you created with Microsoft Paint to a form or report.

Data access pages

You can add a picture object to a data access page. You can bind a picture to a data access page by entering the path to the picture in a field, and then binding an image control to this field. This process differs from a form or report in that the picture object itself can't be stored in a table, only the path to the image. On a data access page, you can also insert an unbound picture, such as a logo or banner, which doesn't change when you move to a new record.

Return to Add a picture or other object to a form, report, or data access page


About adding an unbound object to a form or report

You can add an unbound object to a form or report as an inserted object or as a linked object.

When you insert an object, Microsoft Access stores the object in your database file — so an inserted object is always available. If you modify the object from your form or report, the object is changed in your database.

When you link to an object, you can look at the object and make changes to it from your form or report, but the changes are stored in the original object file, not in your database file. You can also modify the object file separately; in which case, the latest changes will appear the next time you open the form or report. Linking to an object is useful for very large files that you don't want to include in your database file, and for files that you want to use in several forms or reports; but if a linked object file is moved, you have to reconnect the link.

Return to Add an unbound object


 About calculating a sum, average, count, or other total on records in a query

About calculating a sum, average, count, or other total on records in a query

Using the Total row in query Design view, you can calculate the sum, average, count, minimum, maximum, variance, or standard deviation on values in one or more fields either for all the records in a query or for one or more groups of records. Using the Criteria row, you can also add criteria to affect the results of the calculation.

Note You can also use the Simple Query Wizard to calculate the sum, average, count, minimum, or maximum of the values in a field; but if you want to add criteria, you must use the query design grid.

Return to Calculate a sum, average, count, or other total on records in a query


 About compacting an Access database or Access project

About compacting an Access database or Access project

Starting with this version, Microsoft Access now combines compacting and repairing Microsoft Access databases into a single process. However, Access only compacts Microsoft Access projects; Access doesn't repair Access projects.

Compacting an Access database or an Access project If you delete data or objects in an Access database, or if you delete objects in an Access project, the Access database or Access project can become fragmented and use disk space inefficiently. Compacting the Access database or Access project makes a copy of the file and rearranges how the file is stored on your disk.

Compacting optimizes the performance of both Access databases and Access projects. However, in an Access project, compacting does not affect database objects — such as tables or views — that reside in the Microsoft SQL Server database instead of in the Access project itself. Also, compacting has no effect on autonumbering in an Access project. However, in an Access database, if you have deleted records from the end of a table that has an AutoNumber field, compacting the database resets the AutoNumber value; the AutoNumber value of the next record you add will be one greater than the AutoNumber value of the last undeleted record in the table.

Repairing an Access database In most cases, Microsoft Access detects that an Access database is damaged when you try to open it and gives you the option to compact it at that time. In some situations, Microsoft Access may not detect that an Access database is damaged. If an Access database behaves unpredictably, compact it.

Compacting a previous-version Access database won't convert it to Access 2000 format. Learn more about converting a previous-version Access database.

If you are compacting a multiuser (shared) database that is located on a server or shared folder, make sure that no one else has it open. You must have Open/Run and Open Exclusive permissions for an Access database in order to compact it. Learn more about assigning permissions.

Return to Compact an Access database or Access project


 About conditional formatting in a text box or other control on a form or report

About conditional formatting in a text box or other control on a form or report

If a control on a form or report contains values that you want to monitor, you can make it easier to spot different values in the control by applying conditional formatting. For example, you can make the control have a green background if sales exceed your forecast, or a red background if sales fall short. You can also make text bold, italic, or underlined, or enable or disable a control when it meets or doesn't meet criteria you specify.

By using conditional formatting, you can see how the values of controls compare to a constant or to the results of an expression. To specify the formatting criteria according to data in controls or according to multiple sets of criteria, you can use a logical expression. Learn about creating an expression.

You can set conditional formatting based on the value in a control, an arbitrary expression referencing another control, a user-defined Visual Basic for Applications function, or the control with focus. For example, you can set conditional formatting so that if an employee's salary exceeds $100,000 the field's background turns red. Or set formatting so that text in the City field is green and italic if a customer resides in Seattle.

If the value of the control changes and no longer meets the specified condition, Microsoft Access returns to the default formatting for the control. Conditional formatting remains applied to the controls until you remove the formatting, even though none of the conditions are met and the specified control formatting is not displayed.

Note You can not use wildcards — such as the * (asterisk), ?, or any other symbol — in criteria as substitutions for characters in text or numbers.

Return to Conditional formatting in a text box or other control on a form or report


 About converting an Access 2000 database to Access 97

About converting an Access 2000 database to Access 97

You can convert a Microsoft Access 2000 database to an Access 97 database if it is not a member of a replica set. Any functionality that is specific to Access 2000 is lost when you convert the database to Access 97.

Converting an Access 2000 database to an Access 97 database makes the following changes to the converted database.

  • Links to data access pages are lost.

  • Data that relies on Unicode support in Access 2000 might not be converted correctly. Access 97 uses characters from only a single code page — a numbered set of 256 characters. For example, an Access 97 database might use only ANSI characters. During conversion, the collating order of the original Access 2000 database determines which set of characters the resulting Access 97 database can use; any characters that are not in this set are not converted correctly.

  • An Access 2000 database containing a table with a FieldSize property of Decimal cannot be converted to Access 97. You must change the FieldSize property to another value such as Single or Double, or you must change the field's data type to Currency before you can successfully convert the database.

If you are converting a secured Access database, the user account that you use to log on must have the following permissions:

  • Open/Run and Open Exclusive permissions for the database itself. Read Design permissions for all objects in the database.

  • To secure the converted database, you must open it in Microsoft Access 97 and apply user-level security.

If you have protected the Access database with a password, you can convert it without removing the password. If you have protected the Microsoft Visual Basic for Applications (VBA) code with a password, you must supply the password in the Visual Basic Environment.


 About copying a database object

About copying a database object

You can easily customize an existing database object in a Microsoft Access database or Microsoft Access project by creating a copy of that object and modifying the copy.

A copy of the database object usually inherits the properties associated with the original database object. However, if you create a copy of a table in an Access project, the copy does not inherit the indexes, constraints, and triggers of the original table, and you must recreate these properties in the copy. Also, if you create a copy of a table or query in an Access database, and you want a subdatasheet in the table or query to exist in the copy as well, you must open the copy and insert the subdatasheet.

If you want to copy only the structure of a table instead of the table and its data, or if you want to append the data in a table to an existing table, use the Copy command to copy the table.

You can drag a database object from the Database window of an Access database or Access project to another Access database or Access project that is already open. You can copy a table, query or report by dragging it from the Database window to another Microsoft application.

Also, you can save some database objects as objects of another type.

Return to Copy a database object


 About creating custom Help for a form, report, or control

About creating custom Help for a form, report, or control

There are several ways to add Help to a Microsoft Access form, report, or control. If you want to display tips that pop up over controls when you move the mouse pointer over the control, you can use the ControlTipText property. Or you might want to use the StatusBarText property to display helpful information about a form or control in the status bar. You can also create tips for new toolbar buttons that you create.

If you want to have Help for a control pop up only when you click the What's This button [image] and then click a control, you can use a text editor or word-processing program to create a Help file. (The program must be able to save documents in Rich Text Format.) Then you can compile that Help file with Microsoft Help Workshop and attach it to a control by using the HelpFile and HelpContextID properties.

For forms and reports, you can create more extensive Help that is displayed when you press F1 by setting the HelpFile and HelpContextID properties of the form or report. For this type of Help, you can use either Microsoft Help Workshop or Microsoft HTML Help Workshop to create the Help file.

Notes

  • You can download Microsoft Help Workshop from the Microsoft Technical Support Web site.

  • Microsoft HTML Help Workshop is included with Microsoft Office 2000 Developer.

  • For more information about creating custom Help, see "Adding Help to Your Custom Solution" in the Microsoft Office 2000/Visual Basic Programmer's Guide. Learn how to obtain a copy of this book.

Return to Create custom Help for a form, report, or control


 About creating an expression

About creating an expression

When you create an expression, you combine identifiers, values, and operators into a unit that produces a result. Expressions can be as simple as an arithmetic expression, such as (1 + 1), that produces a numeric result, 2. Or they can perform complex operations on data, such as the following validation expression which generates an error if the value of the Country field is France, Italy, or Spain and the PostalCode field contains fewer than or more than five characters:

= [Country] In ("France", "Italy", "Spain") And Len([PostalCode])<>5

You can create an expression using the Expression Builder, or you can create it on your own by combining the elements of the expression to do what you want.

Return to create an expression


 About creating a field that looks up or lists values in tables

About creating a field that looks up or lists values in tables

Lookup lists

The most common Lookup list displays values looked up from a related table. For example, the SupplierID field in the Products table of the Northwind sample database displays this Lookup list:

Information from Suppliers table displayed in Lookup list in Products table

This list is created by looking up the SupplierID values in the Suppliers table and displaying the corresponding Supplier names. Picking a value from a Lookup list sets the foreign key value in the current record (SupplierID in the Products table) to the primary key value of the corresponding record in the related table (SupplierID in the Suppliers table). This creates an association to the related table to display (but not store) the Supplier names in the record. The foreign key (SupplierID) is stored but doesn't display. For this reason, any updates made to the data in the Suppliers table will be reflected in both the list and records in the Products table. You must define a Lookup list field from the table that will contain the foreign key and display the Lookup list. In this example, the Lookup list field would be defined from the Products table.

Value lists

A value list looks the same as a Lookup list, but consists of a fixed set of values you type in when you create it. A value list should only be used for values that will not change very often and don't need to be stored in a table. For example, a list for a Salutation field containing Mr., Mrs., or Ms. would be a good candidate for a value list. Choosing a value from a value list will store that value in the record — it doesn't create an association to a related table. For this reason, if you change any of the original values in the value list later, they will not be reflected in records added before this change was made.

You can add a new Lookup or value list field in either table Design view or table Datasheet view. However, if the field you want to use as the foreign key for a Lookup field already exists, you must open that field's table in Design view to define the Lookup field. For example, if you have a Products table that has a SupplierID field already defined, and you want to change it to a Lookup field to display supplier names from your Suppliers table, you must open the Products table in Design view to change SupplierID to a Lookup field.

Return to Create a field that looks up or lists values in tables


 About creating forms based on more than one table

About creating forms based on more than one table

Using a Form Wizard is the simplest and fastest way to create a form that brings data together from more than one table. A Form Wizard speeds up the process of creating a form because it does all the basic work for you. In the first screen of a Form Wizard, you can pick the fields you want to include in your form. These fields can be from one table or from multiple tables. When you use a Form Wizard to create a multiple-table form, Microsoft Access creates an SQL statement behind the form. The SQL statement includes the information about which tables and fields to use.

Multiple-table flat form

You can use a Form Wizard to create a form that displays data from multiple tables as a "flat form" or as a "hierarchical form." An example of a flat form is a form that shows products and product suppliers.

Multiple-table flat form

Multiple-table hierarchical form

A hierarchical form is a form with one or more subforms. Subforms are useful if you want to show data from tables that have a one-to-many relationship. For example, you could have a Categories form that includes data from a Categories table and a Products table.

Multiple-table hierarchical form

Synchronized forms

You may want to present your data hierarchically without using a subform. For example, if you have a form with lots of controls, you may not have room for a subform. In this case, you can use a Form Wizard to create synchronized forms. When you click a command button on one form, it opens another form that's synchronized with the record on the first form.

Return to Create a form based on more than one table


 About groups

About groups

You can organize different types of database objects into a group. A group consists of shortcuts to the database objects that belong to it; adding an object to a group does not change that object's original location. When you click the Objects bar and then click the icon for a particular object type, any database object of that type appears in the Object list — even if that object also belongs to a group. When you click the Groups bar in the Database window and then click the icon for your group, all of the database objects that you have added to the group appear in the Object list.

You can keep related objects of different types together in a group. For example, you can manage a form with multiple subforms more easily if you create a group that contains the main form, the subforms, and the tables or queries that they are based on. You can also create a group for the forms and reports that you use most often; when you click the icon for that group, both the forms and the reports appear in the Object list in the Database window.


 About customizing your application's environment with Microsoft Access user profiles

About customizing your application's environment with Microsoft Access user profiles

Microsoft Access provides database properties and startup options to meet most of your customization needs. However, if you're an application developer, you might want the added benefits of an Access user profile to customize your application's environment.

An Access user profile is a special set of Windows registry keys that you can create to override standard Access and Microsoft Jet database engine settings, and to specify additional run-time options. You then use the /profile command-line option to specify this Access user profile when you start your application.

You can use an Access user profile, for example, to:

  • Prevent standard Access settings that users might modify in their database properties and startup options from conflicting with your application needs.

  • Ensure that when you distribute your applications, other programs that use Microsoft Jet do not override custom settings.

  • Test your application under different configurations.

Note A user profile that you use to start Access from the command line is not the same thing as a user profile that's defined for logging into the operating system. An Access user profile applies only to Access, and only when you start Access from the command line. A user profile defined for the operating system applies to every application on the operating system and is used to maintain system data for individual users.


 About defining default values

About defining default values

You can use the DefaultValue property to specify a value that will be automatically entered when you add a new record. For example, if most of your suppliers are in New York, you could set the City field of the Suppliers table to have a default value of "New York." You can accept the default value or type a new value over it.

You can set the DefaultValue property for a field in table Design view or for a control in form Design view. In data access page Design view, use the Value property. In most cases, you'll want to add the default value to the field in table Design view, since that default value will be applied to controls based on that field (as long as you create the controls after setting the property in table Design view). If the control is unbound, however, or if it's based on data from a linked (external) table, you'll need to set the default value for the control in the form or data access page.

Return to Define a default value that is automatically entered in a field or control


 About defining the display format for a field or control

About defining the display format for a field or control

You can use the Format property to specify the data display format for a field or a control. For example, you can choose to have all dates formatted using the month/day/year format or some other format. You can choose from a list of predefined formats for fields with the AutoNumber, Number, Currency, Date/Time, and Yes/No data types, or you can create your own custom format. You can create a custom format for any field data type other than OLE Object.

You can set the Format property in table Design view, query Design view, form Design view, or report Design view. In most cases, you'll want to set the property for the field in table Design view. That way, the setting is automatically applied to the field in query Design view and to controls on a form or report bound to that field (as long as you create the controls after setting the property in table Design view). In certain cases, however, you may want to set the property in query Design view, form Design view, or report Design view. For example, you may want to display a different format in a table datasheet than in a report. You could set the Format property for the field in query Design view and then base your report on the query. If you're using an unbound control, you'll need to set the Format property in form Design view or report Design view.

Note If you want to create literal display characters that help you enter data in a predefined format, you may want to use an input mask instead of a format. For information on the differences between a format and an input mask, click [image] .

Return to Define the data display format for a field or control


 About defining the number of decimal places to display in a field or control

About defining the number of decimal places to display in a field or control

You can use the DecimalPlaces property to specify the number of decimal places to display in a Number or Currency field or a control with number or currency data. You can set the DecimalPlaces property in table Design view, query Design view, form Design view, or report Design view. In most cases, you'll want to set the property for the field in table Design view. This way, the setting is automatically applied to the field in query Design view and to controls on a form or report bound to that field (as long as you create the controls after setting the property in table Design view). In certain cases, however, you may want to set the property in query Design view, form Design view, or report Design view. For example, you may want to display a different number of decimal places in a table datasheet than in a report. You could set the DecimalPlaces property for the field in query Design view and then base your report on the query. If you're using an unbound control, you'll need to set the DecimalPlaces property in form Design view or report Design view.

Return to Define the number of decimal places to display in a field or control


 About deleting a group of records with a query

About deleting a group of records with a query

You can use a single delete query to delete records from a single table, from multiple tables in a one-to-one relationship, or from multiple tables in a one-to-many relationship, if cascading deletes are enabled (for example, all customers from Ireland and all their orders). However, if you need to include the "many" table along with the "one" table, in order to add criteria, you must run the query twice, since a query cannot delete records from the primary table and the related tables at the same time.

You can distinguish a one-to-many relationship in query Design view by looking at the joins between tables. If one end of a join is marked with the infinity symbol [image], it is a one-to-many relationship. If both ends are marked with a 1, it's a one-to-one relationship.

Return to Delete a group of records with a query


 About specifying a substitution font for dual-font support

About specifying a substitution font for dual-font support

In a datasheet, form, or report, you might need to display characters that are not supported by the default font. For example, if your data consists of both English-language and Asian-language characters, your default font may not support the Asian-language characters.

Dual-font support allows you to specify a substitution font. If the default font does not support a particular character, Microsoft Access then uses the substitution font to display that character. The font size and font weight are the same as the size and weight of the default font in that area of the datasheet, form, or report.

Note If your data contains only characters of non-Asian languages such as English, Greek, or Russian and characters of one Asian language, you should specify a substitution font. Microsoft Office does include a universal font, the Arial Unicode MS font, which contains all of the characters and symbols defined in the Unicode 2.1 standard. However, to ensure optimal performance, use this font only if necessary.

Learn about Unicode support and the Arial Unicode MS font.

Learn about multilingual support in Microsoft Office.

Return to Specify a substitution font for dual font support


 About field properties

About field properties

Each field has a set of properties that you use to customize how a field's data is stored, handled, or displayed. For example, you can control the maximum number of characters that can be entered into a Text field by setting its FieldSize property. You set a field's properties by displaying a table in Design view, selecting the field in the upper portion of the window, and then selecting the desired property in the lower portion of the window.

The properties that are available for each field are determined by the data type you select for the field.

Tip When you create a bound control on a form or report by dragging a field from the field list, Microsoft Access copies certain properties from that field to the control. This way you can be sure that you have consistent settings whenever you add fields to a form or report. For more information, click [image] .

Return to Set field properties to customize how data is stored, handled, or displayed


 About grouping records on the first n characters in a text value on a data access page

About grouping records on the first n characters in a text value on a data access page

This topic provides reference information about:

Data types required to group records on prefix characters

How a page that groups records on the first character in a field looks in Page view or in Microsoft Internet Explorer

How a page that groups records on the first characters in a field looks in Design view

Settings for properties in the Sorting And Grouping box

Data types required to group records on prefix characters

When you group records on the first n (or prefix) characters in a text field, the control you group on must be bound to a field of one with the following data types: a Text data type in a Microsoft Access database (.mdb); or a char, varchar, nchar, or nvarchar data type in a Microsoft Access project (.adp).

Return to top

How a page that groups records on the first character in a field looks in Page view or in Internet Explorer

To group records on the first n characters, you need two controls bound to the field you want to group on. You use one control to group the records by the specified number of prefix characters, and then display the prefix characters. You use the other control, which is in the next lower group level, to sort records and display the actual value of the field.

In the following example, the records come from the Products table. In the first group level, the records are grouped on the first character of the values in the ProductName field. In the next lower group level, the page displays and sorts the records by the actual values in the ProductName field.

Page that groups on the first characters in a field, in Page view or in Internet Explorer

Return to top

How a page that groups records on the first characters in a field looks in Design view

The following illustration shows the layout of the example page in Design view.

Page that groups on the first characters in a field, in Design view

Return to top

Settings for properties in the Sorting And Grouping box

The following table lists the properties that are set for the example page in the Sorting And Grouping box. When you don't specify ASC or DESC after the field name in the DefaultSort property, Microsoft Access sorts the records in ascending order.

Property | Group Record Source Products-ProductName | Group Record Source Products
CaptionSection | No | Yes
GroupHeader | Yes | Yes
GroupFooter | No | No
RecordNavigation Section | Yes | Yes
ExpandedByDefault | No | No
DataPageSize | 3 | 3
GroupOn | Prefix Characters | Each Value
GroupInterval | 1.0 | 1.0
DefaultSort | GroupOfProductName | ProductName

Note When you group on a field, Access creates an alias for the control by adding the prefix "GroupOf" to the control's name in the ControlSource property; for example, GroupOfProductName: ProductName. When you reference this control in an expression or property, you must use the alias.

Return to top

Return to Group records by the first n characters in a text value on a data access page


 About grouping records on intervals of autonumbered, currency, or numeric values on a data access page

About grouping records on intervals of autonumbered, currency, or numeric values on a data access page

This topic provides reference information about:

Data types required for grouping on intervals of autonumbered, currency, or numeric values

How a page that groups records on intervals of 100 dollars looks in Page view or in Microsoft Internet Explorer

How a page that groups records on intervals of 100 dollars looks in Design view

Settings for properties in the Sorting And Grouping box

Data types required for grouping on intervals of autonumbered, currency, or numeric values

When you group records by autonumbered, currency, or numeric values, the control you group on must be bound to a field with one of the following data types: an Autonumber, Currency, or Numeric data type in a Microsoft Access database (.mdb); or a decimal, numeric, int, smallint, tinyint, money, smallmoney, float, or real data type in a Microsoft Access project (.adp).

Return to top

How a page that groups records on intervals of 100 dollars looks in Page view or in Internet Explorer

To group records on an interval, you need two controls bound to the field you want to group on. You use one control to group the records and display the field values as intervals. You use the other control, which is placed in the next lower group level, to display the full value of the field. In the following example, the records come from a query named Sales. The records are grouped in intervals of 100 in a control bound to the SaleAmount field. In the next lower group level, the page displays, and sorts the records by, the actual values in the SaleAmount field.

Page that groups records on intervals of 100 dollars, in Page view or Internet Explorer

Return to top

How a page that groups records on intervals of 100 dollars looks in Design view

The following illustration shows the layout of the example page in Design view.

Page that groups records on intervals of 100 dollars, in Design view

Return to top

Settings for properties in the Sorting And Grouping box

The following table lists the properties that are set for the page in the Sorting And Grouping box. When you don't specify ASC or DESC after the field name in the DefaultSort property, Microsoft Access sorts the records in ascending order.

Property | Group Record Source Sales-SaleAmount | Group Record Source Sales
CaptionSection | No | Yes
GroupHeader | Yes | Yes
GroupFooter | No | No
RecordNavigation Section | Yes | Yes
ExpandedByDefault | No | No
DataPageSize | 3 | 3
GroupOn | Interval | Each Value
GroupInterval | 100 | 1.0
DefaultSort | GroupOfSaleAmount | SaleAmount

Note When you group on a control, Access creates an alias for the control by adding the prefix "GroupOf" to the control's name in the ControlSource property; for example, GroupOfSaleAmount: SaleAmount. When you reference this control in an expression or property, you must use the alias.

Return to top

Return to Group records on intervals of autonumbered, currency, or numeric values on a data access page


 About grouping records on intervals of date or time values on a data access page

About grouping records on intervals of date or time values on a data access page

This topic provides reference information about:

Data types required for grouping on intervals of date or time values

How a page that groups records by month looks in Page view or in Microsoft Internet Explorer

How a page that groups records by month looks in Design view

Settings for properties in the Sorting And Grouping box

Data types required for grouping records on intervals of date or time values

When you group records on date or time intervals, the control you group on must be bound to a field with one of the following data types: a Date/Time data type in a Microsoft Access database (.mdb), or a datetime or smalldatetime data type in a Microsoft Access project (.adp).

Return to top

How a page that groups records by month looks in Page view or in Internet Explorer

To group records on an interval of date or time values, you need two controls. The control you group on is bound to the field that stores the date or time values and is hidden. The other control is bound to an expression that returns the interval of the date or time and is visible. In the following example, the records come from a query named Summary. The page uses an invisible control bound to the ShippedDate field to group records by month in the higher group level. In the same group level, another control, which is visible, is bound to an expression that returns the month equivalent of the ShippedDate field.

Data access page that groups records by month, in Page view

Return to top

How a page that groups records by month looks in Design view

In Design view of the example page, you can see the hidden control that is used to group the records in the first group level.

Data access page that groups records by month, in Design view

Return to top

Settings for properties in the Sorting And Grouping box

The following table lists the properties that are set for the page in the Sorting And Grouping box. When you don't specify ASC or DESC after the field name in the DefaultSort property, Microsoft Access sorts the records in ascending order.

Property | Group Record Source Summary-ShippedDate | Group Record Source Summary
CaptionSection | No | Yes
GroupHeader | Yes | Yes
GroupFooter | No | No
RecordNavigation Section | Yes | Yes
ExpandedByDefault | No | No
DataPageSize | 3 | 3
GroupOn | Year | Qtr
GroupInterval | 1.0 | 1.0
DefaultSort | GroupOfShippedDate | ShippedDate

Note When you group on a control, Access creates an alias for the control by adding the prefix "GroupOf" to the control's name in the ControlSource property; for example, GroupOfShippedDate: ShippedDate. When you reference this control in an expression or property, you must use the alias.

Return to top

Return to Group records on intervals of date or time values on a data access page


 About indexes in an Access database

About indexes in an Access database

An index helps Microsoft Access find and sort records faster. Microsoft Access uses indexes in a table as you use an index in a book: to find data, it looks up the location of the data in the index. You can create indexes based on a single field or on multiple fields. Multiple-field indexes enable you to distinguish between records in which the first field may have the same value.

Deciding which fields to index

You'll probably want to index fields you search frequently, fields you sort, or fields that you join to fields in other tables in queries. However, indexes can slow down some action queries such as append queries, when the indexes for many fields need to be updated while performing these operations.

The primary key of a table is automatically indexed, and you can't index a field whose data type is OLE Object. For other fields, you should consider indexing a field if all the following apply:

  • The field's data type is Text, Number, Currency, or Date/Time.

  • You anticipate searching for values stored in the field.

  • You anticipate sorting values in the field.

  • You anticipate storing many different values in the field. If many of the values in the field are the same, the index may not significantly speed up queries.

Multiple-field indexes

If you think you'll often search or sort by two or more fields at a time, you can create an index for that combination of fields. For example, if you often set criteria for LastName and FirstName fields in the same query, it makes sense to create a multiple-field index on both fields.

When you sort a table by a multiple-field index, Microsoft Access sorts first by the first field defined for the index. If there are records with duplicate values in the first field, Microsoft Access sorts next by the second field defined for the index, and so on.

Return to Create an index to find and sort records faster


 About creating input masks

About creating input masks

You can use the InputMask property to create an input mask (sometimes called a "field template") that uses literal display characters to control how data is entered in a field or control. For example, the following input mask requires that all phone number entries contain exactly enough digits to make up a U.S. area code and telephone number, and that only digits can be entered in each blank. You just fill in the blanks.

Telephone number input mask

You can set the InputMask property in table Design view, query Design view, or form Design view. In most cases, you'll want to set the property for the field in table Design view. This way, the input mask is automatically applied to the field in query Design view and to controls on a form or report bound to that field (as long as you create the control after setting the property in table Design view). In certain cases, however, you may want to set the property in query Design view or form Design view. For example, you might want to omit the input mask in a table but include it in a text box. If you're using an unbound control, you'll need to set the InputMask property in form Design view.

Note If you want to specify how saved data is displayed, you may want to use a format instead of an input mask. For information on the difference between a format and an input mask, click [image] .

Return to Create an input mask to control how data is entered in a field or control


 About performing calculations in a query

About performing calculations in a query

You perform calculations in a query using:

  • Predefined calculations, called "totals," to compute the following amounts for groups of records or for all the records combined in the query: sum, average, count, minimum, maximum, standard deviation, or variance.

  • A custom calculation to perform numeric, date, and text calculations on each record using data from one or more fields. You need to create a new calculated field directly in the design grid for these types of calculations.

Instead of displaying a calculation's results, you can use them:

  • As criteria to determine the records the query selects or to determine which records to perform an action on.

  • To update data from an update query.

Return to Perform calculations in a query


 About pop-up forms and custom dialog boxes

About pop-up forms and custom dialog boxes

Pop-up forms

You can create a pop-up form to display information to a user or to prompt a user for data. A pop-up form stays on top of other open forms, even when another form is active. A pop-up form can be modeless or modal. When a pop-up form is modeless, you can access other objects and menu commands while the form is open. For example, on a Suppliers form, you could add a command button that displays a Product List pop-up form. The pop-up form displays the products available from the current supplier in the Suppliers form.

Modeless pop-up form

Custom dialog boxes

When a pop-up form is modal, you can't access any other objects or menu commands unless you hide or close the form. A modal pop-up form is called a custom dialog box. For example, you could create a custom dialog box that asks what report you want to print.

Custom dialog box

To read more about using forms to collect and display information, see "Using Forms to Collect, Filter, and Display Information," in Building Applications with Forms and Reports.

Return to Create a pop-up form or custom dialog box


About restoring toolbars or menu bars, or individual buttons, commands, or menus

You can restore different aspects of a built-in toolbar or menu bar:

  • Restore an entire built-in toolbar or menu bar to its default settings to display the original buttons or menus and commands and to restore their original property settings. Microsoft Access will also restore the property settings for the toolbar or menu bar itself, including restoring its screen location and size, and hiding or showing the bar based on its original state.

  • Restore all the original buttons or menus (including shortcut menus) and commands and their property settings without restoring the properties of the toolbar or menu bar (such as the screen location and size).

  • Restore an individual button, command, or menu (except an individual shortcut menu) without affecting other toolbar and menu bar settings. When you restore an individual button, command, or menu, you restore how it appeared originally.

Return to Restore toolbars or menu bars, or individual buttons, commands, or menus


 About restricting or validating data

About restricting or validating data

Microsoft Access provides a variety of ways to control how data is entered into your database. For example, you can limit the data that can be entered into a field by defining a validation rule for that field. If the data that is entered into the field breaks the rule, Microsoft Access will display a message telling the user what kind of entries are allowed. Another method of controlling data entry is to create an input mask to restrict the kind of values that can be entered in positions across the field. You can perform these simple forms of validation and restriction by setting properties for fields in tables, or by setting properties for controls on forms.

In most cases, it is preferable to define data validation and restriction by setting a field's properties in table Design view. This saves you time, because whenever you use that field in a form, the field's validation rule and other properties will apply to data entry performed using the form.

However, if the data entered into a control on a form isn't bound to a field in a table, and you need to restrict or validate data entry, you must define those properties in the form. Additionally, there are situations where you must use macros or Visual Basic for Applications code in conjunction with a form to perform more complex validation. For example, you might want to be able to override your validation rule or compare values from different tables.

Return to Restrict or validate data


 About setting a hyperlink base for an Access database or Access project

About setting a hyperlink base for an Access database or Access project

When you create a hyperlink in a Microsoft Access database or Microsoft Access project, you can make the path to the destination of the hyperlink a fixed location (absolute link), which identifies the destination by its full address — such as C:\My Documents\Sales.doc — or you can make the path a relative link. You can easily change the path of a relative link by setting the hyperlink base for the Access database or Access project. The value of the HyperlinkBase property of an Access database or Access project can be a URL, or a location on a network or your hard drive.

For example, you may want hyperlinks to Web pages on an intranet server in your Access database or Access project. If you set the value of the hyperlink base to http://servername1, you can create a hyperlink as a relative link, such as webpage.htm. Clicking this hyperlink opens the web page located at http://servername1/webpage.htm. If you then move the web pages to a different intranet server, you only need to change the value of the HyperlinkBase property to http://servername2 to adjust all of the relative links in the Access database or Access project.

Return to Set hyperlink base for an Access database or Access project


 About using an Access database with several versions of Microsoft Access

About using an Access database with several versions of Microsoft Access

In some situations, the users of a shared Microsoft Access database may not all be able to upgrade to Microsoft Access 2000 at the same time. You can share an Access database with users of different versions of Microsoft Access, without having to alter your original database. You can upgrade parts of an Access database to Microsoft Access 2000 so that it can take advantage of many new features, and still use the original unchanged database for users of previous versions of Microsoft Access. Users of all versions can share the same data.

You can use this strategy whether your Access database is in one file, or is a front-end/back-end application. To use an Access database that is one file in several versions of Microsoft Access, convert it to a front-end/back-end application. The data in the back end remains in the oldest version of Microsoft Access, and you use a front end that has been converted to Access 2000.

To use a front-end/back-end application with several versions of Microsoft Access, convert the front end of the application.

Return to Use an Access database with several versions of Microsoft Access


 About using file properties to locate files

About using file properties to locate files

File properties are details about a file that help identify it — for example, a descriptive title, the author name, the subject, and keywords that identify topics or other important information in the file. You can set file properties for the database you're working on and for any Microsoft Access database, Microsoft Access project, or data access page.

There are three different types of properties that you can use to locate files:

Built-in file properties Built-in file properties are properties (such as author, title, and subject) that already exist for which you can enter a value. For example, you can enter the database author's name so that you can search for all databases created by that person.

Custom file properties You can create custom file properties that include any value you assign. For example, you can create a database property that stores the version number of your database.

Automatically updated file properties Statistics such as size of database, date of creation, and date that database was last modified are database properties that are automatically maintained for you. For example, you could search for all databases created after March 3, 1998, or last modified yesterday.


 About validating or restricting data entry in tables

About validating or restricting data entry in tables

Microsoft Access provides a variety of ways to control how data is entered in fields in your table.

The first thing you should consider is whether a field has an appropriate data type. For example, Date/Time fields only allow entry of valid date and time formats. If you are currently using a Text field for such information, it may be appropriate to change the field to a Date/Time field.

There are also additional properties that you can set for a field to provide further control over the values that can be entered into the field:

  • For Number fields, you can choose from a variety of field sizes to control the kind and range of values that can be entered.

  • For Text fields, you can set the maximum number of characters that can be entered.

  • For all but AutoNumber fields (which generate their own data), you can require that data be entered in the field.

  • For Text, Date/Time, and Number fields, you can define an input mask to provide blanks to fill in and can control what values can be entered in those blanks.

  • For all but OLE Object fields, you can prevent duplicate values from being entered into a field or combination of fields.

You can also define two kinds of validation rules: field validation rules and record validation rules. Validation rules allow you to define a rule to limit what will be accepted.

  • A field validation rule is used to check the value entered into a field as the user leaves the field. For example, you could define ">=10 And <=100" as the validation rule for a Number field to allow only values from 10 to 100 to be entered.

  • A record validation rule controls when an entire record can be saved. Unlike field validation rules, record validation rules can refer to other fields in the same table. This makes them useful when you want to compare values in different fields. For example, you could define "[RequiredDate]<=[OrderDate]+30" as the validation rule for an Orders table. This rule would make sure that the date entered into the RequiredDate field is within 30 days of the date in the OrderDate field.

Both kinds of validation rules will display a message that you define when the rule is broken to inform the user how to properly enter data.

Return to Validate or restrict data entry in tables


 About validating values entered in a field, record, or control

About validating values entered in a field, record, or control

To validate a value entered in a field, record, or control, you create a validation rule and then define the text that you want to display when the data entered doesn't meet that rule. For example, you might create a rule that says all dates entered must be in 1998.

There are several ways that you can define validation rules in Microsoft Access. This topic provides reference information about:

Field validation rules

Record validation rules

Control validation rules

Form-level validation with macros or Visual Basic for Applications

Field validation rules

You can ensure that data is entered correctly into a field by defining a field validation rule. A field validation rule is used to check the value entered into a field as the user leaves the field. A message you define is displayed if the value breaks the validation rule. You define a field validation rule in a table.

Return to top

Record validation rules

A record validation rule controls when an entire record can be saved. Unlike field validation rules, record validation rules can refer to other fields. This makes them useful when you want to compare values from different fields in a table. You define a record validation rule in a table.

Return to top

Control validation rules

You can also define a validation rule in a control on a form. In most cases, it's best to define the validation rule for the field in the table, because any field validation rule is automatically applied to a control based on that field (as long as you create the control after defining the validation rule in table Design view). But you must define the validation rule in the control if the control is unbound or if the control is based on data in a linked (external) table. You must also define the validation rule in the control if the validation rule refers to fields or controls in other forms, or if the validation rule contains domain aggregate functions, aggregate functions, user-defined functions, or the CurrentUser or Eval function.

Return to top

Form-level validation with macros or Visual Basic for Applications

There are also situations where you must use macros or Visual Basic for Applications code in conjunction with a form to perform more complex validation. For example, you might want to be able to override your validation rule under certain circumstances or compare values from different tables.

Return to top


About the Windows registry

Microsoft Access stores its initialization information in the Windows registry. The Windows registry is a centralized database that Windows uses to set up and configure the software and hardware running in your Windows environment. The registry is analogous to the .ini files used under Windows 3.x: Each subkey in the registry is similar to a bracketed heading in an .ini file, and the entries under each registry subkey are similar to the entries under an .ini file heading.


 About working with SQL in queries, forms, reports, macros, and modules

About working with SQL in queries, forms, reports, macros, and modules

You can use SQL, or Structured Query Language, to query, update, and manage relational databases such as Microsoft Access. When you create a query in query Design view, behind the scenes Microsoft Access constructs the equivalent SQL statements. You can view or edit the SQL statement in SQL view. After you make changes to a query in SQL view, the query might not be displayed the way it was previously in query Design view.

Some queries can't be created in the design grid. For pass-through, data-definition, and union queries, you must create SQL statements directly in SQL view.

You can also use SQL statements in many places in Microsoft Access where you can enter the name of a table, query, or field. In some cases, Microsoft Access fills in the SQL statement for you. For example, when you use a wizard to create a form or report that gets data from more than one table, Microsoft Access automatically creates an SQL statement that it uses as the setting for the RecordSource property of the form or report. When you create a list box or combo box with a wizard, Microsoft Access creates the SQL statement and uses it as the setting for the RowSource property of the list box or combo box. You can also use SQL statements in subqueries in the query design grid, in the SQL Statement argument of the RunSQL macro action, and in code.

Return to Work with SQL in queries, forms, reports, macros, and modules


Work with MDE files

What do you want to do?

Learn about MDE files

Save a Microsoft Access database as an MDE file

Learn about using other forms of security with an Access database that is saved as an MDE file

Learn about saving a replicated Access database as an MDE file

Learn about saving an Access database that references another Access database as an MDE file


 About appending records with AutoNumber fields

About appending records with AutoNumber fields

Depending on how you design an append query, Microsoft Access can automatically add new AutoNumber values, or retain the values from the original table.

  • To have Microsoft Access add AutoNumber values automatically, don't drag the AutoNumber field to the query design grid when you create the query.

    With this method, Microsoft Access appends records and automatically inserts AutoNumber values. The first record appended has a value that is one larger than the largest entry that was ever entered in the AutoNumber field (even if the record that contained the largest AutoNumber value has been deleted).

  • To keep the AutoNumber values from the original table, drag its AutoNumber field to the query design grid when you create the query.

    If the AutoNumber field in the table you're appending to is a primary key, and the original table and the table you're appending to contain duplicate AutoNumber values, use the first method instead.


 About AutoLookup queries that enter data automatically

About AutoLookup queries that enter data automatically

You can design a multiple-table query to automatically fill in certain field values for a new record. When you enter a value in the join field in the query or in a form, report, or data access page based on the query, Microsoft Access looks up and fills in existing information related to that value. For example, if you know the value in the join field between a Customers table and an Orders table (typically, a customer identifier such as CustomerID), you could enter the customer ID and have Microsoft Access enter the rest of the information for that customer. If no matching information is found, Microsoft Access displays an error message when the focus leaves the record.

Enter a value in a join field

Remaining data is retrieved

For AutoLookup to work, certain conditions must be met:

  • The query must be based on more than one table and the tables must have a one-to-many relationship. (Referential integrity doesn't have to be enforced.)

  • The join field on the "one" side of the relationship must have a unique index. A unique index means that the field is a primary key or its Indexed property in table Design view is set to Yes (No Duplicates).

  • The join field you add to the design grid must come from the table on the "many" side of the one-to-many relationship. (In other words, it's the foreign key for that table.) For AutoLookup to work, this field can't be a primary key and its Indexed property can't be set to Yes (No Duplicates). For example, in a query that includes the Customers and Orders tables, drag to the design grid the CustomerID field from the Orders table, not the one from the Customers table.

  • The value you enter in the join field from the "many" side must already exist in the join field from the "one" side.

When the value of the join field from the "many" side of the relationship is added or changed in a record, Microsoft Access automatically finds and displays the associated values from the table on the "one" side of the relationship.

While you can always update the join field from the "many" side of a relationship, you can update the join field from the "one" side only if you enabled cascading updates when defining the relationship between the tables. Either way, when you update data, Microsoft Access automatically recalculates any totals or expressions in the query that are dependent on the updated data.


 About right-to-left language features

About right-to-left language features

Language-specific information

To enable the right-to-left features in Microsoft Access 2000, you must be running a 32-bit Microsoft Windows operating system that has right-to-left support — for example, the Arabic version of Microsoft Windows 95. Learn about system or special requirements for right-to-left languages.

When languages such as Arabic, Farsi, Hebrew, and Urdu are enabled for editing, you have several features available to you to make working in a right-to-left or bidirectional environment easier.

More information

Learn about bidirectional fonts

Learn about checking the spelling of bidirectional text

Learn about using bidirectional text in expressions

Learn about right-to-left features compatibility

Change the default for a right-to-left feature

Use database calendars

Use right-to-left sort orders

Import, export, and link right-to-left tables in text formats

Learn about code page and text layout support for right-to-left HTML files

Change table direction

Change query direction

Use right-to-left features in forms and reports

Set right-to-left properties in controls

Convert reports saved as text files to ANSI characters

Use right-to-left features in data access pages

About creating macros in right-to-left applications

About creating modules in right-to-left applications


 Examples of working with Null values using calculated fields

Examples of working with Null values using calculated fields

You enter the expression in the Field cell in the query design grid. The fields you reference in the expression are from the tables or queries in the current query.

Expression | Description
CurrentCountry: IIf(IsNull([Country]), " ", [Country]) | Uses the IIf and IsNull functions to display an empty string in the CurrentCountry field if the Country field is Null; otherwise, it displays the contents of the Country field.
LeadTime: IIf(IsNull([RequiredDate] - [ShippedDate]), "Check for a missing date", [RequiredDate] - [ShippedDate]) | Uses the IIf and IsNull functions to display in the LeadTime field the message "Check for a missing date" if the value of either the RequiredDate or ShippedDate fields is Null; otherwise, it displays the difference.
SixMonthSales: Nz([Qtr1Sales],0) + Nz([Qtr2Sales],0) | Displays in the SixMonthSales field the total of the values in the first- and second-quarter sales fields combined, using the Nz function to convert the Null values to zero first.
IIf(IsNull([UnitPrice]),0,[UnitPrice]) | Changes a Null value to a zero (0) in the UnitPrice field.

Note When you use an arithmetic operator (+, -, *, /) in an expression and the value of one of the fields in the expression is Null, the result of the entire expression will be Null. If some records in one of the fields you used in the expression might have a Null value, you can convert the Null value to zero by using the Nz function, as shown in the preceding table. For more information on the Nz function, click [image] .


 Example of a subquery in a calculated field

Example of a subquery in a calculated field

You enter the expression in the Field cell in the query design grid. The fields you reference in the expression are from the tables or queries in the current query.

Expression | Description
Cat: (SELECT [CategoryName] FROM [Categories] WHERE [Products].[CategoryID]=[Categories].[CategoryID]) | Displays the CategoryName if the CategoryID from the Categories table is the same as the CategoryID from the Products table.


 Examples of using SQL and domain aggregate functions in calculated fields

Examples of using SQL and domain aggregate functions in calculated fields

You enter the expression in the Field cell in the query design grid. The fields you reference in the expression are from the tables or queries in the current query.

Expression | Description
Count(*) | Uses the Count function to count the number of records in the query, including records with Null (blank) fields.
FreightPercentage: Sum([Freight])/Sum([Subtotal]) *100 | Displays in the FreightPercentage field the percentage of freight charges in each subtotal, by dividing the sum of the values in the Freight field by the sum of the values in the Subtotal field. (This example uses the Sum function.) The Total row in the design grid must be displayed, and the Total cell for this field must be set to Expression. If the Format property of the field is set to Percent, don't include the *100.
AverageFreight: DAvg("[Freight]", "[Orders]") | Uses the DAvg function to display in the AverageDiscount field the average discount given on all orders combined in a totals query.

For more information on using domain aggregate functions, click [image] .


 Examples of performing arithmetic operations in calculated fields

Examples of performing arithmetic operations in calculated fields

You enter the expression in the Field cell in the query design grid. The fields you reference in the expression are from the tables or queries in the current query.

Expression | Description
PrimeFreight: [Freight] * 1.1 | Displays freight charges plus 10 percent in the PrimeFreight field.
OrderAmount: [Quantity] * [UnitPrice] | Displays the product of the values in the Quantity and UnitPrice fields in the OrderAmount field.
LeadTime: [RequiredDate] - [ShippedDate] | Displays the difference between the values in the RequiredDate and ShippedDate fields in the LeadTime field.
TotalStock: [UnitsInStock]+[UnitsOnOrder] | Displays the sum of the values in the UnitsInStock and UnitsOnOrder fields in the TotalStock field.
FreightPercentage: Sum([Freight])/Sum([Subtotal]) *100 | Displays in the FreightPercentage field the percentage of freight charges in each subtotal, by dividing the sum of the values in the Freight field by the sum of the values in the Subtotal field. (This example uses the Sum function.) The Total row in the design grid must be displayed, and the Total cell for this field must be set to Expression. If the Format property of the field is set to Percent, don't include the *100.

Note When you use an arithmetic operator (+, -, *, /) in an expression and the value of one of the fields in the expression is Null, the result of the entire expression will be Null. If some records in one of the fields you used in the expression might have a Null value, you can convert the Null value to zero using the Nz function; for example:

Nz([UnitsInStock],0)+Nz([UnitsOnOrder],0)

For more information on the Nz function, click [image] .


 Examples of manipulating and calculating dates in calculated fields

Examples of manipulating and calculating dates in calculated fields

You enter the expression in the Field cell in the query design grid. The fields you reference in the expression are from the tables or queries in the current query.

Expression | Description
LagTime: DateDiff("d", [OrderDate], [ShippedDate]) | Uses the DateDiff function to display in the LagTime field the number of days between the order date and ship date.
YearHired: DatePart("yyyy",[HireDate]) | Uses the DatePart function to display in the YearHired field the year each employee was hired.
Date( )- 30 | Uses the Date function to display the date 30 days prior to the current date.


 Examples of manipulating text values in calculated fields

Examples of manipulating text values in calculated fields

You enter the expression in the Field cell in the query design grid. The fields you reference in the expression are from the tables or queries in the current query.

Expression Description

FullName: [FirstName] & " " & [LastName] | Displays the value of the FirstName and LastName fields, separated by a space, in the FullName field.
Address2: [City] & " " & [Region] & " " & [PostalCode] | Displays the value of the City, Region, and PostalCode fields, separated by spaces, in the Address2 field.
ProductInitial: Left([ProductName], 1) | Uses the Left function to display in the ProductInitial field the first character of the value in the ProductName field.
TypeCode: Right([AssetCode], 2) | Uses the Right function to display in the TypeCode field the last two characters of the value in the AssetCode field.
AreaCode: Mid([Phone],2,3) | Uses the Mid function to display in the AreaCode field the three characters starting with the second character of the value in the Phone field.


 Color Builder

Color Builder

The Color Builder is a Microsoft Access tool used to select colors from the palette or to create custom colors that you can save and use in forms and reports.

To run this builder, click the Build button [image] next to the appropriate property in the property sheet.


Examples of complex optimizable expressions

These examples assume that you created indexes for the LastName and HireDate fields but not the MiddleInitial or FirstName fields. The following table lists examples of combined simple expressions and the extent to which the result is optimized.

Optimizable expression | Operator | Optimizable expression | Result
[LastName]="Smith" | And | [Hire Date]<#12/30/90# | Rushmore-optimizable
[LastName]="Smith" | Or | [Hire Date]<#12/30/90# | Rushmore-optimizable

Optimizable expression | Operator | Expression not optimizable | Result
[LastName]="Smith" | And | [MiddleInitial]="C" | Partially optimizable (but doesn't use Rushmore)
[LastName]="Smith" | Or | [MiddleInitial]="C" | Not optimizable

Expression not optimizable | Operator | Expression not optimizable | Result
[FirstName]="Terry" | And | [MiddleInitial]="C" | Partially optimizable (but doesn't use Rushmore)
[FirstName]="Terry" | Or | [MiddleInitial]="C" | Not optimizable


Considerations when designing or modifying queries in a multiuser environment

If you open a query to make design changes and someone else modifies the query design before you have finished, Microsoft Access displays a message telling you that the design has changed since you started working. You can either replace the new changes with your changes or save your version of the query with a different name. If others are using the query to view data while you're changing the design, they don't see the design changes until they close and reopen the query.


 Considerations when setting options in the Startup dialog box

Considerations when setting options in the Startup dialog box

  • The Startup options apply only to the current Microsoft Access database or Microsoft Access project.

  • When you specify a setting in the Startup dialog box, you automatically set the Access database or Access project property associated with that setting. For a list of those properties, click [image] .

  • The Startup properties don't override the property settings for a specific toolbar, menu bar, shortcut menu, form, or report. For example, the Menu Bar and Shortcut Menu Bar options in the Startup dialog box don't override the property settings for specific forms or reports that have a custom menu bar or shortcut menu. Thus, when you open a form or report, Microsoft Access displays the custom menu bar attached to the form or report instead of the global menu bar specified in the Startup dialog box.

  • You can use the Startup dialog box instead of or in addition to an AutoExec macro. An AutoExec macro runs after the Startup options have taken effect; therefore, you should avoid any actions in an AutoExec macro that change the effect of the Startup option settings. For example, if you specify a form in the Display Form/Page box in the Startup dialog box, and you also use the OpenForm action in an AutoExec macro, Microsoft Access first displays the form specified in the Startup dialog box, then immediately displays the form specified in the OpenForm action.

  • In an Access database, if user-level security has been defined for your database, you can prevent users from changing the settings in the Startup dialog box by making sure they haven't been granted Administer permission for the database. For more information, click [image] .

  • To bypass the Startup option settings, hold down the Bypass (SHIFT) key while opening the database.


 Convert Access Basic Code to Visual Basic

Convert Access Basic Code to Visual Basic

In Microsoft Access 95, Visual Basic for Applications replaced Access Basic, which was used in versions 1.x and 2.0 of Microsoft Access. In most respects, Visual Basic is identical to Access Basic, and Microsoft Access makes most necessary conversions to your code automatically when you convert your database.

However, the conversion process makes some changes to your code that you need to be aware of, and there are some additional changes that you must make yourself in order for your application to run successfully in Microsoft Access 2000.

Note The /runtime command-line switch is not available in the stand-alone or Office Professional Edition versions of Microsoft Access 2000. However, the /runtime command-line switch is available in the Office Developer Edition version of Microsoft Access 2000.

Calling the Windows Application Programming Interface

If your existing version 1.x or 2.0 Access Basic code makes calls to the Windows application programming interface (API), you may need to modify these calls when you convert your database. Versions 1.x and 2.0 of Microsoft Access are 16-bit applications and run on 16-bit versions of Windows. Microsoft Access 2000 is a 32-bit application and runs on 32-bit versions of Windows — Windows 95 and the Windows NT platform.

Check any Declare statements to ensure that they refer to the correct 32-bit dynamic-link libraries (DLLs). For example, 32-bit versions of Windows include User32.dll; in earlier versions of Windows, this DLL is called User.dll. For more information, see Convert Code That Calls a DLL.

The names of some functions in the Windows API have changed. Additionally, functions in the 32-bit Windows API are case-sensitive. For a complete reference, see the Microsoft Win32 Software Development Kit.

Some Properties and Optional Arguments Are Strictly Typed

Certain properties that returned Variant values in previous versions of Microsoft Access now return strings. Code that includes these properties will now run faster; however, when you convert a database from a previous version of Microsoft Access to Microsoft Access 2000, you should verify that no errors are introduced by these new return values.

In addition, some optional arguments which were of type Variant in previous versions of Microsoft Access are now strictly typed. Affected methods, properties, and functions include the GoToPage method of a Form object, the OpenCurrentDatabase, Echo, Quit, CreateForm, CreateReport, CreateControl, and CreateReportControl methods of the Application object, the Column property of a combo box or list box, and the domain aggregate functions. If your code includes any of these elements, you may want to verify that no errors are introduced when you convert your database.

To check for errors, first compile all code in the database. Next check for run-time errors when you run your code. The errors most likely to occur are a "Type mismatch" error, or an "Invalid use of Null" error.

You should also check for silent errors that may be introduced into your code when you convert a database. For example, the RecordSource property of a control previously returned a Variant value, but now returns a string. A string can't contain a Null value, although a Variant can. Code in a converted database that checks whether the value of the RecordSource property is Null will no longer run properly, because the value of the RecordSource property will never be Null. The following procedure is an example of code that checks whether the value of the RecordSource property of a text box is Null.

Private Sub Form_Load()
    If IsNull(Me.RecordSource) Then
        Me.Recordsource = "Employees"
    End If
End Sub

In Microsoft Access 2000, the IsNull function will never return True for the value of the RecordSource property. If the RecordSource property has not already been set in the previous example, its value is an empty string, the value returned by the IsNull function is False, and the procedure will never enter the If...Then construct to set the RecordSource property.

To correct the code in the previous example, use the Len function to check the length of the string returned by the RecordSource property to determine whether it is an empty string. The following line corrects the code in the previous example:

If Len(Me.RecordSource) = 0 Then
    ' Remainder of procedure here.

Changes to Modules

In versions 1.x and 2.0 of Microsoft Access, modules containing general procedures not specific to any form or report module are called global modules. In Microsoft Access 2000, these are called standard modules.

Microsoft Access 2000 includes class modules, which you can use to create custom objects. Any public procedures in a class module become methods and properties of a custom object when you create a new instance of the class. Class modules exist both independently and in association with forms and reports. For more information about class modules, see Program with Class Modules.

The CurrentDb Function Versus DBEngine(0)(0)

Use the CurrentDb method instead of DBEngine(0)(0) to return a Connection object variable that points to the current database. The CurrentDb function creates another instance of the current database, whereas DBEngine(0)(0) refers to the open copy of the current database. Using DBEngine(0)(0) limits your ability to use more than one variable of type Database that refers to the current database.

The DBEngine(0)(0) syntax is still supported, so Microsoft Access doesn't change your code during the conversion process. However, you should consider making this modification to your code in order to avoid possible conflicts in a multiuser environment.

The CurDir Function

The CurDir function behaves differently than it does in version 1.x or 2.0 due to the way that applications interact with Windows 95. Since each application has its own current folder, setting the current folder in Windows 98 by double-clicking an icon doesn't affect the current folder in Microsoft Access. The CurDir function in Microsoft Access 2000 always returns the current path.

Assigning an OLE Object to a Variable

If you manipulate OLE objects or other binary data in your code, you should use an array of bytes to store binary data. In versions 1.x and 2.0 of Microsoft Access, you assign OLE objects, or other binary data less than 64K in size, to string variables when you need to manipulate the objects or data in code. You also assign the data returned by the GetChunk method to string variables. However, Visual Basic supplies a Byte data type and byte functions such as LeftB and RightB. In Microsoft Access 2000, you should store binary data in an array of bytes instead of a string variable, and you should use the byte functions to manipulate that data.

Declare DDE Channels as Variant or Long

If you use the DDEInitiate function to open a DDE channel, you can declare the variable that stores the channel number, which is a Long value, as either a Variant or Long value. In versions 1.x and 2.0 of Microsoft Access, the channel number is an Integer value, so you must modify any Declaration statements in your code that create variables of type Integer to store the channel number.

String Conversion Fails If the String Contains a Percent Sign (%)

You can't assign a string containing a percent sign to a variable or a field that has a numeric data type, as in the following example:

Dim intX As Double
    intX = "10"                ' This works.
    intX = "10%"            ' This returns an error.

The hWnd Property

If you use the hWnd property in your code to pass a window handle of a form or a report to a Windows routine, you should pass the value directly to the routine. You shouldn't assign the value of this property to a variable. For example:

If Not IsZoomed(Screen.ActiveForm.hWnd) Then
    DoCmd.Maximize
EndIf

In versions 1.x and 2.0 of Microsoft Access, the hWnd property of a form or report is an Integer value. In Microsoft Access 2000, the hWnd property is a Long value, which you must change your code to accept.

DAO Property Objects vs. Microsoft Access Property Objects

You can't use an object variable in your code to refer to a Category property. The Category property is no longer supported for Form, Report, and Control objects.

The Parent Property

In Microsoft Access 2000, if you use the Parent property of a control in code or in an expression on a form or report, it typically returns the Form or Report object that contains the control. For example, if CategoryID is a text box on the Categories form, the code Forms!Categories!CategoryID.Parent returns a reference to the Categories form. There are two exceptions: for attached labels, the Parent property now returns the control the label is attached to; and for controls in an option group, it now returns the option group control.

Calling Code in Microsoft Access Wizards

If code in your version 1.x or 2.0 applications calls procedures in Microsoft Access wizards, after you convert your application, you must establish a reference from your application to the wizard database that contains the procedures that you call. For more information on establishing references, see Set References to Type Libraries.

In Microsoft Access version 2.0, there's no distinction between wizards and libraries, so their public code is always available to the current database. In Microsoft Access 2000, wizards and other add-ins are no longer treated as libraries. In addition, because wizards may change a great deal from one version of Microsoft Access to the next, you may need to rewrite some of your code to adapt to the changes after upgrading to a new version of Microsoft Access.

For code that's no longer provided in the Microsoft Access wizards, such as the AutoDialer, functionality has been added to Utility.mda, a special library database that's provided with Microsoft Access. A reference to this library is automatically added when you convert a database to Microsoft Access 2000.

Setting a Reference to a Microsoft Access Database

You cannot set a reference to a database created with a prior version of Microsoft Access from Microsoft Access 2000. You must convert the database to a Microsoft Access 2000 (version 9.0) database in order to set a reference to it.

Handling Automation Errors

In versions 1.x and 2.0 of Microsoft Access, COM components that support Automation (formerly called OLE Automation servers) return a single error. Visual Basic now enables a COM component to return error information specific to the error that has occurred. If your existing databases include code to handle a single Automation error, you may have to update that code to handle the more-specific errors that will now be returned.

Microsoft Access Errors and the Error Function

In Microsoft Access 2000, you use the properties of the Err object to obtain information about errors.

When a Microsoft Access error occurs, you can get the error number and the error description by using the Err object's Number and Description properties, as in the following example:

Debug.Print Err.Number, Err.Description

To return information about Microsoft Access, Visual Basic, or DAO errors, use the AccessError method. With the AccessError method, you can obtain error information regardless of whether the error has actually occurred.

Exclamation Point vs. Dot Operator When Referencing DAO Fields

If you used the . (dot) operator syntax when referring to a Field object of a Recordset object in applications created in versions 1.x or 2.0 of Microsoft Access, you must modify those references to use the ! (exclamation point) operator syntax. Or, if you want to continue using the . (dot) operator syntax, you must establish a reference to the Microsoft DAO 2.5/3.5 compatibility library in the References dialog box, available by clicking References on the Tools menu while in module Design view.

Converted ActiveX Controls

If your application contains ActiveX controls (formerly called OLE, or custom, controls) that were set up in version 2.0, you may need to insert the ByVal keyword in front of arguments that are passed to event procedures called from ActiveX control events, as in the following example:

Sub ChangeMonth_Click(ByVal intCurrentYear As Integer)

In order to determine whether an argument needs to be passed by value, click Compile All Modules on the Debug menu in module Design view. If you receive the following error message, you need to insert the ByVal keyword in front of the argument: "Event procedure declaration doesn't match description of event having the same name."

Because type checking of arguments is improved in Microsoft Access 2000, new event procedures created for ActiveX controls automatically have the ByVal keyword inserted when it's needed.

Calling Procedures in Form and Report Modules

In versions 1.x and 2.0 of Microsoft Access, you couldn't call a procedure defined in a form or report from anywhere but within that form or report module. In Microsoft Access 2000, you can call a public procedure in a form or report module from any procedure in the current database. You must qualify the procedure with the class name of the form or report module. For instance, to call a procedure named DisplayMessage that's defined in the module of the Orders form, you would use the following syntax:

Form_Orders.DisplayMessage

It's better to place procedures that you will call from outside a form or report in a standard module if possible, rather than in a form or report module.

Referring to Forms, Reports, and Controls in the Debug Window

When you're testing and debugging code, you must fully qualify all references to objects that you use in the Debug window, unless you've suspended execution in a form or report module. This means that in the Immediate pane of the Debug window, you must use the code Forms!Categories!CategoryID to refer to the CategoryID control on the Categories form in Form view, instead of just CategoryID, even when the Categories form is the current form.

Also, you can't use the Me keyword in the Debug window to refer to an object on a form or report when that form or report is in Design view unless you've suspended the execution of code in the form or report.

Converting Forms and Reports That Contain ActiveX Controls

When you convert a Microsoft Access 2.0 database for use in Microsoft Access 2000 (version 9.0), ActiveX controls on forms and reports may not be converted automatically. Microsoft Access 2.0 supports 16-bit OLE controls, while version 9.0 supports only 32-bit ActiveX controls.

If you're converting a database that contains a form or report that has a 16-bit version of an ActiveX control, and the 32-bit version doesn't yet exist on your system, Microsoft Access will generate an error message. You must obtain a 32-bit version of each ActiveX control that you wish to update and register it in the system registry. You should then save the form or report in the converted database and close and reopen the database.

Enabling a Database Created with a Previous Version of Microsoft Access

When you enable a large database created with version 1.x or 2.0 of Microsoft Access, but don't convert it to Microsoft Access 2000, you may need to increase the maximum buffer size beyond the default. To change this setting, open the system registry and navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.0\Engines\Jet 2.x subkey. Create a new subkey named ISAM, and within this subkey create a new DWORD value called MaxBufferSize. Set this value to 1024, decimal base. For more information about editing the registry, see your Microsoft Windows documentation.

Renaming a Database

When you rename a database, compiled code in the database will be decompiled. To recompile code and save all modules in a compiled state, open the database, open a module in Design view, and click Compile And Save All Modules on the Debug menu.

Time Values in Query Criteria

When you convert a version 1.x or 2.0 database to Microsoft Access 2000, queries that contain criteria based on specific time values in Date/Time fields may return different results than they do in earlier versions. This behavior may also occur if you link tables from a version 1.x or 2.0 database to a Microsoft Access 2000 database. Only the time portion of Date/Time fields is affected.

Visual Basic Functions That Are Not Supported in Expressions

The following six Visual Basic functions can't be used in expressions outside a user-defined Sub or Function procedure:

EOF | Loc
FileAttr | LOF
FreeFile | Seek

If you need to use one of these functions in an expression outside a procedure, you can call the function from within a user-defined function that you call from the expression.

Line Numbers in Visual Basic Procedures

You can't assign line numbers greater than 65,529 to statements in your Visual Basic procedures. If your converted version 1.x or 2.0 Microsoft Access application contains line numbers greater than 65,529, you must modify them to fall within the acceptable range.

The Next Procedure and Previous Procedure Buttons

The Next Procedure and Previous Procedure buttons that are on the Module toolbar in versions 1.x and 2.0 aren't available in Microsoft Access 2000. If you convert a version 1.x or 2.0 database with a custom toolbar that contains one of these buttons, you won't receive an error, but the buttons will have no effect when clicked.

"Out of Memory" Error When Converting Large Databases

Visual Basic for Applications has a limit of 1,082 modules per database, and forms and reports each contain one module. To resolve this problem, reduce the number of objects in your database or consider dividing your application into multiple databases. If you have modules with a large amount of code, consider using library databases to store the code.

Formatting Null Values and Zero-Length Strings

In version 2.0 of Microsoft Access, you can use the Format function to return one value for a zero-length string and another for a Null value, and you can similarly use the Format property to automatically format fields in table Datasheet view or controls on a form or report. For example, you can use a format expression such as the following with the Format function to return the appropriate string value from code:

Dim var As Variant, strX As String
' Assign some value to strX and pass to Format function.
var = Format(strX, "@;ZLS;Null")

In Microsoft Access 2000, you must test separately for the Null value case and then return the appropriate value based on the result. For example, you could use the IIf function in an expression with the Format function, such as the following:

var = IIf(IsNull(strX),"Null", Format(strX, "@;ZLS"))

This change applies only when you use the Format function to format a value depending on whether it's a zero-length string or a Null value. Other format expressions used with the Format function continue to work as they do in previous versions.

If you convert a database from version 2.0 of Microsoft Access to Microsoft Access 2000, you'll need to change any code or property settings to use these methods. You can't use the Format property in table Datasheet view to distinguish between Null values and zero-length strings.


 Convert Library Databases and Add-Ins

Convert Library Databases and Add-Ins

If you use add-ins or library databases created in previous versions of Microsoft Access, you must convert them to Microsoft Access 2000 (version 9.0) format before you can use them with applications created in Access 2000.

You may also need to make some changes to the objects, macros, and procedures in your library databases and add-ins in order to make sure that they function properly.

For more information about library databases, see Chapter 10, "The Windows API and Other Dynamic-Link Libraries," in the Microsoft Office 2000/Visual Basic Programmer's Guide or see Set References to Type Libraries. For information about how to obtain the Microsoft Office 2000/Visual Basic Programmer's Guide, click [image] .

Referencing and Loading Library Databases

Before using a library in Microsoft Access 2000, you must establish a reference to the library database from each of your applications that uses it. You establish such a reference by clicking References on the Tools menu while in module Design view. A referenced database must be in Microsoft Access 2000 format.

A library database should contain only Visual Basic code, which you can call from any application that maintains a reference to that library. In versions 1.x and 2.0 of Microsoft Access, you load a library database at startup by creating an entry in the Libraries section of your .ini file. Most of the information that's stored in an .ini file in versions 1.x and 2.0 is stored in the Windows registry in later versions. However, there's no need to create a Windows registry key in order to use a library database.

Circular References Between Libraries

In versions 1.x and 2.0 of Microsoft Access, you can make circular library references. However, these aren't allowed in later versions of Microsoft Access. In other words, once you've created a reference from Library A to Library B, you cannot create a reference from Library B to Library A.

Custom Add-ins Menu Behavior

In versions 1.x and 2.0 of Microsoft Access, add-ins automatically appear on the Add-ins submenu of the File menu. In later versions of Microsoft Access, the Add-ins submenu is on the Tools menu. In Microsoft Access 2000 you can also reference add-ins from any toolbar or menu.


 Convert SendKeys Key Combinations

Convert SendKeys Key Combinations

If you're converting a version 1.x or 2.0 database to Microsoft Access 2000, changes in some dialog boxes and menus may require you to recode the SendKeys statement or SendKeys action. For example, the Add-ins submenu has been moved from the File menu to the Tools menu, and the previous Import, Export, and Attach submenus on the File menu have changed to the Get External Data and Save As/Export submenus. Because changes like this are likely to occur for each new version of Microsoft Access, it's a good idea to avoid using the SendKeys statement or action to carry out commands or fill in dialog boxes whenever possible.

Here are some tips you can use to avoid using the SendKeys statement or action:

  • Before you use the SendKeys statement or action to carry out a menu command, check for an equivalent macro action or Visual Basic method. Most commands that are commonly carried out by a menu command or option have an equivalent action or method. For example, you can now use the Dropdown method of a combo box rather than the code SendKeys "{F4}".

  • If a menu command doesn't have an equivalent action or method, use the RunCommand action rather than the SendKeys statement or action to carry it out.

  • Avoid using the SendKeys statement or action to set options in the Options dialog box. New versions of Microsoft Access have new and changed options, so the code in your SendKeys statement or action could easily break. Instead, use the GetOption and SetOption methods.

  • When you use the SendKeys statement to carry out an action, consider referencing the built in key-code constants or declaring constants for the values in your SendKeys statement. Defining your keystrokes as constants makes updating your code easier in the future.

  • In Microsoft Access version 2.0, you can enclose the Keystrokes argument of the SendKeys action in quotation marks, but it isn't required. If you enclose this argument in quotation marks in subsequent versions of Microsoft Access, an error occurs. To use quotation marks in the Keystrokes argument, you must use two sets of quotation marks, as in Michael ""Mick"" Suyama. An error can also 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.


 Create a bound HTML control on a data access page

Create a bound HTML control on a data access page

Note You can use a bound HTML control to display data from a field in the database or to display the result of an expression.

  1. Open the data access page in Design view.

  2. Click the Bound HTML tool Bound HTML control in the toolbox.

  3. To bind the control to a field, in the field list, click the field that contains the HTML code, and then drag it to the data access page.

  4. In the data access page, release the field where you want the upper-left corner of the bound HTML control to be.


 Creating Object Variables

Creating Object Variables

In Microsoft Access, you can declare an object variable as a specific object type, as an Object, or as a Variant. Specific object types include Microsoft Access objects, Data Access Objects (DAO), Visual Basic Collection objects, instances of class modules, or Automation (formerly called OLE Automation) objects. The following examples show different specific object types you might use.

Dim frmOrderForm As Form                  ' Declares as Form object.
    Dim tdfOrders As TableDef              ' Declares as TableDef object.
      Dim colThings As New Collection      ' New Collection object.
        Dim obj As New Class1                    ' New instance of a class module.
          Dim appXL As Excel.Application      ' Automation object.

            Note If you use the New keyword in an object variable declaration, a new object is created and the variable is automatically pointed to it, so you don't need to use the Set statement.

              You can use the Me keyword in a form module or report module to refer to the form or report that is associated with that module. The Me keyword allows you to refer to the current form without giving its full reference.

              For example, you might create the following procedure in a standard module to change the color of the Detail section of a form.

              Sub ChangeFormColor(frmCurrent As Form)
    frmCurrent.Section(acDetail).BackColor = RGB(Rnd * 256, _
        Rnd * 256, Rnd * 256)
End Sub

              You can call this procedure from a form module and pass the Me keyword as an argument to the procedure. The Me keyword represents the form from which the procedure is called and on which the procedure is run.

              For example, you might call this procedure from the Click event of a form section. Set the Detail section's OnClick property to [Event Procedure], and create the following Sub procedure in the form's module.

              Private Sub Detail_Click()
    ChangeFormColor Me
End Sub

              If the name of the form were Orders, then you could also call this procedure with the following statement.

              ChangeFormColor Forms!Orders

              One advantage to using the Me keyword is that you don't need to know the name of the form to refer to it.


Examples of expressions that use text values as criteria

Field | Expression | Description
ShipCity | "London" | Displays orders shipped to London.
ShipCity | "London" Or "Hedge End" | Uses the Or operator to display orders shipped to London or Hedge End.
ShippedDate | Between #1/5/95# And #1/10/95# | Uses the Between...And operator to display orders shipped no earlier than 5-Jan-95 and no later than 10-Jan-95.
ShippedDate | #2/2/95# | Displays orders shipped on 2-Feb-95.
ShipCountry | In("Canada", "UK") | Uses the In operator to display orders shipped to Canada or the UK.
ShipCountry | Not "USA" | Uses the Not operator to display orders shipped to countries other than the USA.
ShipName | Like "S*" | Orders shipped to customers whose name starts with the letter S.
CompanyName | >="N" | Displays orders shipped to companies whose name starts with the letters N through Z.
OrderID | Right([OrderID], 2)="99" | Uses the Right function to display orders with OrderID values ending in 99.
CompanyName | Len([CompanyName]) >Val(30) | Uses the Len and Val functions to display orders for companies whose name is more than 30 characters long.


Examples of expressions that use the result of a domain aggregate function as criteria

Field | Expression | Description
Freight | >(DStDev("[Freight]", "Orders") + DAvg("[Freight]", "Orders")) | Uses the DAvg and DStDev functions to display all orders for which the freight cost rose above the mean plus the standard deviation for freight cost.
Quantity | >DAvg("[Quantity]", "Order Details") | Uses the DAvg function to display products ordered in quantities above the average order quantity.

For more information on using domain aggregate functions, click [image] .


Examples of expressions that use the result of subqueries as criteria

Field | Expression | Displays
UnitPrice | (SELECT [UnitPrice] FROM [Products] WHERE [ProductName] = "Aniseed Syrup") | Products whose price is the same as the price of Aniseed Syrup.
UnitPrice | >(SELECT AVG([UnitPrice]) FROM [Products]) | Products that have a unit price above the average.
Salary | > ALL (SELECT [Salary] FROM [Employees] WHERE ([Title] LIKE "*Manager*") OR ([Title] LIKE "*Vice President*")) | Salary of every sales representative whose salary is higher than that of all employees with "Manager" or "Vice President" in their titles.
OrderTotal: [Unit Price]* [Quantity] | > ALL (SELECT AVG([UnitPrice] * [Quantity]) FROM [Order Details]) | Orders with totals that are higher than the average order value.


Examples of expressions that calculate or manipulate dates, and then use the result as criteria

Field | Expression | Description
RequiredDate | Between Date( ) And DateAdd("m", 3, Date( )) | Uses the Between...And operator and the DateAdd and Date functions to display orders required between today's date and three months from today's date.
OrderDate | < Date( )- 30 | Uses the Date function to display orders more than 30 days old.
OrderDate | Year([OrderDate])=1996 | Uses the Year function to display orders with order dates in 1996.
OrderDate | DatePart("q", [OrderDate])=4 | Uses the DatePart function to display orders for the fourth calendar quarter.
OrderDate DateSerial(Year
([OrderDate]),
Month([OrderDate])+1, 1)-1 		Uses the DateSerial, Year, and Month functions to display orders for the last day of each month.
OrderDate Year([OrderDate])=
Year(Now()) And Month([OrderDate])=
Month(Now()) 		Uses the Year and Month functions and the And operator to display orders for the current year and month.


Examples of expressions that use part of a field's value as criteria

Field | Expression | Displays
ShipName | Like "S*" | Orders shipped to customers whose names start with the letter S.
ShipName | Like "*Imports" | Orders shipped to customers whose names end with the word "Imports".
ShipName | Like "[A-D]*" | Orders shipped to customers whose names start with A through D.
ShipName | Like "*ar*" | Orders shipped to customers whose names include the letter sequence "ar".
ShipName | Like "Maison Dewe?" | Orders shipped to the customer with "Maison" as the first part of its name and a 5-letter second name in which the first 4 letters are "Dewe" and the last letter is unknown.


 Examples of expressions that use a blank field's value (Null or zero-length string) as criteria

Examples of expressions that use a blank field's value (Null or zero-length string) as criteria

To learn more about how to use Null values and zero-length strings, click [image] .

Field | Expression | Description
ShipRegion | Is Null | Displays orders for customers whose ShipRegion field is Null (blank).
ShipRegion | Is Not Null | Displays orders for customers whose ShipRegion field contains a value.
Fax | " " | Displays orders for customers who don't have a fax machine, indicated by a zero-length string value in the Fax field instead of a Null (blank) value.


Differences between using multiple pages and tabs on a form

There are two ways to create a form with more than one page. You can use a tab control or a page break control.

A tab control is the easiest and most effective way to create a multiple-page form. With a tab control, the separate pages are all built into one control. To switch pages, you click one of the tabs.

Tab control with two tabs

You use a page break control to mark a horizontal break between controls on a form. When you press the PAGE UP or PAGE DOWN keys, Microsoft Access scrolls to the page before or after the page break control.

Return to Create a form with multiple pages or tabs


 Example of validating data by using a macro

Example of validating data by using a macro

In some circumstances, you might want to use validation rules that depend on complex conditions, and then take different actions depending on those conditions. For example, because different countries have different rules for their postal codes, a database that stores postal codes for many countries can't rely on a simple validation rule to ensure that a postal code is entered correctly.

You can, however, create a macro that checks which country is entered in the Country control and then checks that the value entered in the PostalCode control has the right characteristics for that country.

First, create a macro that displays different messages depending on the value of the Country control and the length of the entry in the PostalCode control.

Validate data by using a macro

Then, open the form that contains the controls in Design view, and set the BeforeUpdate event property of the form to the name of the macro. You use the form property rather than the control property because the validation involves two different controls on the form.

Now when you use the form to add a new supplier, Microsoft Access runs the validation macro after you finish entering the new record, but before it saves the record in the Suppliers table. If either condition in the macro is met, Access displays the appropriate message and doesn't save the record in the Suppliers table.


 Examples of data-definition queries

Examples of data-definition queries

Creating a table

This data-definition query uses the CREATE TABLE statement to create a table named Friends. The statement includes the name and data type for each field in the table and assigns the FriendID field an index that marks it as the primary key.

CREATE TABLE Friends
([FriendID] integer,
[LastName] text,
[FirstName] text,
[Birthdate] date,
[Phone] text,
[Notes] memo,
CONSTRAINT [Index1] PRIMARY KEY ([FriendID]));

Creating an index

This data-definition query uses the CREATE INDEX statement to create a multiple-field index on the LastName and FirstName fields.

CREATE INDEX NewIndex
ON Friends ([LastName], [FirstName]);


 Examples of criteria expressions for queries or advanced filters

Examples of criteria expressions for queries or advanced filters

You can use a criteria expression in the Criteria cell, either in the Advanced Filter/Sort window or in query Design view.

Note You can also use custom criteria expressions in a field in the Filter By Form window, or use the expressions from the list in the fields.

What do you want to do?

See examples of expressions that use text values as criteria

See examples of expressions that calculate or manipulate dates, and then use the result as criteria

See examples of expressions that use a blank field's value (Null or zero-length string) as criteria

See examples of expressions that use part of a field's value as criteria

See examples of expressions that use the result of a domain aggregate function as criteria

See examples of expressions that use the result of subqueries as criteria

See examples of using multiple criteria in one or more fields in a query


 Examples of expressions that calculate on or manipulate values by using a calculated field in a query

Examples of expressions that calculate on or manipulate values by using a calculated field in a query

Enter the expression for the calculated field in the Field cell in the query design grid.

Expression for a calculated field

What do you want to do?

Learn how to create an expression

Learn more about calculated fields

See examples of expressions that manipulate text

See examples of expressions that perform arithmetic operations

See examples of expressions that manipulate and calculate dates

See examples of expressions that count, sum, and average values using SQL aggregate or domain aggregate functions

See examples of expressions for working with blank fields (Null values)

See an example of an expression that uses a subquery


Examples of expressions in SQL statements

You can use an expression in many places in an SQL statement, as the following examples show. Expressions are shown in red.

Expression | Result
SELECT [FirstName],[LastName] FROM [Employees] WHERE [LastName]="Davolio"; | Displays the values in the FirstName and LastName fields for employees whose last name is Davolio.
SELECT [ProductID],[ProductName] FROM [Products] WHERE [CategoryID]=Forms![New Products]![CategoryID]; | Displays the values in the ProductID and ProductName fields in the Products table for records in which the CategoryID value matches the CategoryID value specified in an open New Products form.
SELECT Avg([ExtendedPrice]) AS [Average Extended Price] FROM [Order Details Extended] WHERE [ExtendedPrice]>1000; | Calculates the average extended price for orders for which the value in the ExtendedPrice field is more than 1000, and displays it in a field named Average Extended Price.
SELECT [CategoryID],Count([ProductID]) AS [CountOfProductID] FROM [Products] GROUP BY [CategoryID] HAVING Count([ProductID])>10; | In a field named CountOfProductID, displays the total number of products for categories with more than 10 products.


Examples of reports that start each group in a new row or column

In multiple-column reports, you can emphasize group headings by placing them either down the left side of the page or across the top of the page. The following example reports use CategoryID as the group header and ProductName as the detail record.

Report where each group header prints in a new row

To create the preceding report, place the text box for CategoryID in the group header and the text box for ProductName in the detail section. Then set the NewRowOrCol property of the CategoryID header to Before & After, and set the following properties on the Columns tab in the Page Setup dialog box (Page Setup command on the File menu):

Group | Property | Setting
Grid Settings | Number Of Columns | 3
Column Size | Width | The width of one column in the detail section; for example, 2"
 | Height | The height of one row; for example, 0.25"
Column Layout | Across, Then Down | Selected

To create the report in the following example, you use the same report design as the one in the previous example, but set the NewRowOrCol property of the CategoryID header to Before Section, and set Column Layout to Down, Then Across in the Page Setup dialog box.

Report where each group header prints in a new column


Examples of simple optimizable expressions

If you have created indexes for the LastName, Age, and HireDate fields in the Employees table, the following are simple optimizable expressions:

  • [LastName]="Smith"

  • [Age]>=21

  • #12/30/90#<[HireDate]

  • Employees.[LastName]=Customers.[LastName]

  • [LastName] In ("Smith", "Johnson", "Jones")

  • [Age] Between 18 And 65


 Examples of union queries

Examples of union queries

Union queries combine fields from two or more tables or queries into one field. Following are examples of a basic union query, and of sorting records, renaming fields, and returning duplicate records in union queries.

This topic provides information about:

Basic union query

Sorting in a union query

Renaming fields in a union query

Returning duplicate records in a union query

Basic union query

The following union query consists of two SQL SELECT statements that return the company names and cities that are in Brazil, from both the Suppliers and Customers tables.

Combine data from two or more tables with a union query

Return to top

Sorting in a union query

The following union query selects all company names and cities from both the Suppliers and Customers tables, and sorts the data alphabetically by city:

SELECT [CompanyName], [City]
FROM [Suppliers]

UNION SELECT [CompanyName], [City]
FROM [Customers]
ORDER BY [City];

Return to top

Renaming fields in a union query

The following union query renames the Company Name field to "Supplier/Customer Name" in the query output:

SELECT [CompanyName] AS [Supplier/Customer Name], [City]
FROM [Suppliers]

UNION SELECT [CompanyName] AS [Supplier/Customer Name], [City]
FROM [Customers];

Return to top

Returning duplicate records in a union query

The following union query uses the UNION ALL statement to retrieve all records, including duplicates:

SELECT [CompanyName], [City]
FROM [Suppliers]

UNION ALL SELECT [CompanyName], [City]
FROM [Customers];

Return to top

More information

Work with SQL in queries, forms, reports, macros, and modules

Ways to bring together data from multiple tables or queries in a query


 Examples of text boxes that grow or shrink when printing forms and reports

Examples of text boxes that grow or shrink when printing forms and reports

You can make a text box adjust vertically to the size of the data in the field for each record by setting the CanGrow and CanShrink properties to Yes. For example, a Memo field can contain values that are very long. You can make the text box large enough to accommodate most of the entries and set CanGrow to Yes, so that when the form or report is printed, the text box grows to fit longer entries. If a field has no values in some records, you can set CanShrink to Yes to avoid blank lines.

When a text box grows or shrinks, the entire section grows or shrinks vertically across its entire width. For that reason, the placement and height of the text box in relation to the controls beside it are important.

Text box that grows is the same height as the tallest control in the same row

A text box can't shrink to a height that's less than the other controls on the same line. For example, if you have a label beside a text box, the label will always have a value (its caption) even when the text box doesn't have a value. The text box will shrink only to the same height as the label.

Comparison of text boxes in Design view and on a printed report


 Form

Form

A form is a Microsoft Access database object on which you place controls for taking actions or for entering, displaying, and editing data in fields.


 Form Section

Form Section

A form section is part of a form such as a header, footer, or detail section.

You can set section properties which are attributes of a form that affect the appearance or behavior of that section. For example, you can set the CanGrow property to specify whether the section will increase vertically to print all the data the section contains. Section properties are set in form Design view.


 Ways to optimize query performance

Ways to optimize query performance

There are many things you can do to make your query run faster. In addition to the following tips, you can use the Performance Analyzer to analyze specific queries in your database. For information on using the Performance Analyzer, click [image] .

  • Compact your database. Compacting can speed up queries because it reorganizes a table's records so that they reside in adjacent database pages ordered by the table's primary key. This will improve the performance of sequential scans of a table's records because the minimum number of database pages will have to be read to retrieve all of the records. After compacting the database, run each query to compile it using the updated table statistics.

  • Index any field used to set criteria for the query and index fields on both sides of a join, or create a relationship between these fields. When you create relationships, the Microsoft Jet database engine creates an index on the foreign key if one does not already exist; otherwise, it uses the existing index.

    Note The Microsoft Jet database engine automatically optimizes a query that joins a Microsoft Access table on your hard drive and an ODBC server table if the Microsoft Access table is small and the joined fields are indexed. In this case, Microsoft Access improves performance by requesting only the necessary records from the server. Make sure tables you join from different sources are indexed on the join fields.

  • When defining a field in a table, choose the smallest data type appropriate for the data in the field. Also, give fields you'll use in joins the same or compatible data types, such as Autonumber and Number (if the FieldSize property is set to Long Integer).

  • When creating a query, add only the fields you need. In fields used to set criteria, clear the Show check box if you don't want to display those fields.

  • If the RecordSource property for a form or report is set to an SQL statement, save the SQL statement as a query, and then set the RecordSource property to the name of the query. For more information, click [image] .

  • Avoid calculated fields in subqueries. If you add a query containing a calculated field to another query, the expression in the calculated field may slow performance in the top-level query. In the example below, query Q1 is used as the input for query Q2:
    Q1: SELECT IIF([MyColumn]="Yes","Order Confirmed","Order Not Confirmed") AS X FROM MyTable;
Q2: SELECT * FROM Q1 WHERE X="Order Confirmed";

Because the IIf expression in Q1 cannot be optimized, Q2 also cannot be optimized. If an expression that can't be optimized is nested within a subquery, the entire query cannot be optimized.

An alternative way to construct the query is as follows:

Q1: SELECT * FROM MyTable WHERE MyColumn = "Yes";

If expressions are necessary in the output, try to place them in a control on a form or report. For example, you could change the previous query into a parameter query that prompts for the value of MyColumn, and then base a form or report on the query. On the form or report, you could then add a calculated control that displays "Hello" or "Goodbye" depending on the value in MyColumn.

Construct the query as follows:

PARAMETERS [To see confirmed orders, enter Yes. To see unconfirmed orders, enter No.] Text;
SELECT *
FROM MyTable
WHERE MyColumn = [To see confirmed orders, enter Yes. To see unconfirmed orders, enter No.];

In the calculated control on the form or report, enter:

=IIF([MyColumn]="Yes","Order Confirmed","Order Not Confirmed")

  • When grouping records by the values in a joined field, specify Group By for the field that's in the same table as the field you're totaling (calculating an aggregate on). For example, in the Northwind sample database, if you create a query that totals the Quantity field in the Order Details table and groups by OrderID, it's recommended that you specify Group By for the OrderID field in the Order Details table. If you specify Group By for the OrderID field in the Orders table, Microsoft Access must join all the records first and then perform the aggregate, instead of performing the aggregate and then joining only the necessary fields.

    For greater speed, use Group By on as few fields as possible. As an alternative, use the First function where appropriate. For more information on the First function, click [image] .

    If a totals query includes a join, consider grouping the records in one query and adding this query to a separate query that will perform the join. This improves performance in some queries.

  • Avoid restrictive query criteria on calculated and nonindexed fields whenever possible.

    Use criteria expressions that are optimizable. For information on optimizing criteria expressions using Rushmore technology, click [image] .

  • If you use criteria to restrict the values in a field used in a join between tables with a one-to-many relationship, test whether the query runs faster with the criteria placed on the "one" side or the "many" side of the join. In some queries, you get faster performance by adding the criteria to the field on the "one" side of the join instead of the "many" side.

  • Index the fields you use for sorting.

  • If your data doesn't change often, use make-table queries to create tables from your query results. Use the resulting tables rather than queries as the basis for your forms, reports, or other queries, and make sure you add indexes according to the guidelines recommended here.

  • Avoid using domain aggregate functions, such as the DLookup function to access data from a table that's not in the query. Domain aggregate functions are specific to Microsoft Access, which means that the Jet database engine can't optimize queries that use them. Instead, add to the query the table that the function was accessing, or create a subquery.

  • If you are creating a crosstab query, use fixed column headings whenever possible. For more information, click [image] .

  • Use the Between...And, the In, and the = operators on indexed fields.

  • For bulk update queries against ODBC data sources, optimize performance on the server by setting the FailOnError Property to Yes. For more information, click [image] .

Note For tips on optimizing external SQL database performance [image] .


Hidden Properties

Properties that have been hidden in the Microsoft Access 2000 Visual Basic object model because their functionality has been replaced by new language elements are listed in the following table. These properties are supported only for backward compatibility; for new code; you should use the replacement functionality provided in Microsoft Access 2000. To view hidden objects in the Object Browser, right-click in the Object Browser window and click Show Hidden Members on the shortcut menu.

Object | Hidden Property | Replacement
Form | AllowEditing, DefaultEditing | AllowAdditions, AllowDeletions, AllowEdits, DataEntry
Form | AllowUpdating | RecordsetType
BoundObjectFrame, CheckBox, ComboBox, Image, Label, Line, ListBox, ObjectFrame, OptionButton, OptionGroup, Rectangle, SubForm, TextBox | BorderLineStyle | BorderStyle
Form | Dynaset | RecordsetClone
Form, Report | MaxButton, MinButton | MinMaxButtons (Form only)
Form | ShowGrid | DatasheetGridlinesBehavior


 Important considerations when using a query that deletes records

Important considerations when using a query that deletes records

  • Once you delete records using a delete query, you can't undo the operation. Therefore, you should preview the data that the query selected for deletion before you run the query. You can do this by clicking View [image] on the toolbar, and viewing the query in Datasheet view.

  • You should maintain backup copies of your data at all times. If you delete the wrong records, you can retrieve them from your backup copies.

  • In some cases, running a delete query might delete records in related tables, even if they're not included in the query. This can happen when your query contains only the table that's on the "one" side of a one-to-many relationship, and you've enabled cascading deletes for that relationship. When you delete records from the "one" table, you'll also delete records from the "many" table. For more information on cascading deletes, click [image] .

  • When a delete query contains more than one table, such as a query that deletes duplicate records from one of the tables, the query’s UniqueRecords property must be set to Yes. For more information on setting the UniqueRecords property, click [image] .


 Index

Index

An index is a Microsoft Access feature that speeds up searching and sorting in a table. You can create an index for a field in the Indexes window of table Design view, or by setting the field's Indexed property to Yes.

Note The primary key of a table is automatically indexed, and fields for which the data type is Memo or OLE Object can't be indexed.


Language-Specific Properties and Methods

The Microsoft Access 2000 Visual Basic object model has new language-specific keywords for use with Asian and right-to-left languages. The availability of these language-specific keywords depends on the language support you have selected or installed. For more information about language-specific features, see Language-specific information.

Language-Specific Properties and Methods

Properties and methods that are available only in Asian or right-to-left languages are listed in the following table.

Property or Method | Object
FELineBreak | TextBox
FuriganaControl | TextBox
IMEHold/HoldKanjiConversionMode | ComboBox, ListBox, TextBox
IMEMode/KanjiConversionMode | ComboBox, Label, ListBox, TextBox
IMESentenceMode | ComboBox, Label, ListBox, TextBox
KeyboardLanguage | ComboBox, TextBox
NumeralShapes | ComboBox, Label, ListBox, TextBox
Orientation | Form
PostalAddress | TextBox
ReadingOrder | CheckBox, ComboBox, CommandButton, Label, ListBox, OptionButton, TextBox, ToggleButton
ScrollBarAlign | ComboBox, ListBox, TextBox


Methods with New Arguments

Existing methods for which arguments have been added for Microsoft Access 2000 are listed in the following table.

TransferText


 Avoiding Naming Conflicts

Avoiding Naming Conflicts

Below are some additional naming-conflict errors you may encounter in Microsoft Access.

Procedures and Variables in Standard Modules and Class Modules

In Microsoft Access, if both a standard module and a class module contain a public procedure with the same name, an unqualified reference to the procedure will always call the one residing in the standard module. To call a procedure in a class module, you must qualify it with the class name. The same holds true for variables with the same names defined in standard and class modules.

For example, if you have a function named CountOrders in the module of a form called Orders, you can call the function as follows.

Form_Orders.CountOrders

Differently Scoped Variables with the Same Name

If you declare a module-level variable that has the same name as a procedure-level variable in a procedure in that module, you must qualify the module-level variable with the name of that module. This applies to standard modules and class modules.

For example, you might declare a variable varScope at the module level and at the procedure level in a standard module called Important Functions. You can then refer to the module-level variable by qualifying it as [Important Functions].varScope.

It's best to avoid using variables with the same name within a single module.

Constant, Variable, and Procedure Names within Class Modules

You cannot give a constant, variable, or procedure in a form or report module the same name as a method or property of the form or report. For example, if you create a Sub procedure called Name, Microsoft Access will generate a compile-time error, because the form already has a Name property.


New Objects for Microsoft Access 97

Objects that were added to Visual Basic in Microsoft Access 97 are listed in the following table.

Objects | Description
Assistant | New Office Assistant functionality
Page, Pages | New Tab Control functionality


New Events for Microsoft Access 97

Events that were added to Visual Basic in Microsoft Access 97 are listed in the following table.


New Methods for Microsoft Access 97

Methods that were added to Microsoft Access 97 are listed in the following table.

Add (Pages collection)

AddFromFile (Module object)

AddFromFile (References collection)

AddFromGUID

AddFromString

AddToFavorites

CreateEventProc

DefaultControl

DeleteLines

InsertLines

 Find

Follow

FollowHyperlink

HyperlinkPart

RefreshDatabaseWindow

Remove(Pages collection)

Remove(References collection)

ReplaceLine

RunCommand


New Methods (by Object)

Methods that have been added to existing objects in Microsoft Access 2000 are listed in the following table (sorted by object name).

Objects | Methods
AccessObjectProperties | Add Remove
Application | CreateAccessProject CreateDataAccessPage GetHiddenAttribute NewAccessProject OpenAccessProject SetHiddenAttribute
Code Project, Current Project | CloseConnection OpenConnection
DataAccessPage | ApplyTheme
DoCmd | AddMenu OpenDataAccessPage OpenDiagram OpenStoredProcedure OpenView
FormatCondition | Delete Modify
FormatConditions | Add Delete
Hyperlink | CreateNewDocument
WebOptions | UseDefaultFolderSuffix


New Properties for Microsoft Access 97

Properties that were added to Microsoft Access 97 are listed in the following table.

A–G

CountOfDeclarationLines

CountOfLines

DatasheetBackColor

 DatasheetForeColor

FailOnError

H–P

HasModule

Hyperlink

HyperlinkAddress

HyperlinkSubAddress

IsVisible

Kind

Lines

Major

MDE

 Minor

MousePointer

MultiRow

PageIndex

ProcBodyLine

ProcCountLines

ProcOfLine

ProcStartLine

ProjectName

Q–Z

Style

TabFixedHeight

TabFixedWidth

 Toolbar

UseTransaction


 New Properties (By Object)

New Properties (By Object)

Properties that were added to existing objects in Microsoft Access 2000 are listed in the following table (sorted by object name).

Object | Property
AccessObject | FullName IsLoaded Properties Property (AccessObjectProperties Collection) Type (AccessObject Object)
Application | AnswerWizard CodeData CodeProject COMAddIns CurrentData CurrentProject DataAccessPages DefaultWebOptions FeatureInstall FileSearch LanguageSettings ProductCode Properties Property (Properties Collection) VBE
CodeData, CurrentData | AllDatabaseDiagrams AllQueries AllReports AllStoredProcedures AllTables AllViews
CodeProject, CurrentProject | AllDataAccessPages AllForms AllMacros AllModules AllReports BaseConnectionString Connection FullName IsConnected ProjectType Properties Property (AccessObjectProperties Collection)
DataAccessPage | ConnectionString Document WebOptions
DefaultWebOptions | AlwaysSaveInDefaultEncoding CheckIfOfficeHTMLEditor DownloadComponents Encoding FolderSuffix FollowedHyperlinkColor HyperlinkColor LocationOfComponents OrganizeInFolder UnderlineHyperlinks UseLongFileNames
Form | InputParameters MaxRecButton Recordset ResyncCommand ServerFilter ServerFilterByForm UniqueTable
FormatCondition | Enabled (FormatCondition Object) Expression1 Expression2 Operator (FormatCondition Object) Type (FormatCondition Object)
Hyperlink | Address EmailSubject ScreenTip SubAddress TextToDisplay
Screen | ActiveDataAccessPage
WebOptions | DownloadComponents Encoding FolderSuffix LocationOfComponents OrganizeInFolder UseLongFileNames

Microsoft Office properties

To see a list of the new properties available in the Microsoft Office 9.0 Object Library, open the Microsoft Office Visual Basic Reference in the Help contents.

To use the objects supplied by Microsoft Office, you must set a reference to the Microsoft Office 9.0 Object Library when the Visual Basic Editor is open by clicking References on the Tools Menu and selecting the check box next to this library.

Microsoft Visual Basic Editor properties

To see a list of the new properties available in the Microsoft Visual Basic for Applications Extensibility 5.3 Object Library, open the Microsoft Visual Basic Reference in the Help contents.

To use the objects supplied by the Microsoft Visual Basic Editor, you must set a reference to the Microsoft Visual Basic for Applications Extensibility 5.3 Object Library. To set this reference, open the Visual Basic Editor and click References on the Tools Menu and select the check box next to this library.


 Understanding Automation

Understanding Automation

In Microsoft Access, you can create an Automation (formerly called OLE Automation) object either by using the New keyword to declare an object variable, or by using the CreateObject or GetObject function.

Microsoft Access supports Automation in two different ways. Microsoft Access is an COM component, meaning that you can access objects exposed by other applications and manipulate them from Microsoft Access, or from another application that supports Automation (formerly called OLE Automation), you can manipulate Microsoft Access objects.

Note Before you can use Microsoft Access or another application as a component, you must set a reference to that application's object library. For more information on setting references, search online Help for "setting references."

For example, if you are using Microsoft Access as a component, you can use Microsoft Excel objects. You do this by creating a new Microsoft Excel object from Microsoft Access and pointing an object variable to it. You can then set its properties and call its methods as you would for any object. You can create a new instance of the Microsoft Excel Application class in either of the following ways.

Dim appXL As New Excel.Application
' Or
Dim appXL As Excel.Application
Set appXL = CreateObject("Excel.Application")

If Microsoft Excel is already running, you can use the GetObject function to point an object variable to the current instance of the Microsoft Excel Application class.

Dim appXL As Excel.Application
Set appXL = GetObject( , "Excel.Application")

For more information about the Application object, search the help index for "Application object".

If you are using Microsoft Access as a component, you can manipulate Microsoft Access objects from another application. For example, you can open a Microsoft Access form from Microsoft Excel and use it to view data in a Microsoft Excel workbook. The following example creates a new Microsoft Access object from Microsoft Excel.

Dim appAccess As New Access.Application

If Microsoft Access is already running, use the GetObject function to point an object variable to the current instance of the Microsoft Access Application class.


 About opening a previous-version Access database without converting it

About opening a previous-version Access database without converting it

This topic provides reference information about:

When to enable an Access database

Forward compatibility

Table structure

Toolbars and menu bars

Enabling a secured Access database

Size of an enabled Access database

Code compatibility

When to enable

You may want to enable a Microsoft Access database in a multiuser environment where all users can't upgrade to Microsoft Access 2000 at the same time. In this situation, a database must be used simultaneously with different versions of Microsoft Access, and users who have upgraded to Microsoft Access 2000 can enable a database in a previous-version format. When a Microsoft Access 2000 user enables the database, Microsoft Access maintains the original format so that users of previous versions of Microsoft Access can continue to use the database. For example, if a shared database is created in Microsoft Access version 2.0, it can be used with Microsoft Access version 2.0 and enabled in Microsoft Access 2000.

Return to top

Forward compatibility

You can enable a Microsoft Access version 2.0 database, an Access 95 database, or an Access 97 database so that you can use it in Microsoft Access 2000. . When you use Microsoft Access 2000 to enable a previous-version Access database, you can view database objects and add, delete, or modify records. However, you can't modify the design of objects. To modify the design of existing objects or to add new objects, you must open the database with the version of Microsoft Access used to create it. You can't open a Microsoft Access 2000 database with a previous version of Microsoft Access.

Instead of enabling, you can share front-end/back-end applications between Microsoft Access version 2.0, Access 95, Access 97, and Access 2000, provided that the back-end database is maintained in the oldest version of Microsoft Access that is being used. For more information on using a Microsoft Access database with several versions of Microsoft Access, click [image] .

Return to top

Table structure

In a previous-version Access database, you cannot link or import an Access 2000 table. However, you can export an Access 2000 table to a previous-version Access database. You can also cut, copy, and paste data from an Access 2000 table to a table in a previous version of Microsoft Access.

Return to top

New style of toolbars and menu bars

Microsoft Access 97 or later supports a new style of toolbars and menu bars. When you enable a Microsoft Access 95 database in Microsoft Access 2000, custom toolbars are converted to the new style but the conversion isn't saved. Custom menu bars are interpreted as the new style menu bar, but the menu bar macros are not converted and continue to be supported.

Return to top

Enabling a secured Access database

If your Access database is secure, you can make sure that it retains its security by recreating the workgroup information file in Access 2000. If you cannot recreate the workgroup information file, you can use the Workgroup Administrator to join the secure database's previous-version workgroup information file; however, it is recommended that you convert the workgroup information file to Access 2000 before you join it. As long as you use the database with its original workgroup information, it retains all its security except permissions for the modules. In Access 2000, you can protect Visual Basic for Applications (VBA) code with a password. Learn more about enabling a secured database.

Return to top

Size of an enabled Access database

Your Access database may increase in size when you enable it. If you have already enabled a database in a previous version of Microsoft Access, and if you enable it again in Access 2000, the size of the Visual Basic project will increase even more. In rare cases, you may have enabled a Microsoft Access version 2.0 database in Microsoft Access 95, enabled it again in Microsoft Access 97, and enabled it again in Microsoft Access 2000; in this case, the Visual Basic project must store information in the format of each version.

Return to top

Code compatibility

Microsoft Access 2000 does not support the DAO 2.5/3.x compatibility library. If you attempt to enable an Access database in which the code contains older versions of DAO objects, methods, and properties that depend on the DAO 2.5/3.x compatibility library, you receive a message that there were compilation errors during the enabling of the database. Before you enable the Access database, update the code so that it does not depend on the DAO 2.5/3.x compatibility library. For information on compatibility between Visual Basic in previous versions of Microsoft Access and Visual Basic in Microsoft Access 2000, click [image] .

Return to top

For information on how to enable a Access database, click [image] .


 Optimize form and subform performance

Optimize form and subform performance

There are several things you can do to make your forms run faster. If you’re using a Microsoft Access database, you can use the Performance Analyzer to analyze specific forms in your database in addition to the following tips. For information on using the Performance Analyzer, click [image] .

Performance Tips

  • Avoid overlapping controls.

  • Use bitmaps and other graphic objects sparingly.

  • Convert unbound object frames that display graphics to image controls.

  • Use black-and-white rather than color bitmaps.

  • Close forms that aren't being used.

  • If the underlying record source includes many records and you want to use the form primarily to enter new records, set the DataEntry property of the form to Yes so that the form opens to a blank record. If you open a form with all records showing, Microsoft Access has to read in each record before it can display the blank record at the end of the recordset.

  • Don't sort records in an underlying query unless record order is important, especially with multiple-table queries.

  • Base subforms on queries rather than on tables, and include only fields from the record source that are absolutely necessary. Extra fields can decrease subform performance.

  • Index all the fields in the subform that are linked to the main form.

  • Index any subform fields that are used for criteria.

  • Set the subform's AllowEdits, AllowAdditions, and AllowDeletions properties to No if the records in the subform aren't going to be edited. Or set the RecordsetType property to Snapshot.

  • Eliminate code from forms that don't need it by setting the HasModule form property to No. The HasModule property specifies whether the form has a form module. A form without a form module loads more quickly and occupies less disk space. If a form or controls on the form don't use event procedures, the form doesn't require a form module. For example, if your application uses a switchboard form exclusively to navigate to other forms, instead of using command buttons with event procedures, you can use command buttons with macros, or hyperlinks. You can still use code with a form that has no form module by calling Function procedures from a standard module using an expression. (You can't use Sub procedures, because they can't be called using an expression.) To do this, define a Function procedure in a standard module and then call that function from an event property of the form or a control. For example, to use a command button to call a function to open a form, add an expression to the OnClick property of the command button like this: =OpenDataEntry().

    Note If a form currently contains event procedures, and you decide to eliminate all event procedure code from that form, you must set the HasModule property to No to completely remove the form module.


 Simple and complex optimizable expressions and Rushmore optimization

Simple and complex optimizable expressions and Rushmore optimization

Microsoft Access can optimize simple expressions or complex expressions in the Criteria row of the query design grid, or in a WHERE clause in an SQL SELECT statement. For certain types of complex expressions, Microsoft Access can use Rushmore, a data access technology used by the Microsoft Jet database engine, to achieve a greater level of optimization.

Simple optimizable expressions

A simple optimizable expression can form an entire expression or can appear as part of an expression. A simple optimizable expression takes one of the following forms:

Indexed field Comparison operator Expression

[Order Date]=#09/15/96#

or

Expression Comparison operator Indexed field

#11/1/96#<[HireDate]

In a simple optimizable expression:

  • Indexed field can either be a field that has its own index or a field that's the first field in a multiple-field index.

  • Comparison operator must be one of the following: <, >, =, <=, >=, <>, Between…And, Like, In.

  • Expression can be any valid expression, including constants, functions, and fields from other tables.

For examples of simple optimizable expressions, click [image] .

Complex expressions

A complex expression is created by combining two simple expressions with the And or Or operator. A complex expression takes one of the following forms:

Simple Expression And Simple Expression

or

Simple Expression Or Simple Expression

A complex expression is fully or partially optimizable depending on whether one or both simple expressions are optimizable, and which operator you used to combine them. A complex expression is Rushmore-optimizable if all three of these are true:

  • The expression uses And or Or to join two criteria.

  • Both criteria are made up of simple optimizable expressions.

  • Both expressions contain indexed fields. The fields can be indexed individually or they can be part of a multiple-field index.

Note You can optimize multiple-field indexes if you query the indexed fields in the order they appear in the Indexes window, beginning with the first indexed field and continuing with adjacent fields (up to and including 10 fields). For example, if you have a multiple-field index that includes the LastName and FirstName fields, you can optimize a query on LastName or on LastName and FirstName, but you can't optimize a query on FirstName.

The following table indicates the level of query optimization for different combinations of simple expressions in query criteria.

Expression | Operator | Expression | Query result
Optimizable | And | Optimizable | Fully optimizable (using Rushmore)
Optimizable | Or | Optimizable | Fully optimizable (using Rushmore)
Optimizable | And | Not optimizable | Partially optimizable (doesn't use Rushmore)
Optimizable | Or | Not optimizable | Not optimizable
Not optimizable | And | Not optimizable | Not optimizable
Not optimizable | Or | Not optimizable | Not optimizable
-- | Not | Optimizable | Not optimizable
-- | Not | Not optimizable | Not optimizable

You can also use parentheses to group combinations of simple expressions. The preceding rules also apply to combinations of expressions grouped with parentheses.

Once you've combined simple optimizable expressions into complex expressions, these complex expressions can, in turn, be combined to form even more complex expressions that might be optimizable according to the preceding rules.

For examples of complex optimizable expressions, click [image] .

Notes

  • The Count function is highly optimized for queries using Rushmore. For more information about the Count function, click [image] .

  • Rushmore queries will work with Microsoft Access tables, as well as with Microsoft FoxPro and dBASE tables (.dbf files). You can't use Rushmore with ODBC data sources, since Microsoft Access sends these queries to the ODBC data source instead of processing them locally.


 Order of events for controls on forms

Order of events for controls on forms

Events occur for controls on forms when you move the focus to a control, and when you change and update data in a control.

Moving the focus to a control

When you move the focus to a control on a form — for example, by opening a form that has one or more active controls or by moving to another control on the same form — the Enter and GotFocus events occur in this order:

Enter Þ GotFocus

If you are opening a form, these events occur after the events associated with opening the form (such as Open, Activate, and Current), as follows:

Open (form) Þ Activate (form) Þ Current (form) Þ Enter (control) Þ GotFocus (control)

When the focus leaves a control on a form — for example, when you close a form that has one or more active controls or move to another control on the same form — the Exit and LostFocus events occur in this order:

Exit Þ LostFocus

If you are closing a form, the Exit and LostFocus events occur before the events associated with closing the form (such as Unload, Deactivate, and Close), as follows:

Exit (control) Þ LostFocus (control) Þ Unload (form) Þ Deactivate (form) Þ Close (form)

Changing and updating data in a control

When you enter or change data in a control on a form and then move the focus to another control, the BeforeUpdate and AfterUpdate events occur:

BeforeUpdate Þ AfterUpdate

The Exit and LostFocus events for the changed control occur after the BeforeUpdate and AfterUpdate events:

BeforeUpdate Þ AfterUpdate Þ Exit Þ LostFocus

When you change the text in a text box or in the text box portion of a combo box, the Change event occurs. This event occurs whenever the contents of the control change, but before you move to a different control or record (and thus, before the BeforeUpdate and AfterUpdate events occur). The following sequence of events occurs for each key you press in a text box or in the text box portion of a combo box:

KeyDown Þ KeyPress Þ Change Þ KeyUp

The NotInList event occurs after you enter a value in a combo box that isn't in the combo box list and then attempt to move to another control or record. It occurs after the keyboard events and the Change events for the combo box, but before any other control or form events. If the LimitToList property of the combo box is set to Yes, the Error event for the form occurs immediately after the NotInList event:

KeyDown Þ KeyPress Þ Change Þ KeyUp Þ NotInList Þ Error

For more information on events, click [image] .


 Order of events for forms and subforms

Order of events for forms and subforms

Events occur for forms when you open or close a form, move between forms, or work with data on a form.

Opening and closing a form

When you open a form, the following sequence of events occurs for the form:

Open Þ Load Þ Resize Þ Activate Þ Current

If there are no active controls on the form, the GotFocus event also occurs for the form after the Activate event but before the Current event.

When you close a form, the following sequence of events occurs for the form:

Unload Þ Deactivate Þ Close

If there are no active controls on the form, the LostFocus event also occurs for the form after the Unload event but before the Deactivate event.

Moving between forms

When you switch between two open forms, the Deactivate event occurs for the first form, and the Activate event occurs for the second form:

Deactivate (form1) Þ Activate (form2)

The Deactivate event for a form also occurs when you switch from the form to another window in Microsoft Access. However, the Deactivate event doesn't occur when you switch to a dialog box, to a form whose PopUp property is set to Yes, or to a window in another application.

Note An Open event doesn't occur if you move to a form that is already open, even if you've moved to the form by carrying out an OpenForm action.

Working with data on a form

Form and control events occur as you move between records in the form and change data. For example, when you first open a form, the following sequence of events occurs:

Open (form) Þ Load (form) Þ Resize (form) Þ Activate (form) Þ Current (form) Þ Enter (control) Þ GotFocus (control)

Similarly, when you close a form, the following sequence of events occurs:

Exit (control) Þ LostFocus (control) Þ Unload (form) Þ Deactivate (form) Þ Close (form)

If you've changed data in a control, the BeforeUpdate and AfterUpdate events for both the control and the form occur before the Exit event for the control. For more information on the order of events for controls on forms, click [image] .

Working with subforms

When you open a form containing a subform, the subform and its records are loaded before the main form. Thus, the events for the subform and its controls (such as Open, Current, Enter, and GotFocus) occur before the events for the form. The Activate event doesn't occur for subforms, however, so opening a main form triggers an Activate event only for the main form.

Similarly, when you close a form containing a subform, the subform and its records are unloaded after the form. The Deactivate event doesn't occur for subforms, so closing a main form triggers a Deactivate event only for the main form. The events for the controls, form, and subform occur in the following order:

  1. Events for the subform's controls (such as Exit and LostFocus)

  2. Events for the form's controls (including the subform control)

  3. Events for the form (such as Deactivate and Close)

  4. Events for the subform

For more information on events, click [image] .


 Order of events for keystrokes and mouse clicks

Order of events for keystrokes and mouse clicks

Keyboard events occur for forms and controls when you press keys or send keystrokes while the form or control has the focus. Mouse events occur for forms, form sections, and controls on forms when you press the mouse buttons while the mouse pointer is on a form, section, or control, or when you move the mouse pointer over a form, section, or control.

Keyboard events

When you press and release a key while a control on a form has the focus (or use the SendKeys action or statement to send a keystroke), the following sequence of events occurs:

KeyDown Þ KeyPress Þ KeyUp

When you press and release a key or send a keystroke in the ANSI character set key, the KeyDown, KeyPress, and KeyUp events all occur. 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. For lists of characters in the ANSI character set, click [image] and [image] .

If you press and release a non-ANSI key, the KeyDown and KeyUp events occur. If you press and hold down a non-ANSI key, the KeyDown event occurs repeatedly until you release the key; and then the KeyUp event occurs.

If pressing a key triggers another event for a control, the other event occurs after the KeyPress event but before the KeyUp event. For example, if a keystroke changes text in a text box, triggering a Change event, the following sequence of events occurs:

KeyDown Þ KeyPress Þ Change Þ KeyUp

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 change data in a control and then press the TAB key to move to the next control, the following sequences of events occur:

  • First control:

    KeyDown Þ BeforeUpdate Þ AfterUpdate Þ Exit Þ LostFocus

  • Second control:

    Enter Þ GotFocus Þ KeyPress Þ KeyUp

Mouse events

When you press and release a mouse button while the mouse pointer is on a control on a form, the following sequence of events occurs for the control:

MouseDown Þ MouseUp Þ Click

If a control has the focus and you click another control to move the focus to this second control, the following sequences of events occur:

  • First control:

    Exit Þ LostFocus

  • Second control:

    Enter Þ GotFocus Þ MouseDown Þ MouseUp Þ Click

If you move to another record and then click a control, the Current event for the form also occurs before the Enter event for the control.

Double-clicking a control causes both DblClick and Click events to occur. For example, when you double-click a control other than a command button, the following sequence of events occurs for the control:

MouseDown Þ MouseUp Þ Click Þ DblClick Þ MouseUp

When you double-click a command button, these events occur, followed by a second Click event.

The MouseMove event for a form, section, or control occurs when you move the mouse pointer over the form, section, or control. This event is independent of the other mouse events.

For more information on keyboard events, click [image] .

For more information on mouse events, click [image] .


 Order of events for records on forms

Order of events for records on forms

Events occur for records on forms when you move the focus to a record, update data in a record, delete an existing record or records, or create a new record.

Moving the focus to records and updating data in records

When you move the focus to an existing record on a form, enter or change data in the record, and then move the focus to another record, the following sequence of events occurs for the form:

Current (form) Þ BeforeUpdate (form) Þ AfterUpdate (form) Þ Current (form)

When you leave the record whose data has changed, but before you enter the next record, the Exit and LostFocus events occur for the control with the focus. These events occur after the BeforeUpdate and AfterUpdate events for the form, as follows:

BeforeUpdate (form) Þ AfterUpdate (form) Þ Exit (control) Þ LostFocus (control) Þ Current (form)

As you move the focus among the controls on a form, events occur for each control. For example, the following sequences of events occur when you:

  • Open a form and change data in a control:

    Current (form) Þ Enter (control) Þ GotFocus (control) Þ BeforeUpdate (control) Þ AfterUpdate (control)

  • Move the focus to another control:

    Exit (control1) Þ LostFocus (control1) Þ Enter (control2) Þ GotFocus (control2)

  • Move the focus to another record:

    BeforeUpdate (form) Þ AfterUpdate (form) Þ Exit (control2) Þ LostFocus (control2) Þ Current (form)

For more information on the order of events for controls on forms, click [image] .

Deleting records

When you delete a record, the following events occur for the form, and Microsoft Access displays a dialog box asking you to confirm the deletion:

Delete Þ BeforeDelConfirm Þ AfterDelConfirm

If you cancel the Delete event, the BeforeDelConfirm and AfterDelConfirm events don't occur and the dialog box isn't displayed.

Creating a new record

When you move the focus to a new (blank) record on a form and then create a new record by typing in a control, the following sequence of events occurs:

Current (form) Þ Enter (control) Þ GotFocus (control) Þ BeforeInsert (form) Þ AfterInsert (form)

The BeforeUpdate and AfterUpdate events for the controls on the form and for the new record occur after the BeforeInsert event and before the AfterInsert event.

For more information on events, click [image] .


 Order of events for reports and report sections

Order of events for reports and report sections

Events occur for reports and report sections when you open a report to print or preview it, or close a report.

Events for reports

When you open a report to print or preview it and then later close the report or move to another window in Microsoft Access, the following sequence of events occurs for the report:

Open Þ Activate Þ Close Þ Deactivate

When you switch between two open reports, the Deactivate event occurs for the first report, and the Activate event occurs for the second report:

Deactivate (report1) Þ Activate (report2)

The Deactivate event for a report also occurs when you switch from the report to another window in Access. However, the Deactivate event doesn't occur when you switch to a dialog box, to a form whose PopUp property is set to Yes, or to a window in another application.

When you open a report that is based on a query, Access triggers the Open event before running the underlying query. As a result, you can set the criteria for the report by using a macro or event procedure that responds to the Open event. For example, the macro or event procedure could open a custom dialog box in which you enter the report criteria.

Events for report sections

When you print or preview a report, the Format and Print events occur for the report sections after the Open and Activate events for the report and before the report's Close or Deactivate events:

Open (report) Þ Activate (report) Þ Format (report section) Þ Print (report section) Þ Close (report) Þ Deactivate (report)

In addition, the following events can occur during or after formatting but before the Print event:

  • The Retreat event occurs when Access returns to a previous section during report formatting.

  • The NoData event occurs if there are no records displayed by the report.

  • The Page event occurs after formatting but before printing. You can use this event to customize the appearance of the printed report.

For more information on events, click [image] .


 Query Field

Query Field

A query field represents data from a table linked to the query. By default, a query field inherits all the properties that it has in the underlying table or query. For example, if a table design specifies the display format of the Order Date field as Medium Date in the field's Format property, the Order Date field is formatted in the query recordset as Medium Date. Because the underlying field properties are the defaults, they aren't displayed on the property sheet.

If a field property is changed in the table design, the query field automatically inherits the change. If, however, you change a property within the query, the property setting within the table design is overridden. If the property is later changed in the table design, the change isn't reflected in the query.

You can set the properties for query fields within the Field Properties window of the query Design view.

To open the Field Properties window in query Design view for a query field, click Properties [image] on the Query Design toolbar.


Recommendations for a filtering method to use in a table, query, or form

Filter By Selection, Filter By Form, and Filter For Input are the easiest ways to filter records. If you can easily find and select in the form, or datasheet an instance of the value you want the filtered records to contain, use Filter By Selection. If you want to choose the values you're searching for from a list without scrolling through all the records in a datasheet or form, or if you want to specify multiple criteria at once, use Filter By Form. If the focus is in a field in a form or datasheet and you just want to type in place the exact value you're searching for or the expression whose result you want to use as your criteria, use Filter For Input. For complex filters, use Advanced Filter/Sort.

Note In a report, you can't create a filter using the filtering techniques mentioned previously. However, a report (as well as a form) can inherit a filter. For more information, click [image] .

Return to Create a filter in a table, query, or form


Report

A report is a Microsoft Access database object that presents information formatted and organized according to your specifications. Examples of reports are sales summaries, phone lists, and mailing labels.


 Report Section

Report Section

A report section is part of a report such as a header, footer, or detail section.

You can set report section properties that are attributes of a report which affect the appearance or behavior of a specific section. For example, you can set the CanGrow property to specify whether the section will increase vertically to print all the data the section contains. Section properties are set in report Design view.


 Requirements for using queries as filters

Requirements for using queries as filters

A query must meet certain requirements if you're going to use it as a filter. The query:

  • Must be based on the same underlying table or query as the datasheet or form to which you're applying it.

  • Can't include other tables or queries.

  • Must be a select query (not a crosstab query or action query).

  • Can't include fields that sum, count, or calculate another type of total for the values in a field.


 Resolve errors in Visual Basic code

Resolve errors in Visual Basic code

Debugging is a process you use to find and resolve errors, or bugs, in your Visual Basic code. There are three types of errors you may encounter as your code runs:

  • Compile-time errors occur as a result of incorrectly constructed code. You may have forgotten to balance pairs of statements (such as If and End If or For and Next), or you may have a programming mistake that violates the rules of Microsoft Visual Basic (such as a misspelled word, missing separator, or type mismatch error).

    Compile-time errors also include syntax errors, which are errors in grammar or punctuation. These include mismatched parentheses or an incorrect number of arguments passed to a function.

  • Run-time errors occur after the application starts to run. Examples of run-time errors include attempting an illegal operation, such as dividing by zero or writing to a file that doesn't exist.

  • Logic errors occur when the application doesn't perform as intended and produces incorrect results.

To help you isolate all three types of errors and to monitor how your code runs, the Visual Basic Editor provides debugging tools that let you step through your code one line at a time, examine or monitor the values of expressions and variables, and trace procedure calls.

Note To use most of the Microsoft Access debugging tools, you need to suspend execution of your code. For more information, click [image] .


 Understanding Scope and Visibility

Understanding Scope and Visibility

Procedure-level scoping applies to variables and constants that are declared within a procedure. Public or private module-level scoping applies to variables, constants, user-defined types, and Declare statements which are included at the top of a module. It also applies to Sub, Function, Property Get, Property Let, and Property Set procedures defined within that module. For more information, search the help index for "Declare statement" or "Property procedures".

The following table indicates how different elements are scoped at the two different scoping levels.

Scoping level | Type of element | Scope | Notes
Procedure-level | Variables | Private |
 | Constants | Private |
Module-level | Variables | Private unless declared as Public |
 | Constants | Private unless preceded by Public keyword | You can't declare a public constant within a class module.
 | Declare statements | Public unless preceded by Private keyword | Declare statements within class modules must be preceded by the Private keyword.
 | User-defined types | Public unless preceded by Private keyword | User-defined types declared within class modules must be preceded by the Private keyword.
 | Procedures | Public unless preceded by Private keyword | Event procedures in form and report modules are private by default.

Notes

  • Public elements defined in a standard module are available to all procedures in the current database and in referencing databases, unless the module contains an Option Private Module statement. If a module contains an Option Private Module statement, public elements are available only to procedures in the current database.

  • Class modules are private by default. Public elements defined in a class module are available to all procedures in the current database only; they are never available to referencing databases. Note that form and report modules are class modules.

  • Variables, constants, procedures, user-defined types, and Declare statements defined in a Microsoft Access database are never available to projects in other applications besides Microsoft Access.

  • To refer to a module-level variable or procedure in a class module, preface it with the name of the class. For example, if you have declared a module-level variable varOrders in a class module named Class1, you would refer to the module-level variable as Class1.varOrders. You need to do this if you use this variable in a standard module or in the Debug window. Use brackets around the class name of the form if the form name is two or more words.

  • A module-level variable declared in a class module stays in scope as long as an instance of the class exists. When you destroy the instance of the class, the variable goes out of scope.

  • In a standard module, once you initialize a module-level variable, the variable retains its value, whether or not code is running, until the variable is assigned another value, code is reset, or the database is closed.

  • If you create procedures with identical names in a class module and in a standard module, the procedure in the standard module is always called unless you preface the procedure with the class name of the class module.


 Should I create a Number or Currency field?

Should I create a Number or Currency field?

Microsoft Access provides two field data types to store data containing numeric values: Number or Currency.

Use a Number field to store numeric data to be used for mathematical calculations, except calculations that involve money or that require a high degree of accuracy. The kind and size of numeric values that can be stored in a Number field is controlled by setting the FieldSize property. For example, the Byte field size will only store whole numbers (no decimal values) from 0 to 255 and occupies 1 byte of disk space.

Use a Currency field to prevent rounding off during calculations. A Currency field is accurate to 15 digits to the left of the decimal point and 4 digits to the right. A Currency field occupies 8 bytes of disk space.

Number and Currency fields also provide predefined display formats. You can use the Format property to choose a predefined format or to create a custom format. For information on creating a custom format, click [image] .

For more information on creating a number or currency field, click [image] .


 Should I create a Text or a Memo field?

Should I create a Text or a Memo field?

Microsoft Access provides two field data types to store data with text or combinations of text and numbers: Text or Memo.

Use a Text data type to store data such as names, addresses, and any numbers that do not require calculations, such as phone numbers, part numbers, or postal codes. A Text field can store up to 255 characters, but the default field size is 50 characters. To control the maximum number of characters that can be entered in a Text field, set the FieldSize property.

Use the Memo data type if you need to store more than 255 characters. A Memo field can store up to 64,000 characters. If you want to store formatted text or long documents, you should create an OLE field instead of a Memo field. To find out more about OLE fields, click [image] .

Both Text and Memo data types store only the characters entered in a field; space characters for unused positions in the field aren't stored.

For more information on creating a text or memo field, click [image] .


 Should I use a table or query for a wizard to create a list box, drop-down list box, or combo box?

Should I use a table or query for a wizard to create a list box, drop-down list box, or combo box?

In most cases, you can use a table as the row source for a list box, drop-down list box, or combo box when you create the list box, drop-down list box, or combo box with a wizard. Use a query in the following cases:

  • If you want to include calculated fields in the list box, drop-down list box, or combo box. For example, you could concatenate a first name and a last name by typing the following expression: Name: [FirstName] & " "& [LastName]. You could define this calculated field in a query, and then include this field in the list box, drop-down list box, or combo box.

  • If you want to include fields from more than one table in the list box, drop-down list box, or combo box.

When you select fields from a table or query with a wizard in a form, Microsoft Access creates an SQL statement based on the fields that you select and sets the RowSource property of the list box or combo box to that SQL statement. When you select fields from a table or query with a wizard in a data access page, Access sets the ListRowSource property of the list box or drop-down list box to the table or query you selected.

Note Wizards are not available in a stand-alone data access page, or when you point a data access page to another database than the one currently open. In this case, you will have to create a list box or drop-down list box on your own.


Snapshot Viewer Control

An ActiveX control (Snapview.ocx) that you use to view a snapshot report from Microsoft Internet Explorer version 3.0 or later, or from any application that supports ActiveX controls, such as Microsoft Access or Microsoft Visual Basic for Applications.


 Sorting And Grouping Box

Sorting And Grouping Box

The Sorting And Grouping box specifies the order of your data and define the group levels for a report.

To display the Sorting And Grouping box, click Sorting And Grouping [image] on the toolbar.


Table

A table is the fundamental structure of a relational database management system. In Microsoft Access, a table is an object that stores data in records (rows) and fields (columns). The data is usually about a particular category of things, such as employees or orders.


 Table Field

Table Field

Table fields are separate pieces of information that make up a record within a table. You can control the appearance of data, specify default values, and speed up searching and sorting by setting field properties in the Field Properties section of table Design view.

Microsoft Access uses field properties when you view or edit data. For example, the Format, InputMask, and Caption properties that you set affect the appearance of table and query databases. The controls on new forms and reports that are based on the table inherit these properties by default. You can use other properties to set rules for data or to require data entry in your fields, which Microsoft Access enforces whenever you add or edit data in a table.

To open a table in Design view, go to the Database window, click the Tables tab, select the table you want to open, and then click Design.


Which type of frame should I use and should I insert or link my object in a form?

Example object | Type of control to use | Inserted or linked?
A logo on an invoice report that you don't need to update | Image control | Inserted (if disk space isn't an issue; otherwise linked)
A picture on a form or report that you expect to update | Unbound object frame | Inserted
Part of a Microsoft Excel worksheet in a sales report | Unbound object frame | Linked
A picture for each employee to be stored in an Employees table | Bound object frame | Inserted
Employee résumés (created and stored in a Word document) available from an Employees form | Bound object frame | Linked, and displayed as an icon

Microsoft Access automatically updates linked objects on a report when you preview or print it. It updates them on forms as shown in the following table.

Object type | Property | Updated when
Unbound object frame | UpdateOptions: Automatic Locked: No | The form is opened.
Bound object frame | UpdateOption: Automatic Enabled: Yes Locked: No | The bound object frame gets the focus.


Use an Access database with several versions of Microsoft Access

What do you want to do?

Use a one-file Access database with several versions of Microsoft Access

Use a front-end/back-end application with several versions of Microsoft Access

Not sure which choice you want?


Use the Upsizing Wizard

What do you want to do?

Learn about upsizing a Microsoft Access database

Learn when to upsize a Microsoft Access database to Microsoft SQL Server

Prepare to upsize a Microsoft Access database

Learn about ODBC data sources

Enter database and transaction log devices and sizes

Choose which tables to upsize

Choose which table attributes to upsize

Choose how to upsize your application

See how the Upsizing Wizard converts SQL syntax from a Microsoft Access database to a Microsoft Access project


 What's new in a Microsoft Access project

What's new in a Microsoft Access project

  • Easily create a client/server application A Microsoft Access project (.adp) is a new type of Access file that provides efficient, native-mode access to a Microsoft SQL Server database through the OLE DB component architecture. Using an Access project, you can easily create a client/server application.

  • Work with an Access project Working with a Microsoft Access project is very similar to working with an Access database. The process of creating forms, reports, data access pages, macros, and modules is the same. Once you connect to an SQL Server database, you can view, create, modify, and delete tables, views, stored procedures, and database diagrams using the Microsoft SQL Server Design Tools.

  • Use Microsoft Data Engine (MSDE) MSDE is a new technology that provides local data storage compatible with Microsoft SQL Server 7.0. Think of MSDE as a client/server data engine alternative to the file server Microsoft Jet database engine. It is designed and optimized for use on smaller computer systems, such as a single user computer or small workgroup server.

  • Upsize data and objects by using the Upsizing Wizard The Upsizing Wizard upsizes a Microsoft Access database (.mdb) to a new or existing Microsoft SQL Server 6.5 and 7.0 database or new Microsoft Access project (.adp) by upsizing the data and data definitions and migrating database objects.


 About updating data in a query whose tables have a one-to-many relationship

About updating data in a query whose tables have a one-to-many relationship

If a query is based on a one-to-many relationship, you might not be able to edit the data in the query's results. The following table lists the types of fields that you might not be able to modify, and, when appropriate, alternative methods for updating them.

Type of field | Solution
Join field from the "one" side | Enable cascading updates between the two tables. For more information, click [image] .
New records, if the "many" side join field doesn't appear in the datasheet | Add the join field from the "many" side to your query to allow adding new records.
Join field from the "many" side, after you've updated data on the "one" side | Save the record; then you'll be able to make changes to the "many" side join field.
Blank field from the table on the "one" side of a one-to-many relationship where an outer join exists | Enter values in fields from the table on the "many" side, but only if the joined field from the "one" side contains a value for that record.
New records, if entire unique key of ODBC table isn't output | Select all primary key fields of ODBC tables to allow inserts into them.


 Which type of AutoNumber field should I create?

Which type of AutoNumber field should I create?

Microsoft Access provides the AutoNumber data type to create fields that automatically enter a number when a record is added. Once a number is generated for a record, it can't be deleted or changed. An AutoNumber field can generate three kinds of numbers: sequential numbers that increment by one, random numbers, and Replication ID (also referred to as GUIDS — globally unique identifiers) numbers. AutoNumbers that increment by one are the most common kind of AutoNumber and are a good choice for use as a table's primary key. Random AutoNumbers will generate a random number that is unique to each record within the table. Replication ID AutoNumbers are used in database replication to generate unique identifiers for synchronizing replicas. Learn more about Replication ID AutoNumbers and when to use them.

For more information on creating an AutoNumber field, click [image] .


Work with a database

What do you want to do?

Customize the opening switchboard

See an overview of databases

Read about tables: what they are and how they work

Read about queries: what they are and how they work

Read about forms: what they are and how they work

Read about reports: what they are and how they work

Read about data access pages: what they are and how they work

Read about macros: what they are and how they work


Work with a Microsoft Access project

What do you want to do?

Understand how to use a Microsoft Access project

Learn about a Microsoft Access project

Learn about OLEDB and Data Links

Learn about Microsoft Data Engine (MSDE)

Learn about using Microsoft SQL Server database utilities from Microsoft Access

Optimize Microsoft Access project performance

Use documentation

Learn about Microsoft SQL Server documentation

Learn about the Northwind sample Access project and Microsoft SQL Server database

Upsize from an Access database to an Access project

Upsize your Microsoft Access database

Use the Upsizing Wizard

Share and update data

Learn about using a Microsoft Access project in a multiuser environment

Control the number of records retrieved in a form or datasheet in an Access project

Learn about updating data in a Microsoft Access project or data access page

Compare differences between a Microsoft Access database and a Microsoft Access project

See a comparison of database objects between a Microsoft Access database and a Microsoft Access project

See a comparison of data types between a Microsoft Access database and a Microsoft Access project

See a comparison of delimiters, operators, constants, and wildcard characters between a Microsoft Access database and a Microsoft Access project

See a comparison of SQL syntax between a Microsoft Access database and a Microsoft Access project

See a comparison of functions between Visual Basic for Applications and Microsoft SQL Server Transact-SQL


 Event Procedure Constants

Event Procedure Constants

AfterDelConfirm Event Procedure Constants

You can use the following constants with event procedures for the AfterDelConfirm event:

  • acDelete

  • acDeleteCancel

  • acDeleteOK

  • acDeleteUserCancel

BeforeDelConfirm Event Procedure Constants

You can use the following constants with event procedures for the BeforeDelConfirm event:

  • acDataAdded

  • acDataErrContinue

  • acDataErrDisplay

Button Mask Constants

You can use the following button mask constants with event procedures for the MouseDown, MouseUp, and MouseMove events:

  • acLeftButton

  • acMiddleButton

  • acRightButton

Key Mask Constants

You can use the following key mask constants with event procedures for the KeyDown, KeyUp, MouseDown, MouseUp, and MouseMove events:

  • acAltMask

  • acCtrlMask

  • acShiftMask

NotInList Event Procedure Constants

You can use the following constants with event procedures for the NotInList event:

  • acDataErrAdded

  • acDataErrContinue

  • acDataErrDisplay

Error Event Procedure Constants

You can use the following constants with event procedures for the Error event:

  • acDataErrContinue

  • acDataErrDisplay

Updated Event Procedure Constants

You can use the following constants with event procedures for the Updated event:

  • acOLEChanged

  • acOLEClosed

  • acOLERenamed

  • acOLESaved

ApplyFilter Event Procedure Constants

You can use the following constants with event procedures for the ApplyFilter event:

  • acApplyFilter

  • acCloseFilterWindow

  • acShowAllRecords

Filter Event Procedure Constants

You can use the following constants with event procedures for the Filter event:

  • acFilterAdvanced

  • acFilterByForm


Keycode Constants

You can use the following constants to represent keyboard values. These constants can be used In Microsoft Access in event procedures for the KeyDown and KeyUp events.

vbKey0 | vbKeyF5 | vbKeyNumpad4
vbKey1 | vbKeyF6 | vbKeyNumpad5
vbKey2 | vbKeyF7 | vbKeyNumpad6
vbKey3 | vbKeyF8 | vbKeyNumpad7
vbKey4 | vbKeyF9 | vbKeyNumpad8
vbKey5 | vbKeyF10 | vbKeyNumpad9
vbKey6 | vbKeyF11 | vbKeyO
vbKey7 | vbKeyF12 | vbKeyP
vbKey8 | vbKeyF13 | vbKeyPageDown
vbKey9 | vbKeyF14 | vbKeyPageUp
vbKeyA | vbKeyF15 | vbKeyPause
vbKeyAdd | vbKeyF16 | vbKeyPrint
vbKeyB | vbKeyG | vbKeyQ
vbKeyBack | vbKeyH | vbKeyR
vbKeyC | vbKeyHelp | vbKeyRButton
vbKeyCancel | vbKeyHome | vbKeyReturn
vbKeyCapital | vbKeyI | vbKeyRight
vbKeyClear | vbKeyInsert | vbKeyS
vbKeyControl | vbKeyJ | vbKeySelect
vbKeyD | vbKeyK | vbKeySeparator
vbKeyDecimal | vbKeyL | vbKeyShift
vbKeyDelete | vbKeyLButton | vbKeySnapshot
vbKeyDivide | vbKeyLeft | vbKeySpace
vbKeyDown | vbKeyM | vbKeySubtract
vbKeyE | vbKeyMButton | vbKeyT
vbKeyEnd | vbKeyMenu | vbKeyTab
vbKeyEscape | vbKeyMultiply | vbKeyU
vbKeyExecute | vbKeyN | vbKeyUp
vbKeyF | vbKeyNumlock | vbKeyV
vbKeyF1 | vbKeyNumpad0 | vbKeyW
vbKeyF2 | vbKeyNumpad1 | vbKeyX
vbKeyF3 | vbKeyNumpad2 | vbKeyY
vbKeyF4 | vbKeyNumpad3 | vbKeyZ


 Action Constants

Action Constants

You can use these constants when you use Visual Basic to run a method of the DoCmd object. Using these constants with a method of the DoCmd object is the same as running the corresponding action in a macro. Note that the DoMenuItem method is obsolete; you should use the RunCommand method and its associated constants in Microsoft Access 2000 instead. Constants listed below with an asterisk (*) have been replaced with other constants, but will still work for the method or methods listed.

DoCmd object constants | Used with
acActiveDataObject | GoToRecord
acAdd | OpenQuery, OpenTable, OpenStoredProcedure, OpenView
acAll | FindRecord
acAnywhere | FindRecord
acCopy | DoMenuItem
acCurrent | FindRecord
acCut | DoMenuItem
acDiagram | Close, CopyObject, DeleteObject, Rename, RepaintObject, Save, SelectObject, TransferDatabase
acDataAccessPage | Close, CopyObject, DeleteObject, Rename, RepaintObject, Save, SelectObject, TransferDatabase
acDataAccessPageBrowse | OpenDataAccessPage
acDataAccessPageDesign | OpenDataAccessPage
acDataForm | GoToRecord
acDataQuery | GoToRecord
acDataServerView | GoToRecord
acDataStoredProcedure | GoToRecord
acDataTable | GoToRecord
acDefault | Close, CopyObject, DeleteObject, Rename, RepaintObject, Save,SelectObject
acDelete | DoMenuItem
acDesign | OpenForm
acDialog | OpenForm
acDown | FindRecord
acDraft | PrintOut
acEdit | OpenQuery, OpenTable, OpenStoredProcedure, OpenView
acEditMenu | DoMenuItem
acEntire | FindRecord
acExit* | Quit (DoCmd object), Quit (Application object)
acExport | TransferDatabase, TransferSpreadsheet
acExportDelim | TransferText
acExportFixed | TransferText
acExportHTML | TransferText
acExportMerge | TransferText
acFile | DoMenuItem
acFirst | GoToRecord
acFilterNormal | ApplyFilter
acForm | Close, CopyObject, DeleteObject, Rename, RepaintObject, Save, SelectObject, TransferDatabase
acFormAdd | OpenForm
acFormatASP | OutputTo
acFormatDAP | OutputTo, SendObject
acFormatHTML | OutputTo, SendObject
acFormatIIS | OutputTo
acFormatRTF | OutputTo, SendObject
acFormatSNP | OutputTo
acFormatTXT | OutputTo, SendObject
acFormatXLS | OutputTo, SendObject
acFormBar | DoMenuItem
acFormDS | OpenForm
acFormEdit | OpenForm
acFormPropertySettings | OpenForm
acFormReadOnly | OpenForm
acGoTo | GoToRecord
acHidden | OpenForm
acHigh | PrintOut
acIcon | OpenForm
acImport | TransferDatabase, TransferSpreadsheet
acImportDelim | TransferText
acImportFixed | TransferText
acImportHTML | TransferText
acLast | GoToRecord
acLink | TransferDatabase, TransferSpreadsheet
acLinkDelim | TransferText
acLinkFixed | TransferText
acLinkHTML | TransferText
acLow | PrintOut
acMacro | Close, CopyObject, DeleteObject, Rename, RepaintObject, Save, SelectObject, TransferDatabase
acMedium | PrintOut
acMenuCheck | SetMenuItem
acMenuGray | SetMenuItem
acMenuUncheck | SetMenuItem
acMenuUngray | SetMenuItem
acMenuVer1X | DoMenuItem
acMenuVer20 | DoMenuItem
acMenuVer70 | DoMenuItem
acModule | Close, CopyObject, DeleteObject, Rename, RepaintObject, Save, SelectObject, TransferDatabase
acNew | DoMenuItem
acNewRec | GoToRecord
acNext | GoToRecord
acNormal | OpenForm
acObject | DoMenuItem
acObjectUpdate | DoMenuItem
acObjectVerb | DoMenuItem
acOutputDataAccessPage | OutputTo
acOutputForm | OutputTo
acOutputModule | OutputTo
acOutputQuery | OutputTo
acOutputReport | OutputTo
acOutputTable | OutputTo
acPages | PrintOut
acPaste | DoMenuItem
acPreview | OpenForm
acPrevious | GoToRecord
acPrintAll | PrintOut
acPrompt* | Close, Quit (DoCmd object), Quit (Application object)
acQuery | Close, CopyObject, DeleteObject, Rename, RepaintObject, Save, SelectObject, TransferDatabase
acQuitPrompt | Quit (DoCmd object), Quit (Application object)
acQuitSaveAll | Quit (DoCmd object), Quit (Application object)
acQuitSaveNone | Quit (DoCmd object), Quit (Application object)
acReadOnly | OpenQuery, OpenTable, OpenStoredProcedure, OpenView
acRecordsMenu | DoMenuItem
acRefresh | DoMenuItem
acReport | Close, CopyObject, DeleteObject, Rename, RepaintObject, Save, SelectObject, TransferDatabase
acSaveForm | DoMenuItem
acSaveFormAs | DoMenuItem
acSave* | Quit (DoCmd object), Quit (Application object)
acSaveNo | Close
acSavePrompt | Close
acSaveRecord | DoMenuItem
acSaveYes | Close
acSearchAll | FindRecord
acSelectAllRecords | DoMenuItem
acSelection | PrintOut
acSelectRecord | DoMenuItem
acSendDataAccessPage | SendObject
acSendForm | SendObject
acSendModule | SendObject
acSendNoObject | SendObject
acSendQuery | SendObject
acSendReport | SendObject
acSendTable | SendObject
acServerFilter | ApplyFilter
acServerView | Close, CopyObject, DeleteObject, Rename, RepaintObject, Save, SelectObject, TransferDatabase
acSpreadsheetTypeExcel3 | TransferSpreadsheet
acSpreadsheetTypeExcel4 | TransferSpreadsheet
acSpreadsheetTypeExcel5 | TransferSpreadsheet
acSpreadsheetTypeExcel7 | TransferSpreadsheet
acSpreadsheetTypeExcel8 | TransferSpreadsheet
acSpreadsheetTypeExcel9 | TransferSpreadsheet
acSpreadsheetTypeLotusWK1 | TransferSpreadsheet
acSpreadsheetTypeLotusWK3 | TransferSpreadsheet
acSpreadsheetTypeLotusWK4 | TransferSpreadsheet
acSpreadsheetTypeLotusWJ2 — Japanese version only | TransferSpreadsheet
acStart | FindRecord
acStoredProcedure | Close, CopyObject, DeleteObject, Rename, RepaintObject, Save, SelectObject, TransferDatabase
acTable | Close, CopyObject, DeleteObject, Rename, RepaintObject, Save, SelectObject, TransferDatabase
acToolbarNo | ShowToolbar
acToolbarWhereApprop | ShowToolbar
acToolbarYes | ShowToolbar
acUndo | DoMenuItem
acUp | FindRecord
acViewDesign | OpenQuery, OpenReport, OpenStoredProcedure, OpenTable, OpenView
acViewNormal | OpenQuery, OpenReport, OpenStoredProcedure, OpenTable, OpenView
acViewPreview | OpenQuery, OpenReport, OpenStoredProcedure, OpenTable, OpenView
acWindowNormal | OpenForm


 Miscellaneous Constants

Miscellaneous Constants

The following lists indicate miscellaneous intrinsic constants provided by Microsoft Access.

List Box and Combo Box Constants

You can use the following constants to fill a list box or combo box by using a function. You use these constants with a function that's the setting of the RowSourceType property, by using a special function format.

acLBClose | acLBGetRowCount
acLBEnd | acLBGetValue
acLBGetColumnCount | acLBInitialize
acLBGetColumnWidth | acLBOpen
acLBGetFormat |

SysCmd Method Constants

You can use the following constants with the SysCmd method:

acDataAccessPage | acSysCmdAccessVer
acDefault | acSysCmdClearHelpTopic
acDiagram | acSysCmdClearStatus
acForm | acSysCmdGetObjectState
acMacro | acSysCmdGetWorkgroupFile
acModule | acSysCmdIniFile
acObjStateDirty | acSysCmdInitMeter
acObjStateNew | acSysCmdProfile
acObjStateOpen | acSysCmdRemoveMeter
acQuery | acSysCmdRuntime
acReport | acSysCmdSetStatus
acServerView | acSysCmdUpdateMeter
acStoredProcedure | acTable
acSysCmdAccessDir |

ControlType Property, CreateControl and CreateReportControl Methods Constants

You can use one of the following constants with the ControlType property and the CreateControl and CreateReportControl methods to specify the control type:

acBoundObjectFrame | acOptionButton
acCheckBox | acOptionGroup
acComboBox | acPage
acCommandButton | acPageBreak
acCustomControl | acRectangle
acImage | acSubform
acLabel | acTabCtl
acLine | acTextBox
acListBox | acToggleButton
acObjectFrame |

Section Property, CreateControl and CreateReportControl Methods Constants

You can use one of the following constants with the Section property and the CreateControl and CreateReportControl methodss to specify a section on a form or report:

acDetail | acGroupLevel2Header
acFooter | acHeader
acGroupLevel1Footer | acPageFooter
acGroupLevel1Header | acPageHeader
acGroupLevel2Footer |

OLE Constants

The following table gives the OLE constants, and shows the language elements with which these constants can be used.

OLE constants | Used with
acOLEActivate | Action property
acOLEActivateDoubleClick | AutoActivate property
acOLEActivateGetFocus | AutoActivate property
acOLEActivateManual | AutoActivate property
acOLEChanged | Updated event
acOLEClose | Action property
acOLEClosed | Updated event
acOLECopy | Action property
acOLECreateEmbed | Action property
acOLECreateFromFile (same as acOLECreateLink) | Action property
acOLECreateLink | Action property
acOLECreateNew (same as acOLECreateEmbed) | Action property
acOLEDelete | Action property
acOLEDisplayContent | DisplayType property
acOLEDisplayIcon | DisplayType property
acOLEEither | OLETypeAllowed property
acOLEEmbedded | OLEType property, OLETypeAllowed property
acOLEFetchVerbs | Action property
acOLEInsertObjDlg | Action property
acOLELinked | OLEType property, OLETypeAllowed property
acOLENone | OLEType property
acOLEPaste | Action property
acOLEPasteSpecialDlg | Action property
acOLERenamed | Updated event
acOLESaved | Updated event
acOLESizeAutoSize (not used) | SizeMode property
acOLESizeClip | SizeMode property
acOLESizeStretch | SizeMode property
acOLESizeZoom | SizeMode property
acOLEUpdate | Action property
acOLEUpdateAutomatic | UpdateOptions property
acOLEUpdateFrozen (not used) | UpdateOptions property
acOLEUpdateManual | UpdateOptions property
acOLEVerbHide | Verb property
acOLEVerbInPlaceActivate | Verb property
acOLEVerbInPlaceUIActivate | Verb property
acOLEVerbOpen | Verb property
acOLEVerbPrimary | Verb property
acOLEVerbShow | Verb property

SpecialEffect Property Constants

The following list gives the constants you can use to specify or determine the state of the SpecialEffect property. The acEffectNormal, acEffectRaised, and acEffectSunken constants can also be used with the DatasheetCellsEffect property.

acEffectChisel | acEffectRaised
acEffectEtched | acEffectShadow
acEffectNormal | acEffectSunken

Gridlines Constants

The following list gives the constants you can use to specify or determine the state of the gridlines effect for an object in datasheet view. These constants can be used with the DatasheetGridlinesBehavior property.

acGridlinesBoth | acGridlinesNone
acGridlinesBothV2 | acGridlinesVert
acGridlinesHoriz |

Type Constants

The following list gives the constants you can use to determine if the current module is a standard module or a class module. These constants can be used with the Type property.

acClassModule acStandardModule

HyperlinkPart Function Constants

You can use the following constants with the HyperlinkPart function:

acAddress | acFullAddress
acDisplayedValue | acScreenTip
acDisplayText | acSubAddress

Procedure Constants

You can use the following constants with the ProcStartLine, ProcBodyLine, ProcOfLine, and ProcCountLines properties.

vbext_pk_Get | vbext_pk_Proc
vbext_pk_Let | vbext_pk_Set

Kind Property Constants

You can use the following constants with the Kind property of the Reference object:

vbext_rk_Project vbext_rk_TypeLib

Conditional Formatting Constants

You can use the following constants with the Type property of the FormatCondition object:

acExpression | acFieldValue
acFieldHasFocus |


 RunCommand Method Constants

RunCommand Method Constants

You can use these constants in Visual Basic when you use the RunCommand method. Using these constants with the RunCommand method is the same as supplying the value for the RunCommand action in a macro.

NotesThe acCmdDebugWindow constant will run the Immediate Window menu command.

Constants listed below with asterisks (* or **) have some specific restriction about when they can be used with the RunCommand method.

  • *Only available when the Object Browser is active.

  • **Menu items are available in both VBE and non-VBE views.

Constants shown in italic are included for backwards compatibility only.

acCmdAboutMicrosoftAccess | acCmdGoContinue | acCmdRename
acCmdAddWatch | acCmdGoForward | acCmdRenameColumn
acCmdAdvancedFilterSort | acCmdHideColumns | acCmdRepairDatabase
acCmdAlignBottom | acCmdHidePane | acCmdReplace**
acCmdAlignLeft | acCmdHideTable | acCmdReportHdrFtr
acCmdAlignRight | acCmdHorizontalSpacingDecrease | acCmdReset
acCmdAlignToGrid | acCmdHorizontalSpacingIncrease | acCmdResolveConflicts
acCmdAlignTop | acCmdHorizontalSpacingMakeEqual | acCmdRowHeight
acCmdAlignToShortest | acCmdHyperlinkDisplayText | acCmdRun
acCmdAlignToTallest | acCmdImport | acCmdRunMacro
acCmdAnalyzePerformance | acCmdIndent | acCmdRunOpenMacro
acCmdAnalyzeTable | acCmdIndexes | acCmdSave**
acCmdAnswerWizard | acCmdInsertActiveXControl | acCmdSaveAllModules
acCmdApplyDefault | acCmdInsertChart | acCmdSaveAs**
acCmdApplyFilterSort | acCmdInsertFile | acCmdSaveAsASP
acCmdAppMaximize | acCmdInsertFileIntoModule | acCmdSaveAsHTML
acCmdAppMinimize | acCmdInsertHyperlink | acCmdSaveAsIDC
acCmdAppMove | acCmdInsertLookupColumn | acCmdSaveAsQuery
acCmdAppRestore | acCmdInsertLookupField | acCmdSaveAsReport
acCmdAppSize | acCmdInsertObject | acCmdSaveLayout
acCmdArrangeIconsAuto | acCmdInsertPage | acCmdSaveModuleAsText
acCmdArrangeIconsByCreated | acCmdInsertPicture | acCmdSaveRecord
acCmdArrangeIconsByModified | acCmdInsertProcedure | acCmdSelectAll
acCmdArrangeIconsByName | acCmdInsertQueryColumn | acCmdSelectAllRecords
acCmdArrangeIconsByType | acCmdInsertRows | acCmDSelectDataAccessPage
acCmdAutoCorrect | acCmdInsertTableColumn | acCmdSelectForm
acCmdAutoDial | acCmdInvokeBuilder | acCmdSelectRecord
acCmdAutoFormat | acCmdJoinProperties | acCmdSelectReport
acCmdBookmarksClearAll | acCmdLastPosition | acCmdSend
acCmdBookmarksNext | acCmdLayoutPreview | acCmdSendToBack
acCmdBookmarksPrevious | acCmdLineUpIcons | acCmdSetControlDefaults
acCmdBookmarksToggle | acCmdLinkTables | acCmdSetDatabasePassword
acCmdBringToFront | acCmdListConstants | acCmdSetNextStatement
acCmdCallStack | acCmdLoadFromQuery | acCmdShowAllRelationships
acCmdChangeToCheckBox | acCmdMacroConditions | acCmdShowDirectRelationships
acCmdChangeToComboBox | acCmdMacroNames | acCmdShowMembers
acCmdChangeToImage | acCmdMicrosoftAccessHelpTopics | acCmdShowNextStatement
acCmdChangeToLabel | acCmdMicrosoftOnTheWeb | acCmdShowOnlyWebToolbar
acCmdChangeToListBox | acCmdMicrosoftScriptEditor | acCmdShowPaneDiagram
acCmdChangeToOptionButton | acCmdMoreWindows | acCmdShowPaneGrid
acCmdChangeToTextBox | acCmdNewDatabase | acCmdShowPaneView
acCmdChangeToToggleButton | acCmdNewObjectAutoDataAccessPage | acCmdShowTable
acCmdClearAll | acCmdNewObjectAutoForm | acCmdSingleStep
acCmdClearAllBreakpoints | acCmdNewObjectAutoReport | acCmdSizeToFit
acCmdClearGrid | acCmdNewObjectClassModule | acCmdSizeToFitForm
acCmdClearItemDefaults | acCmdNewObjectDataAccessPage | acCmdSizeToGrid
acCmdClose | acCmdNewObjectDiagram | acCmdSizeToNarrowest
acCmdCloseWindow | acCmdNewObjectForm | acCmdSizeToWidest
acCmdColumnWidth | acCmdNewObjectMacro | acCmdSnapToGrid
acCmdCompactDatabase | acCmdNewObjectModule | acCmdSortAscending
acCmdCompileAllModules | acCmdNewObjectQuery | acCmdSortDescending
acCmdCompileAndSaveAllModules | acCmdNewObjectReport | acCmdSortingAndGrouping
acCmdCompileLoadedModules | acCmdNewObjectStoredProcedure | acCmdSpelling
acCmdCompleteWord | acCmdNewObjectTable | acCmdSQLView
acCmdControlWizardsToggle | acCmdNewObjectView | acCmdStartupProperties
acCmdConvertDatabase | acCmdObjBrwFindWholeWordOnly* | acCmdStepOut
acCmdConvertMacrosToVisualBasic | acCmdObjBrwGroupMembers* | acCmdStepOver
acCmdCopy** | acCmdObjBrwHelp* | acCmdStepToCursor
acCmdCopyHyperlink | acCmdObjBrwShowHiddenMembers* | acCmdStopLoadingPage
acCmdCreateMenuFromMacro | acCmdObjBrwViewDefinition* | acCmdSubformDatasheet
acCmdCreateRelationship | acCmdObjectBrowser* | acCmdSynchronizeNow
acCmdCreateReplica | acCmdOLEDDELinks | acCmdTabControlPageOrder
acCmdCreateShortcut | acCmdOLEObjectConvert | acCmdTableNames
acCmdCreateShortcutMenuFromMacro | acCmdOLEObjectDefaultVerb | acCmdTabOrder
acCmdCreateToolbarFromMacro | acCmdOpenDatabase | acCmdTestValidationRules
acCmdCut** | acCmdOpenHyperlink | acCmdTileHorizontally
acCmdDataAccessPageBrowse | acCmdOpenNewHyperlink | acCmdTileVertically
acCmdDataAccessPageDesignView | acCmdOpenSearchPage | acCmdToggleBreakpoint
acCmdDatabaseProperties | acCmdOpenStartPage | acCmdToggleFilter
acCmdDataEntry | acCmdOpenTable | acCmdToolbarControlProperties
acCmdDatasheetView | acCmdOpenURL | acCmdToolbarsCustomize**
acCmdDateAndTime | acCmdOptions** | acCmdTransparentBackground
acCmdDebugWindow | acCmdOutdent | acCmdTransparentBorder
acCmdDelete** | acCmdOutputToExcel | acCmdUndo**
acCmdDeletePage | acCmdOutputToRTF | acCmdUnfreezeAllColumns
acCmdDeleteQueryColumn | acCmdOutputToText | acCmdUnhideColumns
acCmdDeleteRecord | acCmdPageHdrFtr | acCmdUserAndGroupAccounts
acCmdDeleteRows | acCmdPageNumber | acCmdUserAndGroupPermissions
acCmdDeleteTab | acCmdPageSetup | acCmdUserLevelSecurityWizard
acCmdDeleteTableColumn | acCmdParameterInfo | acCmdVerticalSpacingDecrease
acCmdDeleteWatch | acCmdPaste** | acCmdVerticalSpacingIncrease
acCmdDesignView | acCmdPasteAppend | acCmdVerticalSpacingMakeEqual
acCmdDiagramAddRelatedTables | acCmdPasteSpecial | acCmdViewCode
acCmdDiagramAutosizeSelectedTables | acCmdPreviewEightPages | acCmdViewDataAccessPages
acCmdDiagramDeleteRelationship | acCmdPreviewFourPages | acCmdViewDetails
acCmdDiagramLayoutDiagram | acCmdPreviewOnePage | acCmdViewDiagrams
acCmdDiagramLayoutSelection | acCmdPreviewTwelvePages | acCmdViewFieldList
acCmdDiagramModifyUserDefinedView | acCmdPreviewTwoPages | acCmdViewForms
acCmdDiagramNewLabel | acCmdPrimaryKey | acCmdViewGrid
acCmdDiagramNewTable | acCmdPrint** | acCmdViewLargeIcons
acCmdDiagramRecalculatePageBreaks | acCmdPrintPreview | acCmdViewList
acCmdDiagramRelationshipLabels | acCmdProcedureDefinition | acCmdViewMacros
acCmdDiagramViewPageBreaks | acCmdProperties | acCmdViewModules
acCmdDocMaximize** | acCmdPublish | acCmdViewQueries
acCmdDocMinimize** | acCmdPublishDefaults | acCmdViewReports
acCmdDocMove** | acCmdQueryAddToOutput | acCmdViewRuler
acCmdDocRestore** | acCmdQueryParameters | acCmdViewSmallIcons
acCmdDocSize** | acCmdQueryTotals | acCmdViewStoredProcedure
acCmdDocumenter | acCmdQueryTypeAppend | acCmdViewTableColumnNames
acCmdDuplicate | acCmdQueryTypeCrosstab | acCmdViewTableColumnProperties
acCmdEditHyperlink | acCmdQueryTypeDelete | acCmdViewTableKeys
acCmdEditingAllowed | acCmdQueryTypeMakeTable | acCmdViewTableNameOnly
acCmdEditRelationship | acCmdQueryTypeSelect | acCmdViewTables
acCmdEditTriggers | acCmdQueryTypeSQLDataDefinition | acCmdViewTableUserView
acCmdEditWatch | acCmdQueryTypeSQLPassThrough | acCmdViewToolbox
acCmdEncryptDecryptDatabase | acCmdQueryTypeSQLUnion | acCmdViewVerifySQL
acCmdEnd | acCmdQueryTypeUpdate | acCmdViewViews
acCmdExit | acCmdQuickInfo | acCmdWindowArrangeIcons
acCmdFavoritesAddTo | acCmdQuickPrint | acCmdWindowCascade
acCmdFavoritesOpen | acCmdQuickWatch | acCmdWindowHide
acCmdFieldList | acCmdRecordsGoToFirst | acCmdWindowSplit
acCmdFilterByForm | acCmdRecordsGoToLast | acCmdWindowUnhide
acCmdFilterBySelection | acCmdRecordsGoToNew | acCmdWordMailMerge
acCmdFilterExcludingSelection | acCmdRecordsGoToNext | acCmdZoom10
acCmdFind** | acCmdRecordsGoToPrevious | acCmdZoom100
acCmdFindNext** | acCmdRecoverDesignMaster | acCmdZoom150
acCmdFindNextWordUnderCursor | acCmdRedo | acCmdZoom200
acCmdFindPrevious | acCmdReference | acCmdZoom25
acCmdFindPrevWordUnderCursor | acCmdRefresh | acCmdZoom50
acCmdFitToWindow | acCmdRefreshPage | acCmdZoom75
acCmdFont | acCmdRegisterActiveXControls | acCmdZoomBox
acCmdFormatCells | acCmdRelationships | acCmdZoomSelection
acCmdFormHdrFtr | acCmdRemove |
acCmdFormView | acCmdRemoveFilterSort |
acCmdFreezeColumn | acCmdRemoveTable |
acCmdGoBack |  |


 Security Constants

Security Constants

You can assign permissions to database objects by using Visual Basic:

acSecFrmRptExecute | acSecMacReadDef
acSecFrmRptReadDef | acSecMacWriteDef
acSecFrmRptWriteDef | acSecModReadDef
acSecMacExecute | acSecModWriteDef

Note The constants beginning with acSec are available to set database object permissions only by using Visual Basic.


Action Query

An action query changes data or copies data. Action queries include append, delete, make-table, and update queries. In contrast, a select query doesn't copy or change data; it asks a question and returns a set of records.

Action query type | Description
Append | Adds the records in a query's result set to the end of an existing table.
Delete | Deletes a set of rows that match the criteria you specify.
Make-table | Creates a new table from the result set of an existing query.
Update | Changes a set of records according to criteria you specify.


 ActiveX Control (Form)

ActiveX Control (Form)

In addition to the built-in controls that appear in the toolbox, Microsoft Access supports ActiveX controls (formerly known as custom or OLE controls). An ActiveX control, like a built-in control, is an object that you place on a form to enable or enhance a user's interaction with an application. ActiveX controls have events and can be incorporated into other controls. These controls have an .ocx file name extension. The Calendar control is an example of an ActiveX control.

Control: | Tool:

Note This control should not be confused with the Dynamic HTML ActiveX control used on a data access page. For information about a ActiveXcontrol on a data access page, see ActiveX Control (Data Access Pages).


 ActiveX Control (Data Access Pages)

ActiveX Control (Data Access Pages)

In addition to the built-in controls that appear in the toolbox, Microsoft Access supports ActiveX controls (formerly known as custom or OLE controls). An ActiveX control, like a built-in control, is an object that you place on a form to enable or enhance a user's interaction with an application. ActiveX controls have events and can be incorporated into other controls. These controls have an .ocx file name extension. The Calendar control is an example of an ActiveX control.

Control: | Tool:
Calendar control | ActiveX control


Bound Control

A bound control is a control on a form or report that gets its contents from a field in the underlying table, query, or SQL statement. (The control's ControlSource property is set to a field name in the table, query, or SQL statement.) For example, a text box that displays an employee's last name is bound to the LastName field in the Employees table.


 Bound HTML Control

Bound HTML Control

The bound HTML control can be used to store HTML code in a field in a table, and when the data access page displays the values in that field, the HTML code performs the actions that you specified.

Tool:
Bound HTML control

When the field or column is placed on a data access page as a bound HTML control, the contents of the field are rendered as HTML and are not editable.

Notes

  • You can make the bound HTML control the default control for a grouped data access page. Set the DefaultControlType property of the data access page to Bound HTML.

  • You can use a bound HTML control to display calculations and all data on a grouped data access page. The page will load faster in Microsoft Internet Explorer 5 if you use HTML controls.

  • You can't use the navigation control to sort or filter on bound HTML controls in Page view or in Internet Explorer 5.


 Bound Hyperlink Control

Bound Hyperlink Control

The bound hyperlink control can add a bound hyperlink to a text field of a data access page.

Tool:
Bound hyperlink control

You can use a bound hyperlink when you want a different hyperlink address for each record in a table. As you move from record to record, you can click on the hyperlink and go to a different Web page for each record.


 Bound Object Frame Control

Bound Object Frame Control

A bound object frame control displays a picture, chart, or any OLE object stored in a table in a Microsoft Access database. For example, if you store pictures of your employees in a table in Microsoft Access, you can use a bound object frame to display these pictures on a form or report.

Control: | Tool:

Remarks

This control type allows you to create or edit the object from within the form or report by using the OLE server.

A bound object frame is bound to a field in an underlying table.

The field in the underlying table to which the bound object frame is bound must be of the OLE Object data type.

The object in a bound object frame is different for each record. The bound object frame can display linked or embedded objects. If you want to display objects not stored in an underlying table, use an unbound object frame or an image control.


 Chart Control (Forms and Reports)

Chart Control (Forms and Reports)

You can use the chart control to embed a chart that displays Microsoft Access data from a form or report. You can then edit the chart by using Microsoft Graph from within the form or report.

Control:

Note This control should not be confused with the Dynamic HTML image, hotspot image, or Office chart, or Office Spreadsheet control used on a data access page. For information about these control on a data access page, see Image, Hotspot, Office Chart, or Office Spreadsheet Control (Data Access Pages).

Remarks

When you place a chart control on a form or report, Microsoft Access displays the Chart Wizard to help you create the chart.

Note To embed or link a chart containing data from other applications, use an unbound object frame or bound object frame control.


 Check Box Control (Forms and Reports)

Check Box Control (Forms and Reports)

A check box on a form or report is a stand-alone control that display a Yes/No value from an underlying record source.

Control: | Tool:

Note This control should not be confused with the Dynamic HTML check box control used on a data access page. For information about a check box control on a data access page, see Check Box Control (Data Access Pages).

Remarks

When you select or clear a check box that's bound to a Yes/No field, Microsoft Access displays the value in the underlying table according to the field's Format property (Yes/No, True/False, or On/Off).

You can also use check boxes in an option group to display values to choose from.

It's also possible to use an unbound check box in a custom dialog box to accept user input.


 Check Box Control (Data Access Pages)

Check Box Control (Data Access Pages)

A check box on a data access page is a bound control that displays a Yes/No value from an underlying record source.

Control: | Tool:
Check box | Check Box control

Remarks

When you select or clear a check box that's bound to a Yes/No field, Microsoft Access displays the value in the underlying table according to the field's Format property (Yes/No, True/False, or On/Off).

You can also use check boxes in an option group to display values to choose from.

It's also possible to use an unbound check box in a custom dialog box to accept user input.


 Combo Box Control (Forms)

Combo Box Control (Forms)

The combo box control combines the features of a text box and a list box. Use a combo box when you want the option of either typing a value or selecting a value from a predefined list.

Control: | Tool:

Note This control should not be confused with the Dynamic HTML drop-down list box control used on a data access page. For information about a drop-down list box control on a data access page, see Drop-down List Box Control (Data Access Page).

Remarks

In Form view, Microsoft Access doesn't display the list until you click the combo box's arrow.

If you have Control Wizards on before you select the combo box tool, you can create a combo box with a wizard. To turn Control Wizards on or off, click the Control Wizards tool [image] in the toolbox.

The setting of the LimitToList property determines whether you can enter values that aren't in the list.

The list can be single- or multiple-column, and the columns can appear with or without headings.


 Command Button Control (Forms)

Command Button Control (Forms)

A command button on a form can start an action or a set of actions. For example, you could create a command button that opens another form. To make a command button do something, you write a macro or event procedure and attach it to the button's OnClick property.

Control: | Tool:

Note This control should not be confused with the Dynamic HTML command button control used on a data access page. For information about a command button control on a data access page, see Command Button Control (Data Access Pages).

Remarks

You can display text on a command button by setting its Caption property, or you can display a picture by setting its Picture property.

Tip You can create over 30 different types of command buttons with the Command Button Wizard. When you use the Command Button Wizard, Microsoft Access creates the button and the event procedure for you.


 Command Button Control (Data Access Pages)

Command Button Control (Data Access Pages)

A command button on a data access page can start an action or a set of actions. On a data access page, code written in either JavaScript or Visual Basic Script is attached to a command button using the Microsoft Visual Script Editor.

Control: | Tool:
Command button | Command Button control

Remarks

You can display text on a command button by setting its Value property.


 Crosstab Query

Crosstab Query

A crosstab query computes summary totals based on values for each row and column. It calculates a sum, average, count, or other type of total on records, and then groups the result by two types of information — one down the left side of the datasheet and the other across the top. For example, the Quarterly Orders by Product query in the Northwind sample database is a crosstab query.


 Drop-down List Box Control (Data Access Pages)

Drop-down List Box Control (Data Access Pages)

The drop-down list box control on a data access page combines some of the features of a text box and a list box. Use a drop-down list box control when you want the option of displaying and selecting a value from a predefined list.

Control: | Tool:
Combo box | ComboBox Tool

Remarks

In Page view, Microsoft Access doesn't display the list until you click the drop-down list box control's arrow.

If you have Control Wizards on before you select the drop-down list box control tool, you can create a drop-down list box with a wizard. To turn Control Wizards on or off, click the Control Wizards tool [image] in the toolbox.

You cannot enter values that aren't in the list.

The list can be single- or multiple-column, and the columns can appear with or without headings.


 Subform/Subreport Control

Subform/Subreport Control

The subform/subreport control embeds a form in a form or a report in a report.

Control: | Tool:

For example, you can use a form with a subform to present one-to-many relationships, such as one product category with the items that fall into that category. In this case, the main form can display the category ID, name, and description; the subform can display the available products in that category.

Tip Instead of creating the main form, and then adding the subform control to it, you can simultaneously create the main form and subform with a wizard. You can also create a subform or subreport by dragging an existing form or report from the Database window to the main form or report.


 Expand Control

Expand Control

The expand control can add a expand/collapse button to a data access page.

Tool:

Remarks

This control allows the user to display or hide records which have been grouped under another record.


 Hotspot Image Control

Hotspot Image Control

The hotspot image control can add an unbound image to a data access page.

Tool:
Hotspot Image control

Remarks

Use the hotspot image control to add an image to a data access page that, when clicked, displays another Web page from your hard drive, the Web, or another location. When you create a hotspot image control, you select the image to display on the page and the address of the file to jump to.

  • The Insert Picture dialog box displays a list of pictures that can be selected as the image.

  • The Insert Hyperlink dialog box allows the user to select the file or web page that will be linked to the image control.

In Page view, as the pointer passes over the image, the pointer changes to a hand, indicating that the image is a link that you can click to go to another page. You can also define ScreenTips and alternate text for the image.


 Hyperlink Control (Data Access Page)

Hyperlink Control (Data Access Page)

The hyperlink control can add a hyperlink to a data access page.

Tool:

When the hyperlink control is placed on a data access page, Microsoft Access displays the Insert Hyperlink dialog box. The Insert Hyperlink dialog box allows the user to select the file or web page that will be linked to the hyperlink control.


 Image Control (Forms and Reports)

Image Control (Forms and Reports)

The image control can add a picture to a form or report. For example, you could include an image control for a logo on an Invoice report.

Control: | Tool:

Note This control should not be confused with the Dynamic HTML image control used on a data access page. For information about a image control on a data access page, see Image Control (Data Access Page).

Remarks

You can use the image control or an unbound object frame for unbound pictures. The advantage of using the image control is that it's faster to display. The advantage of using the unbound object frame is that you can edit the object directly from the form or report.


 Image Control (Data Access Pages)

Image Control (Data Access Pages)

The image control can add a picture to a data access page. For example, you could include an image control for a logo on a Sales entry page.

Control: | Tool:
Image control | Image frame control

Remarks

You can use the image control or an unbound object frame for unbound pictures. The advantage of using the image control is that it's faster to display.


 Label Control (Forms and Reports)

Label Control (Forms and Reports)

Labels on a form or report display descriptive text such as titles, captions, or brief instructions. Labels have certain characteristics:

  • Labels don't display values from fields or expressions.

  • Labels are always unbound.

  • Labels don't change as you move from record to record.

Control: | Tool:

Note This control should not be confused with the Dynamic HTML label control used on a data access page. For information about a label control on a data access page, see Label Control (Data Access Pages).

Remarks

A label can be attached to another control. When you create a text box, for example, it has an attached label that displays a caption for that text box. This label appears as a column heading in the Datasheet view of a form.

When you create a label by using the Label tool, the label stands on its own — it isn't attached to any other control. You use stand-alone labels for information such as the title of a form or report, or for other descriptive text. Stand-alone labels don't appear in Datasheet view.


 Label Control (Data Access Pages)

Label Control (Data Access Pages)

Labels on an data access page display descriptive text such as titles, captions, or brief instructions. Labels have certain characteristics:

  • Labels don't display values from fields or expressions.

  • Labels don't change as you move from record to record.

Control: | Tool:
Label | Label control

Remarks

A label can be attached to another control. When you create a text box, for example, it has an attached label that displays a caption for that text box.

When you create a label by using the Label tool, the label stands on its own it isn't attached to any other control. You use stand-alone labels for information such as the title, or for other descriptive text.


 Line Control (Forms and Reports)

Line Control (Forms and Reports)

The line control displays a horizontal, vertical, or diagonal line on a form or report.

Control: | Tool:

Note This control should not be confused with the Dynamic HTML line control used on a data access page. For information about a line control on a data access page, see Line Control (Data Access Pages).

Remarks

You can use Line/Border Width [image] to change the line width. You can use Line/Border Color [image] to change the color of the border or make it transparent. You can change the line style (dots, dashes, and so on) of the border by using the BorderStyle property.


 Line Control (Data Access Pages)

Line Control (Data Access Pages)

The line control displays a horizontal, vertical, or diagonal line on a data access page.

Control: | Tool:
Line | Line control

Remarks

You can use the Height property to change the line width. You can use Line/Border Color [image] to change the color of the border or make it transparent.


 List Box Control (Forms)

List Box Control (Forms)

The list box control displays a list of values or alternatives. In many cases, it's quicker and easier to select a value from a list than to remember a value to type. A list of choices also helps ensure that the value that's entered in a field is correct.

Control: | Tool:

The list in a list box consists of rows of data. Rows can have one or more columns, which can appear with or without headings.

Note This control should not be confused with the Dynamic HTML list box control used on a data access page. For information about a list box control on a data access page, see List Box Control (Data Access Pages).

Remarks

If a multiple-column list box is bound, Microsoft Access stores the values from one of the columns.

You can use an unbound list box to store a value that you can use with another control. For example, you could use an unbound list box to limit the values in another list box or in a custom dialog box. You could also use an unbound list box to find a record based on the value you select in the list box.

If you don't have room on your form to display a list box, or if you want to be able to type new values as well as select values from a list, use a combo box instead of a list box.


 List Box Control (Data Access Pages)

List Box Control (Data Access Pages)

The list box control displays a list of values or alternatives. In many cases, it's quicker and easier to select a value from a list than to remember a value to type. A list of choices also helps ensure that the value that's entered in a field is correct.

Control: | Tool:
List box | List Box control

The list in a list box consists of rows of data. Rows can have one or more columns, which can appear with or without headings.

Remarks

If a multiple-column list box is bound, Microsoft Access stores the values from one of the columns.

You can use an unbound list box to store a value that you can use with another control. For example, you could use an unbound list box to limit the values in another list box or in a custom dialog box. You could also use an unbound list box to find a record based on the value you select in the list box.

If you don't have room on your form to display a list box, use a dropdown box instead of a list box.


 Movie Control

Movie Control

The movie control can add a video file (.avi or .mov) to a data access page.

Tool:
Movie control

Remarks

When this control is added to a data access page, the Video Browser dialog box is displayed to select the name of the movie file to be bound to this control.

You can specify whether you want the movie tobegin when the data access page is opened or when the mouse paases over the movie control.


 Office Chart Control

Office Chart Control

The Office chart control can add a chart to a data access page.

Tool:
Office Chart control

Remarks

You can use Microsoft Office Chart, a Microsoft Office Web Component, to create dynamic, interactive charts in a data access page that you can make available on Web sites for viewing in a browser. For example, you can create a chart using data in a table that stores sales figures. When you update the sales figures, the chart updates — so users can always see the latest information on their Web pages.

Microsoft Internet Explorer 5 or later is required to create a chart on a data access page, but users with Internet Explorer version 4.x or later can view the chart and see the chart updated in response to changes to data.


 Office Spreadsheet Control

Office Spreadsheet Control

The Office spreadsheet control can add a spreadsheet with some of the features of a Microsoft Excel spreadsheet to a data access page.

Tool:
Office Spreadsheet control

Remarks

You can add a spreadsheet control to a data access page to provide some of the same capabilities you have in a Microsoft Excel worksheet. You can enter values, add formulas, apply filters, and so on. Use the procedure below to create a spreadsheet in which you enter raw data, or import data from a Web page or text file. If within the spreadsheet you want to use data from other controls on the data access page, you need to refer to those controls in the appropriate spreadsheet cells.


 Option Button Control (Forms and Reports)

Option Button Control (Forms and Reports)

An option button on a form or report is a stand-alone control used to display a Yes/No value from an underlying record source

Control: | Tool:

Note This control should not be confused with the Dynamic HTML option button control used on a data access page. For information about a option button control on a data access page, see Option Button Control (Data Access Pages).

Remarks

When you select or clear an option button that's bound to a Yes/No field, Microsoft Access displays the value in the underlying table according to the field's Format property (Yes/No, True/False, or On/Off).

You can also use option buttons in an option group to display values to choose from.

It's also possible to use an unbound option button in a custom dialog box to accept user input.


 Option Button Control (Data Access Pages)

Option Button Control (Data Access Pages)

An option button on a data access page is a stand-alone control used to display a Yes/No value from an underlying record source

Control: | Tool:
Option button |

Remarks

When you select or clear an option button that's bound to a Yes/No field, Microsoft Access displays the value in the underlying table according to the field's Format property (Yes/No, True/False, or On/Off).

You can also use option buttons in an option group to display values to choose from.

It's also possible to use an unbound option button in a custom dialog box to accept user input.


 Option Group Control (Forms and Reports)

Option Group Control (Forms and Reports)

An option group on a form or report displays a limited set of alternatives. An option group makes selecting a value easy since you can just click the value you want. Only one option in an option group can be selected at a time.

An option group consists of a group frame and a set of check boxes, toggle buttons, or option buttons.

Control: | Tool:

Note This control should not be confused with the Dynamic HTML option group control used on a data access page. For information about a option group control on a data access page, see Option Group Control (Data Access Pages).

Remarks

If an option group is bound to a field, only the group frame itself is bound to the field, not the check boxes, toggle buttons, or option buttons inside the frame. Instead of setting the ControlSource property for each control in the option group, you set the OptionValue property of each check box, toggle button, or option button to a number that's meaningful for the field to which the group frame is bound. When you select an option in an option group, Microsoft Access sets the value of the field to which the option group is bound to the value of the selected option's OptionValue property.

Note The OptionValue property is set to a number because the value of an option group can only be a number, not text. Microsoft Access stores this number in the underlying table. In the preceding example, if you want to display the name of the shipper instead of a number in the Orders table, you can create a separate table called Shippers that stores shipper names, and then make the ShipVia field in the Orders table a Lookup field that looks up data in the Shippers table.

An option group can also be set to an expression, or it can be unbound. You can use an unbound option group in a custom dialog box to accept user input and then carry out an action based on that input.


 Option Group Control (Data Access Pages)

Option Group Control (Data Access Pages)

An option group on a data access page displays a limited set of alternatives. An option group makes selecting a value easy since you can just click the value you want. Only one option in an option group can be selected at a time.

An option group consists of a group frame and a set of check boxes, toggle buttons, or option buttons.

Control: | Tool:
Option group |

Remarks

If an option group is bound to a field, only the group frame itself is bound to the field, not the check boxes, toggle buttons, or option buttons inside the frame. Instead of setting the ControlSource property for each control in the option group, you set the Value property of each check box, toggle button, or option button to a number that's meaningful for the field to which the group frame is bound. When you select an option in an option group, Microsoft Access sets the value of the field to which the option group is bound to the value of the selected option's Value property.

Selected option in an option group

Note The Value property is set to a number because the value of an option group can only be a number, not text. Microsoft Access stores this number in the underlying table. In the preceding example, if you want to display the name of the shipper instead of a number in the Orders table, you can create a separate table called Shippers that stores shipper names, and then make the ShipVia field in the Orders table a Lookup field that looks up data in the Shippers table.

An option group can also be set to an expression, or it can be unbound. You can use an unbound option group in a custom dialog box to accept user input and then carry out an action based on that input.


 Page

Page

A Page object corresponds to an individual page on a tab control.

Each Page object can contain one or more controls, such as text boxes or option buttons. 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 Control collection.

With the tab control, you can construct a single form or dialog box that contains several different tabs, and you can group similar options or data on each tab's page. For example, you might use a tab control on an Employees form to separate general and personal information.

Control: | Tool:


 Page Break Control

Page Break Control

The page break control marks the start of a new screen or printed page on a form or report.

Control: | Tool:

Remarks

In a form, a page break is active only when you set the form's DefaultView property to Single Form. Page breaks don't affect a form's datasheet.

In Form view, press the PAGE UP or PAGE DOWN key to move to the previous or next page break.

Position page breaks above or below other controls. Placing a page break on the same line as another control splits that control's data.


Parameter Query

A parameter query, which is a type of select query, extends the flexibility of another query by prompting you to enter certain criteria each time the query is run. A parameter query is not, strictly speaking, a separate kind of query; rather, it extends the flexibility of other queries.


 Office PivotTable Control

Office PivotTable Control

The Office PivotTable control can add a pivot list to a data access page.

Tool:
Office Pivot List control

Create a PivotTable list on a data access page

What is a PivotTable form ?


 Record Navigation Control

Record Navigation Control

The record navigation control can add record navigation to a data access page.

Tool:
Record Navigation control

Remarks

The record navigation control can contain buttons for the following:

First record | Previous record | Next record
Last record | New record | Delete
Save record | Undo | Sort ascending
Sort descending | Filter by selection | Toggle filter


 Rectangle Control (Forms and Reports)

Rectangle Control (Forms and Reports)

The rectangle control displays a rectangle on a form or report.

Control: | Tool:

Note This control should not be confused with the Dynamic HTML rectangle control used on a data access page. For information about a rectangle control on a data access page, see Rectangle Control (Data Access Page).

Remarks

You can move a rectangle and the controls in it as a single unit by dragging the mouse pointer diagonally across the entire rectangle to select all of the controls. The entire selection can then be moved to a new position.


 Rectangle Control (Data Access Pages)

Rectangle Control (Data Access Pages)

The rectangle control displays a rectangle on a data access page.

Control: | Tool:
Rectangle | Rectangle control

Remarks

You can move a rectangle and the controls in it as a single unit by dragging the mouse pointer diagonally across the entire rectangle to select all of the controls. The entire selection can then be moved to a new position.


 Scrolling Text Control

Scrolling Text Control

The scrolling text control can add animated text to a data access page.

Tool:
Scroll Text control

Remarks

You use a scrolling text control, often called a marquee, on a data access page to display moving text or text that scrolls. Scrolling text draws attention to a line of text, such as a headline or an important announcement. You display text that is contained in a field of your database by binding the scrolling text control to the field. You can customize scrolling text by setting options such as direction of travel, speed, and type of motion.

Some Web browsers cannot display scrolling text. In these cases, a normal line of text will be displayed in the control.


Select Query

A select query asks questions about the data stored in your database and returns the result of the query without changing the data. Once the result set is displayed, you can view and, in some cases, change the data in the underlying tables. In contrast, an action query does make changes to your data.


SQL-Specific Query

An SQL-specific query is one that can be created only by writing an SQL statement in SQL view. Union, pass-through, and data-definition queries are SQL-specific queries.

SQL-specific query type | Description
Union | An SQL-specific select query that combines corresponding fields from two or more tables or queries into one field. For example, a union query of the Customers table and the Suppliers table results in a snapshot that contains all the specified records from both the Customers table and the Suppliers table.
Pass-through | An SQL-specific query that sends commands directly to an SQL database server (such as Microsoft SQL Server). With pass-through queries, you work with the tables on the server instead of linking the tables to your Microsoft Access database.
Data-definition | An SQL-specific query that can create or delete an index, or create, alter, or delete a table.


 Tab Control

Tab Control

A tab control contains multiple pages on which you can place other controls, such as text boxes or option buttons. When a user clicks the corresponding tab, that page becomes active.

With the tab control, you can construct a single form or dialog box that contains several different tabs, and you can group similar options or data on each tab's page. For example, you might use a tab control on an Employees form to separate general and personal information.

Control: | Tool:


 Text Box Control (Forms and Reports)

Text Box Control (Forms and Reports)

Text boxes on a form or report display data from a record source. This type of text box is called a bound text box because it's bound to data in a field. Text boxes can also be unbound. For example, you can create an unbound text box to display the results of a calculation, or to accept input from a user. Data in an unbound text box isn't saved with the database.

Control: | Tool:

Note This control should not be confused with the Dynamic HTML text box control used on a data access page. For information about a text box control on a data access page, see Text Box Control (Data Access Pages).


 Text Box Control (Data Access Pages)

Text Box Control (Data Access Pages)

Text boxes on a data access page display data from a record source. This type of text box is called a bound text box because it's bound to data in a field. Text boxes can also be unbound. For example, you can create an unbound text box to display the results of a calculation, or to accept input from a user. Data in an unbound text box isn't saved with the database.

Control: | Tool:
Text box | Text Box control


 Toggle Button Control

Toggle Button Control

A toggle button on a form is a stand-alone control used to display a Yes/No value from an underlying record source.

Control: | Tool:

Remarks

When you click a toggle button that's bound to a Yes/No field, Microsoft Access displays the value in the underlying table according to the field's Format property (Yes/No, True/False, or On/Off).

Toggle buttons are most useful when used in an option group with other buttons.

You can also use a toggle button in a custom dialog box to accept user input.


 Unbound Object Frame Control

Unbound Object Frame Control

The unbound object frame control displays a picture, chart, or any OLE object not stored in a table. For example, you can use an unbound object frame to display a chart that you created and stored in Microsoft Graph.

Control: | Tool:

Remarks

This control allows you to create or edit the object from within a Microsoft Access form or report by using the application in which the object was originally created.

To display objects that are stored in a Microsoft Access database, use a bound object frame control.

The object in an unbound object frame is the same for every record.

The unbound object frame can display linked or embedded objects.

Tip You can use the unbound object frame or an image control to display unbound pictures in a form or report. The advantage of using the unbound object frame is that you can edit the object directly from the form or report. The advantage of using the image control is that it's faster to display.


 About command-line options

About command-line options

You can automatically open a database, run a macro, supply a user account name or password, and other options when you start Microsoft Access by specifying options on the command line.

You can specify command-line options either for Microsoft Access on the Windows Start menu or for a shortcut. If you specify command-line options for the Windows Start menu, Microsoft Access will start with those options when you use the Start menu. If you specify command-line options for a shortcut, Microsoft Access will start with these options when you use this shortcut. To create alternative ways to start Microsoft Access, you can create multiple shortcuts and put them on your desktop or in a folder, or add them to the Windows Start menu. Search Windows Help for "shortcuts" for more information.

Return to Start Microsoft Access with command-line options


About creating a database

Microsoft Access provides two methods to create a database. You can create a blank database and then add the tables, forms, reports, and other objects later — this is the most flexible method, but it requires you to define each database element separately. Or you can use a Database Wizard to create in one operation the required tables, forms, and reports for the type of database you choose — this is the easiest way to start creating your database. Either way, you can modify and extend your database at any time after it has been created.

Return to Create a database


About sorting records in a table, query, or form

When you specify a sort order in Form view or Datasheet view, you can perform simple sorts, which means you can sort all records in ascending or descending order (not both). When you specify a sort order in query Design view or in the Advanced Filter/Sort window, you can perform complex sorts. This means you can sort records in ascending order by some fields and in descending order by others.

Regardless of where you specify the sort order, Microsoft Access saves the sort order when you save the form or datasheet, and reapplies it automatically when you reopen the object or base a new form or report on that object.

Return to Sort records in a table, query, or form.


Use built-in drivers, ODBC drivers, and ODBC data sources

What do you want to do?

Learn more about differences between ODBC drivers and built-in drivers for external data

Learn more about ODBC data sources

Set up ODBC data sources


 Open a report snapshot

Open a report snapshot

  1. Start Windows Explorer.

  2. Locate the folder that contains the report snapshot.

  3. Double-click the report snapshot icon.

More information about opening a report snapshot.


Work with report snapshots and the Snapshot Viewer

What do you want to do?

Learn about report snapshots and Snapshot Viewer

Create a report snapshot

Create a report snapshot by using the OutputTo action and publish it to the Web

Send a report snapshot in e-mail by using the SendObject action


Add a bound object to a form or report

What do you want to do?

Create and insert an object

Insert an existing object

Insert part of an existing object

Create a link on a form to an existing object

Link to part of an existing object

See examples of when to use unbound, bound, inserted, and linked objects

Not sure which choice you want?


Add or manipulate fields

What do you want to do?

Add fields to the design grid in a query

Move a field in the design grid in a query

Remove a field from the design grid in a query

Insert a field in the design grid of a query

Show or hide a field in a query's results

Change a field name

Set properties for a query, its fields, or its field lists

Learn about using the asterisk in the query design grid

Perform calculations or manipulate field values using a query


Add, remove, or format a form header, page header, or other section

What do you want to do?

Add or remove a form header and footer or a page header and footer

Change the size of a header, footer, or other section on a form or report

Format a form, report, section, or selected controls using predefined formats


Add, remove, or format a report header, page header, or other section

What do you want to do?

Add or remove a report header and footer or a page header and footer

Change the size of a header, footer, or other section on a form or report

Format a form, report, section, or selected controls using predefined formats


Add, remove, or format a header, footer, or other section on a data access page

What do you want to do?

Add an unbound section to a data access page that doesn't have one

Add a group header

Merge two group headers

Add or remove a group footer

Add or remove a group's caption section

Add or remove a group's navigation section

Change the size of a header, footer, or other section

Use a theme to format a data access page


Add an unbound object to a form or report

What do you want to do?

Create and insert an object

Insert an existing object

Insert part of an existing object

Link to an existing object

Link to part of an existing object

See examples of when to use unbound, bound, inserted, and linked objects

Not sure which choice you want?


 About adding an unbound picture to a form, report, or data access page

About adding an unbound picture to a form, report, or data access page

Adding a picture to a form, report, or data access page differs depending on how you want to use the picture and on whether you're working in a form, report, or data access page.

This topic provides reference information about:

Forms and reports

Data access pages

Forms and reports

How you add an unbound picture depends on whether you want it to appear as a background picture (watermark) that covers the entire window, or a picture that appears in a control. If you want to add a background picture, you use the Picture property of the form or report. If you want to add a picture that appears in a control, you use an image control or an unbound object frame.

Whether you use an image control or an unbound object frame depends on whether you want to be able to edit the picture directly from the form or report. If you won't need to update the picture, you can add the picture by using an image control. If you will need to update the picture, you can add the picture by using an unbound object frame. Then if you want to edit the picture, you can double-click the object from the form or report to open the application that you used to create the object. For most unbound pictures, you'll probably want to use an image control, because image controls load much faster than unbound object frames.

You can insert pictures in a form or report or you can link to them. When you insert a picture in a form or report, Microsoft Access stores the picture in your database file. An inserted object is always available. If you modify the picture from your form or report, the picture is changed in your database.

When you link to a picture, you can look at the picture and make changes to it from your form or report, but the changes are stored in the original object file, not in your database file. You can also modify the object file separately; in which case, the latest changes will appear the next time you open the form or report. Linking to a picture is useful for large files that you don't want to include in your database file, and for files that you want to use in several forms and reports; but if a linked object file is moved, you have to reconnect the link.

Return to top

Data access pages

How you add an unbound picture to a data access page depends on whether you want it to appear as a background picture (watermark) that covers the entire page, or a picture that appears in a control. If you want to add a background picture to a data access page, you can insert the picture by using options on the Format menu. If you want to add a picture that appears in a control, then you use the image control.

After you add a picture to a data access page, you won't be able to edit it. When you insert a picture in a data access page, the picture is added to the supporting files that accompany the data access pages; the picture is not stored in the data access page. So if you want to move a data access page to a new location, do not copy the data access page. Instead, save the data access page to the new location; the picture is automatically saved with it.

Return to top

Return to Add an unbound picture


Analyze or maintain your Access database

What do you want to do?

Create a switchboard form by using the Switchboard Manager

Change a switchboard form created by the Database Wizard

Control how a Microsoft Access database or application starts

Import or link data

Split a table into related tables using the Table Analyzer Wizard

View or print the design characteristics of database objects

Optimize database performance using the Performance Analyzer

Compact a database to defragment the file and free disk space

Compact a database automatically when you close it

Create a replica of your database


Calculate a sum, average, count, or other total on records in a query

What do you want to do?

Calculate totals on all the records in a query

Calculate totals on groups of records in a query

Learn more about the types of totals calculations and when to use them

Not sure which choice you want?


 Change a field name in a query

Change a field name in a query

You can rename a field in a query to describe the field's data more accurately. This is particularly useful when you define a new calculated field or calculate a sum, count, or another type of total on an existing field. In such cases, unless you enter a name, Microsoft Access assigns names such as Expr1 or SumOfOrder Amount. The new field name must follow object-naming rules.

What do you want to do?

Display new field names by changing them in the design grid

Display new field names by changing the Caption property

Not sure which choice you want?


Create and manage a switchboard form

When you use the Database Wizard to create a database, Microsoft Access automatically creates a switchboard that helps you to navigate around the database. This switchboard has buttons that you can click to open forms and reports (or open other switchboards that open additional forms and reports), quit Microsoft Access, or customize the switchboard. You can create a switchboard similar to the one that the Database Wizard creates by using the Switchboard Manager.

What do you want to do?

Create a switchboard form by using the Switchboard Manager

Create a new switchboard that you can open from the opening switchboard

Make a change to an existing switchboard

Change which switchboard is automatically displayed when you open the database

Delete a switchboard


Compute totals, perform other calculations, or manipulate field values

What do you want to do?

Perform calculations or manipulate field values using a query

Learn about working with blank fields in queries

Create a crosstab query without using a wizard

See an example of a crosstab query


Convert a secured database from a previous version of Microsoft Access

What do you want to do?

Learn about converting a secured database from a previous version of Microsoft Access

Convert a Microsoft Access version 2.0 secured database when all users are upgrading to Microsoft Access 2000

Convert a Microsoft Access 95 or 97 secured database when all users are upgrading to Microsoft Access 2000

Learn about how to share a secured database from a previous version of Microsoft Access across several versions of Microsoft Access

Convert a workgroup information file from a previous version of Microsoft Access


Copy or move items

This topic contains hyperlinks to the following subjects:

Copy or move data

Copy and paste multiple items

Copy or move an Access data file, database object, or other item

Copy or move data

Copy or move data from one field to another

Copy or move data from multiple fields in Datasheet view

Copy or move records to a datasheet

Copy or move records to a form

Copy or move records from Microsoft Access to another application

Copy or move records from another application to Microsoft Access

Return to top

Copy and paste multiple items

Learn about collecting and pasting multiple items

Collect and paste multiple items

Clear all items from the Office Clipboard

View the contents of the Office Clipboard

Paste specific items from the Office Clipboard

Return to top

Copy or move an Access data file, database object, or other item

Copy or move a Microsoft Access database or Microsoft Access project

Copy or move a field, a control, text, a macro action, or another item

Learn about copying database objects

Use the Copy command to copy a database object

Use the Save As command to copy a database object

Return to top


Create user or group accounts and grant permissions

Work with user and group accounts

Work with permissions


Create an action query

What do you want to do?

Create a make-table query

Create a delete query

Create an append query

Create an update query

Not sure which choice you want?


Create a chart in a form or report

In most cases, you use the Chart Wizard to create a chart. Based on the data you specify, The Chart Wizard will determine whether it should display data from all fields in one global chart, or whether it is more appropriate to show a record-bound chart, so that when you move from record to record you see a chart that represents only the data in the current record. However, if the Chart Wizard creates one global chart, and you want a record-bound chart, you can link the chart to a specific record.

To use the Chart Wizard, you must have Microsoft Graph 2000 installed. You can also create a chart by adding an existing chart from an external file.

What do you want to do?

Add a new chart to a form or report

Link an existing chart in a form or report to a specific record

Add an existing chart to a form or report

Learn about charts in forms, reports, and data access pages


Create custom Help for a form, report, or control

What do you want to do?

Create a custom ToolTip (ScreenTip) for a toolbar button

Create What's This tips for toolbar buttons or menu commands

Create a tip for a control on a form

Add status bar text for a control or form

Create topics that are displayed when you click the What's This button on a form

Add the What's This button to a form

Create a compiled Help file that displays Help for a form, report, or control when you press F1

Not sure which choice you want?


Create a form on your own

You can use the steps in this topic to guide you through creating a form from start to finish. You'll use many of the steps to create every form. The others you'll use when you create a particular kind of form — for example, one that displays data from more than one table. You need to use only the steps that are relevant to the type of form that you're creating. For other tasks related to creating forms, ask the Answer Wizard.

See examples of what forms are and how they work

  1. Start your form

    Create a blank form and select a record source

    See examples of the kinds of tools you can work with when designing a form

  2. Add headers and footers

    See how you can use sections on a form

    Add or remove a form header and footer or a page header and footer

    Change the size of a header, footer, or other section

  3. Display data, text, and totals on the form

    See how you display data, text, and totals in text boxes, labels, and other controls

    Display data from the underlying table or query in a text box

    Display a title or other informational text in a label

    Calculate a total for one record in a text box

    Display a list of values that you can select from in a list box

    Automate a task, such as opening another form, by adding a command button

    Get more information about labels, text boxes, and other controls

  4. Format, move, size, and align labels, text boxes, and other controls

    Make the text in a label, text box, or other control bold, italic, or underlined

    Change the font, font size, and line weight for all text and lines on the form at once

    Move a text box or other control and its label

    Size a field

    Align labels, text boxes, and other controls to each other

  5. Display records from a related table in a subform

    See examples of subforms and how they work

    Create a subform

  6. Make final adjustments

    Check the form's design by looking at it in Form view or Datasheet view


 About creating a list box, drop-down list box, or combo box that looks up values

About creating a list box, drop-down list box, or combo box that looks up values

To create a list box, drop-down list box, or combo box that looks up values, you need to decide two things:

  • Where will the rows for the list come from?

  • When a user selects an item in the list box, drop-down list box, or combo box, what will Microsoft Access do with that value?

The rows for a list box, drop-down list box, or combo box can come from a fixed list of values that you enter when you create the list box, drop-down list box, or combo box (use when the list won't change very often), or they can come from a record source (use when you'll frequently update the list). For example, you could use a fixed list for a list box that contains entries for Mr., Mrs., or Ms. If, on the other hand, you have a Products form and you want to display a list of product suppliers in a list box, but the list will change frequently, base the list box on a record source. The list box looks up values in the Suppliers table and displays an up-to-date list of the suppliers that you can choose from.

List box displaying values from Suppliers table

When a user selects a value in a list box, drop-down list box, or combo box, Microsoft Access can do one of two things: Access can store the selected value in a table (not the same table that the list gets its rows from), or Access can pass the value to another control. For example, for the Supplier list box, if a user selects "Pavlova, Ltd." in the preceding illustration, Access looks up the primary key value (SupplierID) for Pavlova, Ltd. in the Suppliers table and sets the SupplierID field (the foreign key) for the current record in the Products table to the same value. This is the value that is stored. Because Access is storing a value based on a selection in the list box, the list box is bound. (Note that the SupplierName value that comes from the Suppliers table is displayed in the list box but not stored.)

If, on the other hand, you want Access to use the value selected in the list box, drop-down list box, or combo box to determine the contents of another control or controls, you would create an unbound list box, drop-down list box, or combo box. For example, you might want to create a list box or drop-down list box that you can use to find a related record on a data access page. Or you might want to create a list box or combo box that you use to filter the records in another list box or combo box on a form.

More information

Create bound and unbound combo boxes, drop-down list boxes, and list boxes


Create or view data access pages

What do you want to do?

Read an overview of what data access pages are and how they work

Read about strategies for creating data access pages

Create a data access page

Open a page in Page view or Internet Explorer

Publish a data access page to Web Folders or any Web server

Troubleshoot designing data access pages


Create, modify, or view the results of a query

What do you want to do?

See an overview of what queries are and how they work

Create a query

Open or run a query

Customize a query

Design or modify a query


Create, modify, or print reports

What do you want to do?

See an overview of what reports are and how they work

Create a report

Open a report

Customize a report

Preview a report

Print a report


Create a form based on more than one table

What do you want to do?

Use a Form Wizard to create a flat form, a form with one or more subforms, or a form that's synchronized with another form

Add a subform to an existing form

Synchronize the records on two existing forms

Create a form on my own and use a query as the data source for that form

Not sure which choice you want?


Create or modify macros

What do you want to do?

See an overview of what macros are and how they work

Create a macro

Create a macro group


Create or modify procedures in modules

What do you want to do?

See an overview of what modules are and how they work

Learn about procedures


Create or modify relationships

What do you want to do?

Learn about relationships in a database

Define relationships between tables

View existing relationships

Manage relationships by using the keyboard


Create a report on your own

You can use the steps in this topic to guide you through creating a report from start to finish. You'll use many of the steps to create every report. The others you'll use when you create a particular kind of report — for example, one that requires grouping records by categories or calculating totals. You need to use only the steps that are relevant to the type of report that you're creating. For other tasks related to creating reports, ask the Answer Wizard.

See examples of what reports are and how they work

  1. Start your report

    Create a blank report and select a record source

    See examples of the kinds of tools you can work with when designing a report

  2. Sort or group the data in your report

    See an example of grouped records on a report

    Sort records

    Group records

    Change the sorting or grouping order

  3. Add headers and footers

    See how you can use sections on a report

    Add a report header and footer or a page header and footer

    Change the size of a header, footer, or other section

  4. Display data, text, and totals on the report

    See how you display data, text, and totals in text boxes, labels, and other controls

    Display data from the underlying table or query in a text box

    Display a title or other informational text in a label

    Calculate a total for one record in a text box

    Calculate a total for a group of records or all records in a text box

    Display the current date in a text box

    Display the page number in a text box

    Get more information about text boxes, labels, and other controls

  5. Format, move, size, and align labels, text boxes, and other controls

    Make the text in a label, text box, or other control bold, italic, or underlined

    Change the font, font size, and line weight for all text, data, and lines on the report at once

    Move a text box or other control and its label

    Change the size of a label, text box, or other control

    Align labels, text boxes, and other controls to each other

  6. Preview or print the report

    Set margins and page orientation

    Preview the report

    Print the report


Create an SQL query

What do you want to do?

Learn more about SQL queries

Create a union query

Create a pass-through query

Create a data-definition query

Create a subquery


Create your first procedure

What do you want to do?

Create a custom Function procedure

Create a custom Sub procedure

Create an event procedure

Specify arguments when you use a procedure, statement, or method in Visual Basic code


Create or change passwords

What do you want to do?

Learn about creating or changing passwords

Learn about linking tables from a password-protected database

Set a database password

Remove a database password

Create or change a user-level security account password

Clear a user-level security account password

Protect Visual Basic for Applications (VBA) code with a password


 Create a new table from existing data

Create a new table from existing data

Microsoft Access provides two ways to create a table from existing data:

  • You can import or link data from another Microsoft Access database or data in a variety of file formats from other programs.

  • You can perform a make-table query to create a table based on data in a current table. For example, you can use make-table queries to archive old records, to make backup copies of your tables, to select a group of records to export to another database, or to use as a basis for reports that display data from a specific time.

What do you want to do?

Create a table by importing or linking data

Create a new table using a make-table query


Customize a Find Duplicates query

What do you want to do?

Add fields

Remove fields

Sort the records

Note You can't convert a Find Duplicates query to a delete query to delete duplicate records. This is because the Find Duplicates query returns the original record and any duplicates of the record so that you can choose which version to delete. Therefore, if you convert it to a delete query, it will delete the original and the duplicates.

There is a way, however, to automatically delete duplicate records while retaining the originals. For more information, click [image] .


Customize a Find Unmatched query

What do you want to do?

Add fields

Remove fields

Move fields


Debug macros

What do you want to do?

Find problems in a macro by single stepping through it

Troubleshoot macros


Debug Visual Basic code

What do you want to do?

Read about resolving errors

Use a breakpoint to suspend execution of Visual Basic code

Step through Visual Basic code

Examine the values of expressions and variables

Set a watch expression in Visual Basic code

Trace Visual Basic procedure calls while debugging Visual Basic code

Use the Immediate pane while working with Microsoft Visual Basic


Should I use a data display format or an input mask?

Microsoft Access provides two field properties that produce similar results: the Format property and the InputMask property.

Use the Format property to display data in a consistent format. For example, if you set the Format property for a Date/Time field to Medium Date format, all dates entered will display in this form: 12-Jan-96. If a user of your database enters a date in the form, 01/12/96 (or any other valid date format), Microsoft Access will convert the display to the Medium Date format when the record is saved.

The Format property affects only how a value is displayed, not how it is stored in the table. Also, a display format isn't applied until the data entered is saved — nothing is displayed in the field to suggest or control the format in which data is entered. If you need to control how data is entered, use an input mask in addition to, or instead of, a data display format. If you want data to display exactly as entered, don't set the Format property.

Predefined display formats are available for Number, Currency, Date/Time, AutoNumber, and Yes/No fields, and you can define custom formats for them as well. There are no predefined formats for Text, Memo, or Hyperlink fields, but you can define custom formats. You can't define a display format for OLE Object fields.

Use the InputMask property to display literal display characters in the field with blanks to fill in. For example, if all phone numbers you enter in a field have the same format, you can create an input mask as shown in the following illustration.

Input masks provide blanks to fill in

An input mask ensures that the data will fit in the format you define, and you can specify the kind of values that can be entered in each blank. For example, the preceding input mask requires that all entries contain exactly enough digits to make up a U.S. area code and telephone number, and that only digits be entered in each blank.

If you define both a display format and an input mask for a field, Microsoft Access uses the input mask when you are adding or editing data, and the Format setting determines how the data is displayed when the record is saved. When using both Format and InputMask properties, be careful that their results don't conflict with each other.

More information

Use the Format property to set display formats

Use the InputMask property to control how data is entered


Edit a chart in a form or report

What do you want to do?

Learn about making changes to a chart in a form or report

Change the size of a chart in a form or report

Change the appearance of the chart in a form or report

Change the data in the underlying table or other record source in a form or report

Change the query in the RowSource property in a form or report

Re-create the chart by using the Chart Wizard in a form or report

Customize a chart in a form or report


 Use shortcut keys to edit text or data

Use shortcut keys to edit text or data

Note If the insertion point isn't visible, press F2 to display it.

Press | Moving the insertion point in a field
RIGHT ARROW | To move it one character to the right
CTRL+RIGHT ARROW | To move it one word to the right
LEFT ARROW | To move it one character to the left
CTRL+LEFT ARROW | To move it one word to the left
END | To move it to the end of the field, in single-line fields
CTRL+END | To move it to the end of the field, in multiple-line fields
HOME | To move it to the beginning of the field, in single-line fields
CTRL+HOME | To move it to the beginning of the field, in multiple-line fields

Press | Copying, moving, or deleting text
CTRL+C | To copy the selection to the Clipboard
CTRL+X | To cut the selection and copy it to the Clipboard
CTRL+V | To paste the contents of the Clipboard at the insertion point
BACKSPACE | To delete the selection or the character to the left of the insertion point
DELETE | To delete the selection or the character to the right of the insertion point
CTRL+DELETE | To delete all characters to the right of the insertion point

Press | Undoing changes
CTRL+Z or ALT+BACKSPACE | To undo typing
ESC | To undo changes in the current field or current record; if both have been changed, press ESC twice to undo changes, first in the current field and then in the current record

Press | Entering data in Datasheet or Form view
CTRL+SEMICOLON (;) | To insert the current date
CTRL+COLON (:) | To insert the current time
CTRL+ALT+SPACEBAR | To insert the default value for a field
CTRL+APOSTROPHE (') | To insert the value from the same field in the previous record
CTRL+PLUS SIGN (+) | To add a new record
CTRL+MINUS SIGN (-) | To delete the current record
SHIFT+ENTER | To save changes to the current record
SPACEBAR | To switch between the values in a check box or option button
CTRL+ENTER | To insert a new line

Press | Refreshing fields with current data
F9 | To recalculate the fields in the window
SHIFT+F9 | To requery the underlying tables; in a subform, this requeries the underlying table for the subform only
F9 | Refresh the contents of a Lookup field list box or combo box


Export data or database objects to another database or file format

What do you want to do?

Learn about exporting

Learn about exporting data and database objects to another database or file format

Summary of data formats you can export to

Export or mail database objects

Export database objects to a Microsoft Access database or Microsoft Access project

Send a database object as an attachment to an electronic mail message

Send a data access page as the body of an electronic mail message

Export to an external file or database

Export a table or query to a Paradox or dBASE file

Export a table or query to an SQL database table or other ODBC data source

Export a datasheet to a delimited or fixed-width text file

Learn about import/export specifications and schema.ini files

Export to a Web page

Learn about the three types of Web pages Microsoft Access creates

Learn about Web page client/server products and platforms

Create a data access page

Export a datasheet to static HTML format

Export a datasheet to server-generated HTML format

Export a report to static HTML format

Publish Web pages

Export to Microsoft Excel from a data access page

Export a PivotTable list on a page to a Microsoft Excel PivotTable report

Export a spreadsheet on a page to a Microsoft Excel workbook

Export to or exchange data with Microsoft Word

Merge data from a datasheet by using the Microsoft Word Mail Merge Wizard

Export a datasheet to a Microsoft Word mail merge data source file

Save a database object's output as a Rich Text Format file

Load the output of a datasheet, form, or report into Microsoft Word

Export to Microsoft Excel or other spreadsheet

Export a datasheet to a spreadsheet file

Save the output of a datasheet, form, or report as a Microsoft Excel file

Load the output of a datasheet, form, or report into Microsoft Excel

Automate exporting

Use macros or Visual Basic code to automate exporting data


Find or replace data

What do you want to do?

Learn more about finding or replacing data

Find a record by scrolling in a datasheet or form

Find a record by its record number

Use the Find dialog box

Use the Replace dialog box

Use a filter in a Microsoft Access database

Use a query in a Microsoft Access database

Use a filter in a Microsoft Access project

Use a query in a Microsoft Access project

Optimize find and replace performance


Get Help in the Visual Basic Editor

What do you want to do?

Get Help on Visual Basic

Copy Visual Basic code examples from Help to the Code window


 Group records by each value in a grouping field on a data access page

Group records by each value in a grouping field on a data access page

Learn about grouping records on a data access page.

  1. Open the data access page in Design view.

  2. If the fields you want to display aren't in the section already, either add the fields to the page as bound HTML controls, or add the fields as bound text boxes.

    Notes

    • The page will load faster in Page view and in Microsoft Internet Explorer if you use bound HTML controls.

    • If there is no section on the page, you can add an unbound section.
  3. Make sure the control you want to group on is selected.

  4. Do one of the following:
    • To group on one field from a table or query, click Promote [image] on the toolbar.

    • To group on a table or query, click Group By Table [image] on the toolbar.

    Microsoft Access adds a group header that contains an expand control and a record navigation section that contains a record navigation control. If you grouped on one field, Access moves the control you grouped on to the group header. If you grouped on a table or query, Access moves all the controls, including controls bound to fields that are in that table or query and controls bound to Lookup fields to the group header.

  5. Repeat steps 3 and 4 until you have as many group levels as you need.

Notes

  • Use the Promote button when you want to group on a control that contains values shared by many records. For example, in the Orders table, group on ShipCountry. If you add other controls to the group header, Microsoft Access groups on every control in the group header. For example, if you add a control bound to the ShipRegion field to the Orders-ShipCountry header, Access uses the values in both the ShipCountry and ShipRegion controls to group the records.

  • Use the Group By Table button when the page contains fields from two tables or queries that have a one-to-many relationship and you want to group on the table or query on the one side of the relationship. For example, in a page that contains fields from the Orders and Order Details tables, group on the Orders table. When you use Group By Table to group records, Access groups and sorts records using the table's primary key — in this case, OrderID.

  • When you group on a control, Access creates an alias for the control by adding the prefix "GroupOf" to the control's name in the ControlSource property; for example, GroupOfShippedDate: ShippedDate. When you refer to this control in an expression or in a property, you must use the alias.

  • You can specify a different default sort order for each group level.

  • When you have two or more group levels on a page, you will be able only to view data in Page view or in Internet Explorer. You won't be able to add, edit, or delete data.


 About renaming a field

About renaming a field

Changing a field name in the query design grid changes the column heading in query Datasheet view. In addition, if you create a new object, such as a new form, report, or data access page, based on the query, the new object uses the new field name. For example, if you create a control to display the renamed field, the new field name will be used for the control name and its label caption. The field name in the underlying table doesn't change, however, nor does it change in forms and reports that were based on the query before you changed the field name.

Note Changing a field's name in the current query's design grid has no effect in the query's Datasheet view if the Caption property for that field has been set in the underlying table or query.

If you want the new field name to be used only for datasheet columns, or label captions in forms, reports, and data access pages, you can set the Caption property for the field instead of renaming the field in the design grid.

Return to Change a field name in a query


About preventing duplicate records

Microsoft Access considers a record to be unique as long as the value in any field in a record differs from the value in the same field in any other record. In a query, you aren't necessarily displaying all the fields that make up the records in the underlying tables or queries. Therefore, if the field that distinguishes one record from another isn't in the query design grid, the query's results can appear to include duplicate records. For example, if you add just the LastName field and Country field to the query design grid, it might appear that you have duplicate records when several employees have the same last name and live in the same country. The records are not duplicates in the underlying table, however, because the EmployeeID is unique for each record.

You can display unique records as determined by all the fields in the underlying table or query, not just those fields in the query design grid, or you can display unique records as determined by just the fields in the query design grid. With either setting, if there are duplicates, the query displays one instance of the record but not the duplicates.

Return to Prevent duplicate records from displaying in query results


Add an unbound picture to a form, report, or data access page

What do you want to do?

See examples of when to use unbound, bound, inserted, and linked objects in forms and reports

Adding background pictures

Add a background picture to a form

Add a background picture to a report

Add a background picture to a data access page

Adding pictures in controls

Add a picture by using an image control in a form, report, or data access page

Create and insert a picture by using an unbound object frame on a form or report

Insert an existing picture by using an unbound object frame on a form or report

Insert part of an existing picture by using an unbound object frame on a form or report

Linking to pictures

Link to an existing picture by using an unbound object frame on a form or report

Link to part of an existing picture by using an unbound object frame on a form or report

Not sure which choice you want?


 About having Access create a query for you

About having Access create a query for you

Microsoft Access can often create a query for you so you don't have to design one from scratch.

  • To create a query to use as the basis of a form, report, or data access page, try the form, report, or data access page wizards. They create the form, report or data access page, and if it's based on more than one table, they also create its underlying SQL statement. If you want, you can save the SQL statement as a query.

  • To easily create queries that you want to run independently or base multiple forms, reports, and data access pages on, try one of the query wizards. Query wizards do all the basic work for you after you provide answers to a series of questions. Even if you've created many queries, you may want to use a wizard to quickly design the query. Then you can switch to Design view to customize it.

  • To create queries from filters you created using Filter By Form, Filter By Selection, or Filter For Input, save the filter as a query.

If none of these methods satisfies your needs, you can create the query from scratch in query Design view.

Return to Create a query


Import or link data and import database objects

What do you want to do?

Learn about importing and linking

Learn about importing and linking data and importing database objects

Get more information to help decide whether to import or link tables

Summary of data sources Microsoft Access can import or link to

Import database objects

Import or link tables from another Microsoft Access database or Microsoft Access project

Import database objects from another Microsoft Access database or Microsoft Access project

Import or link data from HTML files or Web components

Import or link (read-only) HTML tables and lists

Import or link (read-only) data on an FTP or HTTP Internet server

Import a Web page or text file into a spreadsheet on a data access page

Import or link data from other programs or file formats

Learn about the Import Errors table

Import or link dBASE files

Import or link Paradox tables

Import or link SQL database tables or data from other ODBC data sources

Import or link data from Microsoft Outlook or Microsoft Exchange Server

Import or link data from a spreadsheet

Import or link a delimited or fixed-width text file

Learn about import/export specifications and Schema.ini files

Import a Microsoft Works database

Manage linked tables

Use the MSysConf table in a Microsoft Access database with linked SQL databases

Delete the link to a linked table in a Microsoft Access database

View, refresh, or change the file name and path for linked tables in a Microsoft Access database

Rename and set properties for linked tables in a Microsoft Access database

Obtain optimal performance with linked tables in a Microsoft Access database

Automate importing

Automate importing data using a macro or Visual Basic code


Make text or a control hidden or disabled on a data access page

What do you want to do?

Disable a control or make data in a text box or other control read-only

Show or hide a text box or other control


 Modify a filter in the Advanced Filter/Sort window

Modify a filter in the Advanced Filter/Sort window

While you're working in the Advanced Filter/Sort window in a table, query, or form, you can modify the filter's design and change the design grid.

What do you want to do in the design grid?

Add a field

Insert a field between other fields

Move a field

Add a column

Remove a field or column

Change column widths

Insert or delete a criteria row

Enter criteria

Specify a sort order for the filtered records

Clear the design grid


Modify a filter in the Filter By Form window in a table, query, or form

You can modify the filter by adding to blank fields other values you want the filtered records to contain, deleting or changing values in a field, or making any of the following modifications.

How do you want to modify the filter?

Clear all the fields in the Filter By Form window

Delete an Or tab at the bottom of the Filter By Form window

Enter an expression


 Move, size, align, and format text boxes or controls in a form or report

Move, size, align, and format text boxes or controls in a form or report

In forms and reports, you use text boxes and other controls to display data from fields, include descriptive text, and add decorative lines.

What do you want to do?

Move a control and its label

Move a control or its label separately

Move two or more controls at the same time

Move a control in front of or behind other controls

Size a control

Size a control to fit its contents

Size controls uniformly relative to each other

Size controls uniformly using the grid

Align controls to each other

Align controls using the grid

Space controls evenly

Increase or decrease space between controls

Change the alignment of text in a control

Change the format of data in a control

Group controls

Format a form, report, section, or selected controls using predefined formats


Move, size, align, and format text or controls on a data access page

What do you want to do?

Make the text in a label, text box, or other control bold, italic, or underlined

Move a text box or other control and its label

Change the size of a label, text box, or other control

Align text boxes and other controls

Customize a record navigation control


 Use shortcut keys to navigate in Datasheet view

Use shortcut keys to navigate in Datasheet view

Press | Going to a specific record
F5 | To move to the record number box; then type the record number and press ENTER

Press | Navigating between fields and records
TAB or RIGHT ARROW | To move to the next field
END | To move to the last field in the current record, in Navigation mode
SHIFT+TAB, or LEFT ARROW | To move to the previous field
HOME | To move to the first field in the current record, in Navigation mode
DOWN ARROW | To move to the current field in the next record
CTRL+DOWN ARROW | To move to the current field in the last record, in Navigation mode
CTRL+END | To move to the last field in the last record, in Navigation mode
UP ARROW | To move to the current field in the previous record
CTRL+UP ARROW | To move to the current field in the first record, in Navigation mode
CTRL+HOME | To move to the first field in the first record, in Navigation mode

Press | Navigating to another screen of data
PAGE DOWN | To go down one screen
PAGE UP | To go up one screen
CTRL+PAGE DOWN | To go right one screen
CTRL+PAGE UP | To go left one screen

Learn about rearranging columns.

Learn about selecting fields and records in Datasheet view.


 Use shortcut keys to navigate in Form view

Use shortcut keys to navigate in Form view

Press | Going to a specific record
F5 | To move to the record number box; then type the record number and press ENTER

Press | Navigating between fields and records
TAB | To move to the next field
SHIFT+TAB | To move to the previous field
END | To move to the last field in the current record, in Navigation mode
CTRL+END | To move to the last field in the last record, in Navigation mode
HOME | To move to the first field in the current record, in Navigation mode
CTRL+HOME | To move to the first field in the first record, in Navigation mode
CTRL+PAGE DOWN | To move to the current field in the next record
CTRL+PAGE UP | To move to the current field in the previous record

Press | Navigating in forms with more than one page
PAGE DOWN | To go down one page; at the end of the record, moves to the equivalent page on the next record
PAGE UP | To go up one page; at the end of the record, moves to the equivalent page on the previous record

Press | Navigating between the main form and subform
TAB | To enter the subform from the preceding field in the main form
SHIFT+TAB | To enter the subform from the following field in the main form
CTRL+TAB | To exit the subform and move to the next field in the master form or next record
CTRL+SHIFT+TAB | To exit the subform and move to the previous field in the main form or previous record


Protect a Microsoft Access application by hiding objects in the database window and using startup options

Protect a Microsoft Access application by hiding objects in the database window or by using startup options

What do you want to do?

Hide objects in the Database window

Control how a database or application looks and behaves when it starts


Protect a Microsoft Access database (.mdb) file with a password or encryption

What do you want to do?

Protect a database by adding a database password

Remove a database password

About linking tables from a password-protected database

Encrypt or decrypt a database


Protect data access pages

What do you want to do?

Learn about protecting a data access page

Learn about protecting cells in a spreadsheet on a data access page


Protect Visual Basic for Applications code with a password or by creating an MDE file

What do you want to do?

Learn about protecting Visual Basic for Applications code

Protect Visual Basic for Applications code with a password

Work with MDE files


Protect a Microsoft Access database and its tables, queries, forms, reports, and macros with user-level security

What do you want to do?

Secure a database using the User-Level Security Wizard

Secure a database without requiring users to log on

Remove user-level security

Work with workgroup information files

Work with user and group accounts

Work with permissions

Convert a secured database from a previous version of Microsoft Access


Publish Web pages

What do you want to do?

Learn about the three types of Web pages Microsoft Access creates

Publish a data access page to Web Folders or any Web server

Publish server-generated HTML files to Web Folders or a Web server

Publish a static HTML file to Web Folders or a Web server


Read about Visual Basic modules

What do you want to do?

See an overview of what modules are and how they work

Learn about procedures

Run Visual Basic code

Work with data and database objects by using Visual Basic code


 Remove a button or other control from the tab order on a form

Remove a button or other control from the tab order on a form

There are two ways to remove a button or other control from the tab order. If you want to remove the control from the tab order, but you want to be able to select the control, you can set the TabStop property to No for that control.

If you want to disable the control until a certain condition is met, you can use the Enabled property together with the AfterUpdate property.

What do you want to do?

Remove the control from the tab order but don't disable it

Disable the control


Reset all default settings for a built-in toolbar or menu bar

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, click Properties.

  3. In the Selected Toolbar box, select the name of the toolbar or menu bar you want to reset default settings for.

  4. Click the Restore Defaults button.

The Restore Defaults button isn't available until Microsoft Access detects that the selected built-in toolbar or menu bar has been modified.


Secure a Microsoft Access database

What do you want to do?

Learn about protecting a Microsoft Access database

Protect a Microsoft Access database (.mdb) file with a password or encryption

Protect a Microsoft Access database and its tables, queries, forms, reports, and macros with user-level security

Protect Visual Basic for Applications code with a password or by creating an MDE file

Protect data access pages

Protect a Microsoft Access application by hiding objects in the database window and using startup options

Create or change passwords


 Use shortcut keys to select text or data

Use shortcut keys to select text or data

Press | Selecting text in a field
SHIFT+RIGHT ARROW | To extend one character to the right
CTRL+SHIFT+RIGHT ARROW | To extend one word to the right
SHIFT+LEFT ARROW | To extend one character to the left
CTRL+SHIFT+LEFT ARROW | To extend one word to the left

Note To cancel a selection, use the opposite arrow key.

Press | Selecting a field or record
TAB | To select the next field
F2 | To switch between Edit mode (with insertion point displayed) and Navigation mode
SHIFT+SPACEBAR | To switch between selecting the current record and the first field of the current record, in Navigation mode
SHIFT+UP ARROW | To extend selection to the previous record, if the current record is selected
SHIFT+DOWN ARROW | To extend selection to the next record, if the current record is selected
CTRL+A or CTRL+SHIFT+SPACEBAR | To select all records

How to select fields and records in Datasheet view.

Press | Extending a selection
F8 | To turn on Extend mode (EXT appears in the lower-right corner of the window); pressing F8 repeatedly extends the selection to the word, the field, the record (in Datasheet view only), and all records
LEFT ARROW or RIGHT ARROW | To extend a selection to adjacent fields in the same row in Datasheet view
UP ARROW or DOWN ARROW | To extend a selection to adjacent rows in Datasheet view
SHIFT+F8 | To undo the previous extension
ESC | To cancel Extend mode

Press | Selecting and moving a column in Datasheet view
CTRL+SPACEBAR | To select the current column or cancel the column selection, in Navigation mode only
SHIFT+RIGHT ARROW | To select the column to the right, if the current column is selected
SHIFT+LEFT ARROW | To select the column to the left, if the current column is selected
CTRL+SHIFT+F8 | To turn on Move mode; then press the RIGHT ARROW or LEFT ARROW key to move selected column(s) to the right or left Learn about rearranging columns


Share an Access database on a network

What do you want to do?

Ways to share a database

Learn about sharing Microsoft Access databases on a network

Share an Access database on a network server

Share an Access database when I don't have a network server

Split an Access database between its data and its objects

Learn about the three types of Web pages Microsoft Access creates

Use Briefcase to replicate an Access database

Work in a multiuser environment

Learn about editing data in an Access database in a multiuser environment

Learn about saving design changes to a shared Access database

Ways to open an Access database

Specify whether an Access database opens in shared or exclusive mode by default

Read tips for editing Access database objects in a multiuser environment

Read ways to optimize multiuser performance in an Access database

Manage record-locking

Read about choosing a record-locking strategy in an Access database in a multiuser environment

Specify the default record-locking strategy used in an Access database in a multiuser environment

Read ways to avoid data-locking conflicts in an Access database in a multiuser environment

Specify the default locking level used in an Access database in a multiuser environment

Specify multiuser/ODBC update retry and refresh interval settings in an Access database

View current data

Display the most current data in an Access database in Datasheet or Form view

Change how often data is updated automatically in an Access database in Datasheet or Form view

Automatically view the latest record in an Access database from a form

Automatically view the latest record from Page view


Sort or group records in a report

What do you want to do?

Sort records in a report

Group records in a report

Change sorting or grouping order in a report

Insert an additional sorting or grouping field or expression in a report

Delete a sorting or grouping field or expression in a report

Keep the data in a group together on a page or in a column in a report

Repeat a group header on another page or column

Troubleshoot sorting and grouping in a report


Sort or group records on a data access page

What do you want to do?

Specify a default sort order for a group of records

Group records on a page

Specify the number of records to display in a group

Specify whether a group is expanded or collapsed by default


Check the spelling of data

What do you want to do?

Check the spelling of data in Datasheet view

Check the spelling of data in Form view

Check the spelling of a database object in the Database window

Choose a custom dictionary for checking spelling


Use shortcut keys in Print Preview and Layout Preview

Press | Dialog box and window operations
P or CTRL+P | To open the Print dialog box
S | To open the Page Setup dialog box
Z | To zoom in or out on a part of the page
C or ESC | To cancel Print Preview or Layout Preview

Press | Viewing different pages
F5 | To move to the page number box; then type the page number and press ENTER
PAGE DOWN or DOWN ARROW | To view the next page (when Fit To Window is selected)
PAGE UP or UP ARROW | To view the previous page (when Fit To Window is selected)

Press | Navigating in Print and Layout Preview
DOWN ARROW | To scroll down in small increments
PAGE DOWN | To scroll down one full screen
CTRL+DOWN ARROW | To move to the bottom of the page
UP ARROW | To scroll up in small increments
PAGE UP | To scroll up one full screen
CTRL+UP ARROW | To move to the top of the page
RIGHT ARROW | To scroll to the right in small increments
END or CTRL+RIGHT ARROW | To move to the right edge of the page
CTRL+END | To move to the lower-right corner of the page
LEFT ARROW | To scroll to the left in small increments
HOME or CTRL+LEFT ARROW | To move to the left edge of the page
CTRL+HOME | To move to the upper-left corner of the page


Use subdatasheets

What do you want to do?

Learn about using subdatasheets

Insert or modify a subdatasheet in a table or query in a Microsoft Access database

Expand or collapse a subdatasheet

Remove a subdatasheet from a table or query in an Access database

Create one or more subforms

Delete a subform

Print a subdatasheet


 Validate values entered in a field, record, or control

Validate values entered in a field, record, or control

You can validate a value entered in a field, record or control by creating a validation rule. To perform more complex validation in a form, you can use a macro or Visual Basic for Applications code.

What do you want to do?

Create a field validation rule

Create a record validation rule

Create a validation rule for a control

Create more complex validation for a form using a macro or Visual Basic for Applications

Not sure which choice you want?


 Validate or restrict data entry in tables

Validate or restrict data entry in tables

You can control how data is entered in a field in a table by choosing the appropriate data type and field size. You can also use properties, such as input masks and validation rules, to control how data is entered in a field.

What do you want to do?

Find out more about choosing an appropriate data type for a field

Set the field size for a Number or Text field

Require that data be entered in a field

Define an input mask to control data entry

Prevent duplicate entries in a field

Define a field validation rule

Define a record validation rule

Not sure which choice you want?


Ways to get started if you've used previous versions of Microsoft Access

What do you want to read about?

What's new in Microsoft Access 2000

How do you want to get started?

Using a Microsoft Access database with several versions of Microsoft Access

Converting a database


Ways to get started if you've used other database or spreadsheet applications

What do you want to read about?

Relationships in a database

Working with other applications

How do you want to get started?

Importing or linking data from other programs and file formats

Splitting a table into related tables using the Table Analyzer Wizard

Creating a database


Ways to get started if you're using a database for the first time

What do you want to read about?

Databases: What they are and how they work

Tables: What they are and how they work

Queries: What they are and how they work

Forms: What they are and how they work

Reports: What they are and how they work

Data access pages: What they are and how they work

Macros: What they are and how they work

Modules: What they are and how they work

Relationships in a database

How do you want to get started?

Creating a database


 What is a bound HTML control?

What is a bound HTML control?

You can store HTML code in a field in a table, and when the data access page displays the values in that field, the HTML code performs the actions that you specified. You can accomplish this by binding the bound HTML control to a Text or Memo field in a Microsoft Access database (.mdb) or a text, ntext, or varchar column in a Microsoft Access project (.adp). If the HTML text is lengthy, bind the bound HTML control to a field with the Memo data type (Access database), or the text or ntext data type (Access project). When the field or column is placed on a data access page as a bound HTML control, the contents of the field are rendered as HTML and are not editable.

For example, if a value in a field is <font color=red>red Text</font> and you set the DataFormatAs property to HTML, then you will see red text when you view the data access page in Page view. If the DataFormatAs property is set to Text, then <font color=red>red Text</font> is the value displayed in the control.

Notes

  • You can make the bound HTML control the default control for a grouped data access page. Set the DefaultControlType property of the data access page to Bound HTML.

  • You can use a bound HTML control to display calculations and all data on a grouped data access page. The page will load faster in Microsoft Internet Explorer 5 if you use HTML controls.

More information

Create a bound HTML control on a data access page


What's new about Microsoft Access 2000

What area do you want to read about?

Working with data access pages

Working with a Microsoft Access project

Working on the Internet or an intranet

Working with data and database design

Working in the Database window

Programming with Visual Basic

Securing, maintaining, and converting a database

Creating and customizing forms and reports

Working with replication

Working with the sample applications

Using and customizing toolbars, menu bars, and shortcut menus

Working with macros

Working with other applications

What's new about Microsoft Office 2000


Use shortcut keys in the Database window

Press | Editing and navigating the Object list
F2 | To rename a selected object
DOWN ARROW | To move down one line
PAGE DOWN | To move down one window
END | To move to the last object
UP ARROW | To move up one line
PAGE UP | To move up one window
HOME | To move to the first object

Press | Navigating and opening objects
CTRL+TAB | To cycle through the Objects bar top to bottom
SHIFT+CTRL+TAB | To cycle through the Objects bar bottom to top
ENTER or ALT+O | To open the selected table or query in Datasheet view, or form in Form view
ENTER | To open the selected report in Print Preview
ENTER | To open the selected data access page in Page view
ENTER | To run the selected macro
CTRL+ENTER or ALT+D | To open the selected table, query, form, report, data access page, macro, or module in Design view
ALT+N | To create a new table, query, form, report, data access page, macro, or module
F5 | To refresh the Database window
CTRL+G | To display the Immediate window in the Visual Basic Editor


Work with combo boxes

What do you want to do?

Move the combo box

Size the combo box

Figure out why the combo box isn't working the way I want

Read about properties that I can use to modify the combo box


Work with command buttons

What do you want to do?

Move the command button

Size the command button

Add a picture to the command button

Change the command button caption

See the event procedure behind the command button


Work with imported or linked data

What do you want to do?

Customize a table

Troubleshoot importing

Set properties for a linked table


Work with list boxes

What do you want to do?

Move the list box

Size the list box

Figure out why the list box isn't working the way I want

Read about properties that I can use to modify the list box


Work with Lookup fields

What do you want to do?

Learn about properties I can use to modify a Lookup field

Learn more about Lookup fields and how they work


Work with option groups

What do you want to do?

Move the option group

Size the option group

Figure out why the option group isn't working the way I want


Using the User-Level Security Wizard

What do you want to do?

Tips on using the User-Level Security Wizard

Learn about a Microsoft Access workgroup

Learn how to organize security accounts

Learn how permissions work and who can assign them

Types of permissions

Learn about creating and changing passwords


Work with subforms

What do you want to do?

Move the subform control

Size the subform control

Change the layout of the subform

Figure out why the subform isn't working the way I want


Work with a crosstab query's datasheet

What do you want to do?

Change the font or font style, size, or color

Change the gridline style or background colors

Resize rows

Resize columns

Print the datasheet or selected records

Note You can't edit data in a crosstab query.


Work with data from more than one table

What do you want to do?

Read an overview of the ways to bring data from multiple tables or queries together in a query

Join multiple tables and queries in a query

See an overview of join types and how they affect query results

Change the type of join between tables and queries in a query


Work with data in Page view

What do you want to do?

Add, edit, and delete data

Move between records by using navigation buttons in Page view

Add a new record in Page view

Select fields and records in Page view

Edit the data in a field in Page view

Undo changes when adding or editing records in Page view

Display the most current data in Page view

Enter a hyperlink address in Page view

Add, change, or delete the path to a picture in Page view

Save and delete records

Save a record in Page view

Delete a record in Page view

Sort and filter data

Sort data in Page view

Find specific data by using a filter in Page view

Apply an existing filter to data in Page view

Remove a filter to show all records in Page view

Use shortcut keys

Use shortcut keys in Page view


Work with duplicate records in query Datasheet view

What do you want to do?

Delete duplicate records

Edit the data in a field

Print the entire datasheet or selected records


Work with macros in Visual Basic

What do you want to do?

Convert macros to Microsoft Visual Basic

Carry out a macro action in a Visual Basic procedure

See a list of macro actions that don't have corresponding DoCmd methods


Work with objects in Visual Basic by using the Object Browser

What do you want to do?

Locate a method or property in the Object Browser

Use the Object Browser to paste method or property syntax into a module


Work with relationships

What do you want to do?

Learn about relationships in a database

View existing relationships

Define relationships between tables

Define a many-to-many relationship between tables

Define the default join type for a relationship between two tables

Edit an existing relationship

Delete a relationship

Remove a table from the Relationships window

Change a table's design from the Relationships window

Learn about referential integrity

Learn about cascading updates and cascading deletes

Manage relationships by using the keyboard

Use subdatasheets

Print relationships


Work with subreports

What do you want to do?

Move the subreport control

Size the subreport control


Work with unmatched records in query Datasheet view

What do you want to do?

Delete an unmatched record

Add a matching record in the other table

Print the entire datasheet or selected records


Work with user and group accounts

What do you want to do?

Understand security accounts

Learn how to organize security accounts

Create accounts, add users, and print information

Create a security administrator account

Create a security user account

Create a security group account

Add users to security groups

Print information about security users and groups

Delete accounts and remove users

Remove users from security groups

Delete a security user account

Delete a security group account

Work with passwords

Create or change a security account password

Clear a security account password

View or transfer ownership

View or transfer ownership of individual objects in a secure database

Transfer ownership of an entire database to another administrator


Work with workgroup information files

Work with a workgroup information file

What do you want to do?

Understand workgroup information files

Learn about a Microsoft Access workgroup

Learn about ways to make a secure application and workgroup available to users

Create and join a workgroup information file

Create a new Microsoft Access workgroup information file

Join a Microsoft Access workgroup using the Workgroup Administrator

Set up more than one workgroup to use the same secure database

Learn about providing user-level security on a specific Access database

Log on to a workgroup information file

Log on to a Microsoft Access workgroup

Require users to log on to Microsoft Access

Turn off the Logon dialog box

Restore or rebuild a workgroup information file

Restore a damaged or deleted Microsoft Access workgroup information file

Rebuild a workgroup information file from user and group names and IDs


 #Const Directive

#Const Directive

In Microsoft Access, you can define a public conditional compiler constant in the Declarations section of a module. A public compiler constant is applicable to all modules in the current database, but not in any other database.

You can also declare a public compiler constant by clicking Options on the Tools menu, then clicking the Advanced tab. Enter the constant in the Conditional Compilation Arguments box.

For example, you might enter the following expression into the Conditional Compilation Arguments box.

conDebug = 1

You can use a public compiler constant in code in any module. For example, you can create an #If...Then...#Else construct to optionally run debug code.

#If conDebug = 1 Then
    .        ' Run debug code.
    .
    .
#Else
    .        ' Run streamlined code.
    .
    .
#End If

To create multiple public conditional compilation constants, declare them on separate lines in the Declaration section. In the Conditional Compilation Arguments box, separate them with colons. For example, you can enter the following conditional compilation constants in the Conditional Compilation Arguments box.

conActiveLanguage = 1 : conDebug = 1

You can use a logical operator to include both constants in an #If...Then...#Else construct. In the following example, the first segment of code runs only if both constants are currently equal to 1, so that the expression containing the constants is true.

#If (conActiveLanguage = 1 And conDebug = 1) Then
    .        ' Run debug code for the active language version.
    .
    .
#Else
    .        ' Run another code segment.
    .
    .
#End If

If either or both constants have a different value, then the code in the #Else portion of the construct runs. To change which block of code runs, you can simply change the values of the constants.

Notes

  • A conditional compilation constant is always evaluated with a text-based string comparison method. This evaluation is equivalent to having an Option Compare Text statement in the module and occurs even if the module contains an Option Compare Database statement.

  • When writing code for conditional compilation, it may be less confusing to view one procedure at a time rather than all procedures in the module. To change how you view your code, click Options on the Tools menu, then click the Module tab. Under Code View, clear the Full Module View check box.


 Activate, Deactivate Events - Event Procedures

Activate, Deactivate Events — Event Procedures

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 [image] .

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.


Activate, Deactivate Events - Event Procedures Example

Activate, Deactivate Events — Event Procedures Example

The following example shows how to display a custom toolbar named CustomToolbar when a form receives the focus and to hide it when the focus moves to a different window.

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", acToolbarYes
End Sub

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


 Activate, Deactivate Events - Macros

Activate, Deactivate Events — Macros

To run a macro when the Activate or Deactivate event occurs, set the OnActivate or OnDeactivate property to the name of the macro.

Remarks

You can use the ShowToolbar action in an Activate or Deactivate macro to display or hide a custom toolbar. Use the Activate or Deactivate event to display or hide custom toolbars when you have more than one form loaded at a time. If you have only one form loaded at a time, you can use the Open and Close events.

If you use a Deactivate macro to hide a custom toolbar 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.


 ApplyFilter Event - Event Procedures

ApplyFilter Event — Event Procedures

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

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 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
 | acApplyServerFilter | 3
 | acCloseServerFilterWindow | 4

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 or acCloseServerFilterWindow.


ApplyFilter Event - Event Procedures Example

ApplyFilter Event — Event Procedures Example

The following example shows how to hide the AmountDue, Tax, and TotalDue controls on an Orders form when the applied filter restricts the records to only those orders that have been paid for.

To try this example, add the following event procedure to an Orders form that contains 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 If
End Sub


 ApplyFilter Event - Macros

ApplyFilter Event — Macros

To run a macro when the ApplyFilter event occurs, set the OnApplyFilter property to the name of the macro.

Remarks

You can check a filter, or even change the criteria the user has entered, by reading the value of the Filter or ServerFilter 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.


 BeforeInsert, After Insert Events - Event Procedures

BeforeInsert, AfterInsert Events — Event Procedures

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 [image] .

Syntax

Private Sub Form_BeforeInsert(Cancel As Integer)

Private Sub Form_AfterInsert( )

The BeforeInsert event procedure has the following argument.

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

Remarks

You can't cancel the AfterInsert event.


BeforeInsert, AfterInsert Events - Event Procedures Example

BeforeInsert, AfterInsert Events — Event Procedures Example

This example shows how you can use a BeforeInsert event procedure to verify that the user wants to create a new record, and an AfterInsert event procedure to requery the record source for the Employees form after a record has been added.

To try the example, add the following event procedure to a form named Employees that is based on a table or query. Switch to form Datasheet view and try to insert a record.

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

Private Sub Form_AfterInsert()
    Forms!Employees.Requery
End Sub


 BeforeInsert, AfterInsert Events - Macros

BeforeInsert, AfterInsert Events — Macros

To run a macro when the BeforeInsert or AfterInsert event occurs, set the BeforeInsert or AfterInsert property to the name of the macro.

Remarks

You can use these macros to display messages or useful information. For example, you can have the BeforeInsert macro display data the user needs when entering a new record.

You can use the CancelEvent action in a BeforeInsert macro to cancel the creation of the new record. When you use the CancelEvent action in a BeforeInsert macro, the focus returns to the new record, which is blank (the character that the user typed is deleted).

You can't use the CancelEvent action in an AfterInsert macro.


 BeforeUpdate, AfterUpdate Events - Event Procedures

BeforeUpdate, AfterUpdate Events — Event Procedures

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 [image] .

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.

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.

The AfterUpdate event procedure has the following argument.

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

Remarks

You can't cancel the AfterUpdate event.

You can use an AfterUpdate event procedure to display a different page in the form or move the focus to a particular control or record. For example, when the user enters a value in a Category control on a form, you can use the GoToPage method in the AfterUpdate event procedure for the form to move the focus to the page of the form that contains the controls for that category.


BeforeUpdate, AfterUpdate Events - Event Procedures Example

BeforeUpdate, AfterUpdate Events — Event Procedures Example

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

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

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


 BeforeUpdate, AfterUpdate Events - Macros

BeforeUpdate, AfterUpdate Events — Macros

To run a macro when the BeforeUpdate or AfterUpdate event occurs, set the BeforeUpdate or AfterUpdate property to the name of the macro. Microsoft Access runs the macro specified by the BeforeUpdate or AfterUpdate property for a control or form before or after the data in the control or in the current record on the form is updated. If the data in the control or record isn't updated, the macro doesn't run.

Remarks

You can use BeforeUpdate macros if you want to store all the validations for a form in one macro group or if you use a validation expression on several forms.

For example, suppose you have a form on which the user enters the name of a country in a Country control and its corresponding postal code in a Postal Code control. You use conditional expressions in the macro to make sure that the data entered in the Country control corresponds to the data entered in the Postal Code control and to display a message if invalid data is entered in the Postal Code control.

You can use an AfterUpdate macro to display a different page in the form or move the focus to a particular control or record. For example, when the user enters a value in a Category control on a form, you can use the GoToPage action in an AfterUpdate macro to move the focus to the page of the form that contains the controls for that category.

You can use the CancelEvent action in a BeforeUpdate macro to cancel the update. If the BeforeUpdate macro is attached to a control, the CancelEvent action returns the focus to the control, and the data the user entered remains in the control.

If a BeforeUpdate macro is attached to a form (in which it runs each time a record is changed), the CancelEvent action returns the focus to the record.

You can't use the CancelEvent action in an AfterUpdate macro to cancel the AfterUpdate event.


 Change Event - Event Procedures

Change Event — Event Procedures

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

Syntax

Private Sub controlname_Change( )

The Change event procedure has the following argument.

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

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.


Change Event - Event Procedures Example

Change Event — Event Procedures Example

The following example counts the number of characters entered in a text box. If more than three characters are entered, a message is displayed and the count is reset to 0.

To try 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 If
End Sub


 Change Event - Macros

Change Event — Macros

To run a macro when the Change event occurs, set the OnChange property to the name of the macro.

Remarks

You can use a Change macro to synchronize data in two controls; when a change occurs in one control, it can be reflected in the other control.

You can't use the CancelEvent action in a Change macro.


 Click Event - Event Procedures

Click Event — Event Procedures

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

Syntax

Private Sub Form_Click( )

Private Sub controlname_Click( )

The Click event procedure has the following argument.

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

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.


Click Event - Event Procedures Example

Click Event — Event Procedures 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 With
End Sub


 Click Event - Macros

Click Event — Macros

To run a macro when the Click event occurs, set the OnClick property to the name of the macro.

Remarks

You often use Click macros to carry out the actions for each command button on a form. For example, by clicking one command button on a form, users can print a report showing the form's records. By clicking another, they can open a related form.

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


 Current Event - Event Procedures

Current Event — Event Procedures

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

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.


Current Event - Event Procedures Examples

Current Event — Event Procedures Examples

In the following example, a Current event procedure checks the status of an option button called Discontinued. If the button is selected, the example sets the background color of the ProductName field to red to indicate that the product has been discontinued.

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
    EndIf
End 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!SupplierName
End Sub


 Current Event - Macros

Current Event — Macros

To run a macro when the Current event occurs, set the OnCurrent property to the name of the macro.

Remarks

You can'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.


 DblClick Event - Event Procedures

DblClick Event — Event Procedures

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

Syntax

Private Sub Form_DblClick(Cancel As Integer)

Private Sub controlname_DblClick(Cancel As Integer)

The DblClick event procedure has the following arguments.

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.

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


DblClick Event - Event Procedures Example

DblClick Event — Event Procedures 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

DblClick Event — Macros

To run a macro when the DblClick event occurs, set the OnDblClick property to the name of the macro.

Remarks

By running a macro when the DblClick event occurs, you can modify a control's default double-click behavior. For example, you can run a macro before an OLE 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.


 Delete, BeforeDelConfirm, AfterDelConfirm Events - Event Procedures

Delete, BeforeDelConfirm, AfterDelConfirm Events — Event Procedures

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 [image] .

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.

Argument | Description
Cancel | The setting determines if the Delete event occurs. Setting the Cancel argument to True (–1) cancels the Delete event.

The BeforeDelConfirm event procedure has the following arguments.

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

The AfterDelConfirm event procedure has the following argument.

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.
 | acDeleteUserCancel | Indicates the deletion was canceled by the user.

Remarks

The AfterDelConfirm event can't be canceled.

You can use these events to customize how records are deleted. For example, when a user deletes a record, such as an employee record, the Delete event occurs. You can place code in the Delete event procedure to save the data from the Employee ID and Name fields in a 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.


Delete, BeforeDelConfirm, AfterDelConfirm Events - Event Procedures Example

Delete, BeforeDelConfirm, AfterDelConfirm Events — Event Procedures 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 If
End Sub

Private Sub Form_AfterDelConfirm(Status As Integer)
    Select Case Status
        Case acDeleteOK
            MsgBox "Deletion occurred normally."
        Case acDeleteCancel
            MsgBox "Programmer canceled the deletion."
        Case acDeleteUserCancel
            MsgBox "User canceled the deletion."
    End Select
End Sub


 Delete, BeforeDelConfirm, AfterDelConfirm Events - Macros

Delete, BeforeDelConfirm, AfterDelConfirm Events — Macros

To run a macro when a Delete, BeforeDelConfirm, or AfterDelConfirm event occurs, set the OnDelete, BeforeDelConfirm, or AfterDelConfirm property to the name of the macro.

Remarks

You can use a Delete macro to display 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.


 Dirty Event - Event Procedures

Dirty Event — Event Procedures

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

Syntax

Private Sub Form_Dirty(Cancel As Integer )

The Dirty event procedure has the following argument.

Argument | Description
Cancel | The setting determines if the Dirty event occurs. Setting the Cancel argument to True (-1) cancels the Dirty event. You can also use the CancelEvent method of the DoCmd object to cancel the event.

Remarks

Canceling the Dirty event will cause the changes to the current record to be rolled back. It is equivalent to pressing the Esc key.


Dirty Event - Event Procedures Example

Dirty Event — Event Procedures Example

The following example enables the btnUndo button when data is changed. The UndoEdits( ) subroutine is called from the Dirty event of text box controls. Clicking the enabled btnUndo button restores the original value of the control by using the OldValue property.

Private Sub Form_Dirty()
    If Me.Dirty Then
        Me!btnUndo.Enabled = True    ' Enable button.
    Else
        Me!btnUndo.Enabled = False    ' Disable button.
    End If
End Sub

Sub btnUndo_Click()
    Dim 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 ctlC
End Sub


 Dirty Event - Macros

Dirty Event — Macros

To run a macro when the Dirty event occurs, set the OnDirty property to the name of the macro.

Remarks

You can use a Dirty macro to check to see if the user has permission to change this record. A message can be displayed to input the user's id for validation.


 Enter, Exit Events - Event Procedures

Enter, Exit Events — Event Procedures

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 [image] .

Syntax

Private Sub controlname_Enter( )

Private Sub controlname_Exit(Cancel As Integer)

The Enter event procedure has the following argument.

Argument | Description
controlname | The name of the control whose Enter event procedure you want to run.

The Exit event procedure has the following arguments.

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

Remarks

You can't cancel the Enter event.


Enter, Exit Events - Event Procedures Example

Enter, Exit Events — Event Procedures 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 If
End Sub


 Enter, Exit Events - Macros

Enter, Exit Events — Macros

To run a macro when the Enter or Exit event occurs, set the OnEnter or OnExit property to the name of the macro.

Remarks

When the Enter or Exit event occurs, you can run a macro that uses a GoToControl action to change the tab order based on current data in a control. For example, if the user enters Single in the MaritalStatus field, 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.


 Error Event - Event Procedures

Error Event — Event Procedures

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

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

Remarks

You can't cancel the Error event.


Error Event - Event Procedures Example

Error Event — Event Procedures Example

The following example shows how you can replace a default error message with a custom error message. When Microsoft Access returns an error message indicating it has found a duplicate key (error code 3022), this event procedure displays a message that gives more application-specific information to users.

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
        strMsg = "Each employee record must have a unique " _
            & "employee ID number. Please recheck your data."
        MsgBox strMsg
    End If
End Sub


 Error Event - Macros

Error Event — Macros

To run a macro when the Error event occurs, set the OnError property to the name of the macro.

Remarks

You can use an Error macro to display a general message whenever a run-time error occurs. However, macros can't return the error code and determine which error occurred, so you typically use event procedures with this event.

You can't use the CancelEvent action in an Error macro.


 Filter Event - Event Procedures

Filter Event — Event Procedures

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

Syntax

Private Sub Form_Filter(Cancel As Integer, FilterType As Integer)

The Filter event procedure has the following arguments.

Argument | Description
Cancel | The setting determines whether to open the filter window. Setting the Cancel argument to True (–1) prevents the filter window from opening. You can also use the CancelEvent method of the DoCmd object to cancel opening the filter window.
FilterType | The filter window the user is trying to open. The FilterType argument can be one of the following intrinsic constants:
 | Constant | Value
 | acFilterByForm | 0
 | acFilterAdvanced | 1
 | acServerFilterByForm | 2

Remarks

You can use the Filter event procedure to disable or hide certain controls in the Filter By Form or Server Filter By Form window, preventing them from being used in filter criteria. For example, you may want your Orders form always to show records that have a value in the TotalDue control, no matter how small. You can disable or hide this control in the Filter event procedure, then enable or show it in the ApplyFilter event procedure. Disabling and hiding controls in the Filter By Form or Server Filter By Form window is best accomplished in the Filter event procedure rather than the Filter macro, because you can check the FilterType argument to see if the user opened the Filter By Form or Server Filter By Form window. In a Microsoft Access database (.mdb), all of the fields in a form appear in the Advanced Filter/Sort window, even if the controls are disabled or hidden.


Filter Event - Event Procedures Example

Filter Event — Event Procedures Example

The following example shows how to disable the TotalDue control on an Orders form when the user tries to create a filter, so that the user can't filter on this field. Any records that have a TotalDue value and meet the other filter criteria will always be shown on the filtered form. This example also forces the user to use the Filter By Form window and not the Advanced Filter/Sort window.

To try this example, add the following event procedure to an Orders form that contains a TotalDue control. Try to create a filter by using the Advanced Filter/Sort window that uses the TotalDue control. Also try creating the same filter by using the Filter By Form window.

Private Sub Form_Filter(Cancel As Integer, FilterType As Integer)
    If FilterType = acFilterByForm Then
        Forms!Orders!TotalDue.Enabled = False
    ElseIf FilterType = acFilterAdvanced Then
        MsgBox "The best way to filter this form is to use the " _
            & "Filter By Form command or toolbar button.", vbOKOnly + vbInformation
        Cancel = True
    End If
End Sub


 Filter Event - Macros

Filter Event — Macros

To run a macro when the Filter event occurs, set the OnFilter property to the name of the macro.

Remarks

You can set the Filter or ServerFilter property in a Filter macro by using the SetValue action. This enables you to customize the filter criteria that the user sees when the Filter By Form, Advanced Filter/Sort, or the Server Filter By Form window is displayed.

You can use the CancelEvent action in a Filter macro to cancel opening the filter window.


 Format Event - Event Procedures

Format Event — Event Procedures

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

Syntax

Private Sub sectionname_Format(Cancel As Integer, FormatCount As Integer)

The Format event procedure has the following arguments.

Argument | Description
sectionname | The name of the report section whose Format event procedure you want to run.
Cancel | The setting determines if the formatting of the section occurs. Setting the Cancel argument to True (–1) cancels formatting of the section.
FormatCount | An Integer value that specifies whether the Format event has occurred more than once for a section. For example, if a section doesn't fit on one page and part of it moves to the next page of the report, Microsoft Access sets the FormatCount argument to 2.

Remarks

If you cancel formatting, Microsoft Access doesn't format the section for printing and prints the next section instead. You can use this event procedure to skip a section in a report without leaving a blank space on the page when the report is printed.


Format Event - Event Procedures Example

Format Event — Event Procedures Example

The following example displays or hides a congratulatory message next to a calculated control that shows sales totals by salesperson. In report sections where the sales total is greater than the sales goal, a label named Message displays the message "Congratulations! You have met your sales goal" when the section is printed; in sections where the sales total is less than the sales goal, the label is hidden.

To try the example, add the following event procedure to a report that contains a label called Message, a text box called GrandTotal (a calculated control that displays the sales total), and a detail section called SalesDetail.

Private Sub SalesDetail_Format(Cancel As Integer, _
        FormatCount As Integer)
    Const conSalesGoal = 1000
    If Me!GrandTotal > conSalesGoal Then
        Me!Message.Visible = True
    Else
        Me!Message.Visible = False
    End If
End Sub


 Format Event - Macros

Format Event — Macros

To run a macro when the Format event occurs, set the OnFormat property to the name of the macro.

Remarks

You can use the FormatCount property to check whether the Format event has occurred more than once for a section. For example, if a section doesn't fit on one page and part of it moves to the next page of the report, the Format event occurs once for each page, and the FormatCount property is set to 2. You can check the FormatCount property setting to determine how many times a Format macro has run per section.

You can use the CancelEvent action in a Format macro to cancel formatting of a section. If you cancel formatting, Microsoft Access doesn't format the section for printing and prints the next section instead. You can use the CancelEvent action to skip a section in a report without leaving a blank space on the page when the report is printed.


 GotFocus, LostFocus Events - Event Procedures

GotFocus, LostFocus Events — Event Procedures

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 [image] .

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.

Argument | Description
controlname | The name of the control whose GotFocus or LostFocus event procedure you want to run.

Remarks

You can use a LostFocus event procedure to validate entered data as the user moves the focus from a control. You can also reverse or change conditions that you set up in the object's GotFocus event procedure.

Other uses for LostFocus and GotFocus event procedures are enabling, disabling, hiding, and displaying other objects.

You can't cancel a GotFocus or LostFocus event.


GotFocus, LostFocus Events - Event Procedures Example

GotFocus, LostFocus Events — Event Procedures Example

The following example displays a message in a label when the focus moves to an option button.

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

GotFocus, LostFocus Events — Macros

To run a macro when the GotFocus or LostFocus event occurs, set the OnGotFocus or OnLostFocus property to the name of the macro.

Remarks

You can use a LostFocus macro to validate entered data as the user moves the focus from a control. You can also reverse or change conditions that you set up in the object's GotFocus macro.

Other uses for LostFocus and GotFocus macros are enabling, disabling, displaying, and hiding other objects.

You can't use the CancelEvent action in a GotFocus or LostFocus macro.


 Initialize Event - Event Procedure

Initialize Event — Event Procedure

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 code in a standard module that creates a new instance of the class CustomObject, as shown in the following example:

Dim obj As CustomObject
Set obj = New CustomObject

When you run the procedure that contains this code, Visual Basic creates a new instance of the CustomObject class, and the Initialize event occurs.

When declaring an object variable using the New keyword, the Initialize event 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.


Initialize, ItemAdded, ItemRemoved, Terminate Event Procedures 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.References
End Sub

' When instance is removed, set evtReferences to Nothing.
Private Sub Class_Terminate()
    Set evtReferences = Nothing
End 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
    AddReference = False
    Resume Exit_AddReference
End 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_RemoveReference
End Function


 ItemAdded Event - Event Procedures

ItemAdded Event — Event Procedures

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.

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. 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. 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. 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. 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.References
End 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. 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 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 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

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

  • You can include the ItemAdded event procedure only in a class module.

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

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

  • The ItemAdded event occurs after the reference has been added to the project.


 ItemRemoved Event - Event Procedures

ItemRemoved Event — Event Procedures

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)

The ItemRemoved 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 removed from the References collection.

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. 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. 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. 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.References
End 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.

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. 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 ref
End Function

Notes

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

  • You can include the ItemRemoved event procedure only in a class module.

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

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

  • The ItemRemoved event occurs after the reference has been removed from the project.


 KeyDown, KeyUp Events - Event Procedures

KeyDown, KeyUp Events — Event Procedures

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 [image] .

Syntax

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)

Private Sub controlname_KeyDown(KeyCode As Integer, Shift As Integer)

Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)

Private Sub controlname_KeyUp(KeyCode As Integer, Shift As Integer)

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

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


KeyDown, KeyUp Events - Event Procedures Example

KeyDown, KeyUp Events — Event Procedures Example

The following example determines whether you have pressed the SHIFT, CTRL, or ALT key.

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

KeyDown, KeyUp Events — Macros

To run a macro when the KeyDown or KeyUp event occurs, set the OnKeyDown or OnKeyUp property to the name of the macro.

Remarks

You can use a KeyDown or KeyUp macro to respond whenever the user presses or releases a key while a form or control has the focus. However, macros can't return the key code and determine which key was pressed, so you typically use event procedures with these events.

You can't use the CancelEvent action in a KeyDown or KeyUp macro.


 KeyPress Event - Event Procedures

KeyPress Event — Event Procedures

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

Syntax

Private Sub Form_KeyPress(KeyAscii As Integer)

Private Sub controlname_KeyPress(KeyAscii As Integer)

The KeyPress event has the following arguments.

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.

Remarks

A KeyPress event procedure is useful for intercepting keystrokes entered in a text box or combo box. It enables you to test keystrokes for validity or to format characters as they're typed. Changing the value of the KeyAscii argument changes the character displayed.

You can convert the KeyAscii argument to a character by using the following expression.

Chr(KeyAscii)

You can then perform string operations and translate the character back to an ANSI number that the control can recognize by using the following syntax.

KeyAscii = Asc(character)

Note The ANSI number for the keyboard combination CTRL+@ is 0. Because Microsoft Access recognizes a KeyAscii value of 0 as a zero-length string (" "), you should avoid using CTRL+@ in your applications.

You can respond to specific keys pressed while a form is open, regardless of which control has the focus. For example, you may want the key combination CTRL+X to always perform the same action on a form. To make sure a form receives all keyboard events, even those that occur for controls, before they occur for the controls, set the KeyPreview property of the form to Yes. With this property setting, all keyboard events occur first for the form, and then for the control that has the focus. You can respond to specific keystrokes in the form's KeyDown, KeyPress, and KeyUp events. You can prevent a control from receiving keystrokes you've responded to, and prevent the keyboard events from occurring for the control, by setting the KeyCode argument to 0 for both the KeyDown and KeyUp events, and setting the KeyAscii argument to 0 for the KeyPress event. You must set all three arguments to 0 if you don't want the control to receive the keystrokes.

You can use the arguments for the KeyDown, KeyPress, and KeyUp events, in conjunction with the arguments for the MouseDown, MouseUp, and MouseMove events, to make your application work smoothly for both keyboard and mouse users.

You can't cancel the KeyPress event in an event procedure, but you can cancel it in a macro.


KeyPress Event - Event Procedures Example

KeyPress Event — Event Procedures Example

The following example converts text entered in a text box to uppercase as the text is typed in, one character at a time.

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


 Key Press Event - Macros

KeyPress Event — Macros

To run a macro when the KeyPress event occurs, set the OnKeyPress property to the name of the macro.

Remarks

You can use a KeyPress macro to respond whenever the user presses an ANSI key while the focus is on a form or control. However, macros can't return the ANSI key code and determine which key was pressed, so you typically use event procedures with this event.

You can use the CancelEvent action in a KeyPress macro to cancel the key or key combination. For example, you may want to disallow the entry of ANSI keystrokes in a control under certain conditions.


 Load, Unload Events - Event Procedures

Load, Unload Events — Event Procedures

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 [image] .

Syntax

Private Sub Form_Load( )

Private Sub Form_Unload(Cancel As Integer)

The Unload event has the following argument.

Argument | Description
Cancel | The setting determines whether to unload the form. Setting Cancel to True (–1) prevents the form from being unloaded.

Remarks

You can place initialization code in a form's Load event procedure. For example, you can specify default settings for controls and initialize form-level variables.

You can't cancel the Load event.

In an Unload event procedure, you can include any form-level validation code you might need to close the form or save the data it contains to a file.

If Cancel is set to True for a form that is modal, you may not be able to return control to the rest of the application.


Load, Unload Events - Event Procedures Example

Load, Unload Events — Event Procedures Example

The following example displays the current date in the form's caption when the form is loaded.

To try the example, add the following event procedure to a form:

Private Sub Form_Load()
    Me.Caption = Date
End 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 If
End Sub


 Load, Unload Events - Macros

Load, Unload Events — Macros

To run a macro when the Load or Unload event occurs, set the OnLoad or OnUnload property to the name of the macro.

Remarks

You can use a Load macro to carry out actions for the controls or records on a form after the form opens. For example, you can specify default settings for controls.

You can't use the CancelEvent action in a Load macro.

You can use the CancelEvent action in an Unload macro to cancel unloading of the records. This also cancels closing of the form.

If a form's Unload macro carries out a CancelEvent action, you won't be able to close the form. You must either correct the condition that caused the CancelEvent action to be carried out or open the macro and delete the CancelEvent action. If the form is modal, you won't be able to open the macro or work in any other windows in the application.


 MouseDown, MouseUp Events - Event Procedures

MouseDown, MouseUp Events — Event Procedures

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 [image] .

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.

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

Note If a mouse button is pressed while the pointer is over a form or control, that object receives all mouse events up to and including the last MouseUp event. This means that the X and Y arguments may not always be relative to the object that receives them.

Remarks

You test for a condition by first assigning each result to a temporary Integer variable and then comparing the Shift or Button argument to 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.


MouseDown, MouseUp Events - Event Procedures Example

MouseDown, MouseUp Events — Event Procedures Example

The following example shows how you can find out which mouse button caused a MouseDown event.

To try 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
        MsgBox "You pressed the middle button."
    End If
End Sub


 MouseDown, MouseUp Events - Macros

MouseDown, MouseUp Events — Macros

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.


 MouseMove Event - Event Procedures

MouseMove Event — Event Procedures

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

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.

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

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

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.


MouseMove Event - Event Procedures Example

MouseMove Event — Event Procedures Example

The following example determines where the mouse is and whether the left mouse button and/or the SHIFT key is pressed. The x and y coordinates of the mouse pointer position are displayed in a label control as you move the mouse.

To try 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 If
End Sub


 MouseMove Event - Macros

MouseMove Event — Macros

To run a macro when the MouseMove event occurs, set the OnMouseMove property to the name of the macro.

Remarks

You can use a MouseMove macro to respond whenever the user moves the mouse over a form or control. However, macros can't return the button code and determine the state of the mouse buttons or determine the coordinates of the mouse pointer when the movement occurs, so you typically use event procedures with this event.

You can't use the CancelEvent action in a MouseMove macro.


 NoData Event - Event Procedures

NoData Event — Event Procedures

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

Syntax

Private Sub Report_NoData(Cancel As Integer)

The NoData event procedure has the following argument.

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.


NoData Event - Event Procedures Example

NoData Event — Event Procedures 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." _
        & chr(13) & "Printing is canceled. " _
        & chr(13) & "Check the data source for the " _
        & chr(13) & "report. Make sure you entered " _
        & chr(13) & "the correct criteria (for " _
        & chr(13) & "example, a valid range of " _
        & chr(13) & "dates),." vbOKOnly + vbInformation
    Cancel = True
End Sub


 NoData Event - Macros

NoData Event — Macros

To run a macro when the NoData event occurs, set the OnNoData property to the name of the macro.

Remarks

You can use the CancelEvent action in a NoData macro to cancel printing of the blank report.


 NotInList Event - Event Procedures

NotInList Event — Event Procedures

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

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

Remarks

You can create an event procedure for the NotInList event that provides a way for the user to add a new item to the combo box list. For example, you can add a record to the table that supplies the list's values, or add a value to the value list that is the source for the combo box list.

To add a new entry to a combo box list, your event procedure must add the value in the NewData argument to the source of the combo box list. How you do this depends on the type of source the combo box list uses, as determined by the RowSourceType and RowSource properties of the combo box. In the Example in this topic, the event procedure adds the new value to a value list for the combo box.

If you let the user change the value originally typed in the combo box (for example, in a custom dialog box), you must set the combo box value to the new entry entered in the custom dialog box. This saves the new value in the field the combo box is bound to. Set the Response argument to acDataErrContinue, and Microsoft Access will add the new value to the combo box list.


NotInList Event - Event Procedures Example

NotInList Event — Event Procedures Example

The following example uses the NotInList event to add an item to a combo box.

To try this example, create a combo box called Colors on a form. Set the 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.
    Set ctl = Me!Colors
    ' Prompt user to verify they wish to add new value.
    If MsgBox("Value is not in list. Add it?", _
         vbOKCancel) = vbOK Then
        ' Set Response argument to indicate that data
        ' is being added.
        Response = acDataErrAdded
        ' Add string in NewData argument to row source.
        ctl.RowSource = ctl.RowSource & ";" & NewData
    Else
    ' If user chooses Cancel, suppress error message
    ' and undo changes.
        Response = acDataErrContinue
        ctl.Undo
    End If
End Sub

Note The above example adds an item to an unbound combo box. When you add an item to a bound combo box, you add a value to a field in the underlying data source. In most cases you can't simply add one field in a new record — 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

NotInList Event — Macros

To run a macro when the NotInList event occurs, set the OnNotInList property to the name of the macro.

Remarks

You can use a NotInList macro to add a new value to the combo box list. When the NotInList event occurs, open a custom dialog box and set the value of one of its controls to the new value. This control should be bound to the field in the table or query that is the source for the combo box. Save the record in the custom dialog box, then requery the combo box.

You can't use the CancelEvent action in a NotInList macro.


 Open, Close Events - Event Procedures

Open, Close Events — Event Procedures

To create an event procedure that is run when the Open or Close event occurs, set the OnOpen or OnClose property to [Event Procedure], and click the Build button [image] .

Syntax

Private Sub Form_Open(Cancel As Integer)

Private Sub Report_Open(Cancel As Integer)

Private Sub Form_Close( )

Private Sub Report_Close( )

The Open event procedure has the following argument.

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.

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", acToolbarYes
End Sub


Open, Close Events - Event Procedures Example

Open, Close Events — Event Procedures 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
            ' Open Order Details form.
            DoCmd.OpenForm "Order Details"
        Case vbNo
            MsgBox "Remember to enter order details by 5 P.M."
            Cancel = True                    ' Cancel Open event.
    End Select
End Sub


 Open, Close Events - Macros

Open, Close Events — Macros

To run a macro when the Open or Close event occurs, set the OnOpen or OnClose property to the name of the macro.

Remarks

You can use the CancelEvent action in an Open macro to cancel opening of the form or report. You can't use the CancelEvent action in a Close macro 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.


 Page Event - Event Procedures

Page Event — Event Procedures

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

Syntax

Private Sub Report_Page( )

Remarks

You can't cancel the Page event.


Page Event - Event Procedures Example

Page Event — Event Procedures Example

The following example shows how to draw a rectangle around a report page 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), , B
End Sub


 Page Event - Macros

Page Event — Macros

To run a macro when the Page event occurs, set the OnPage property to the name of the macro.

Remarks

Since you normally use the Line, Circle, or PSet methods in the Page event procedure to create the desired graphics for the page, you typically use the Page event procedure with this event rather than the Page macro.

You can't use the CancelEvent action in a Page macro.


 Print Event - Event Procedures

Print Event — Event Procedures

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

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

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.


Print Event - Event Procedures Example

Print Event — Event Procedures 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 = True
End Sub


 Print Event - Macros

Print Event — Macros

To run a macro when the Print event occurs, set the OnPrint property to the name of the macro.

Remarks

You can use the PrintCount property to check whether the Print event has occurred more than once for a record. For example, if part of a record is printed on one page and the rest is printed on the next page, the Print event occurs twice, and the PrintCount property is set to 2. You can check the PrintCount 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.


 Resize Event - Event Procedures

Resize Event — Event Procedures

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

Syntax

Private Sub Form_Resize( )

Remarks

To repaint the screen every time a form is resized, use the Repaint method in a Resize event procedure.

You can't cancel the Resize event.


Resize Event - Event Procedures Example

Resize Event — Event Procedures Example

The following example shows how a Resize event procedure can be used to repaint a form when it is maximized. When the user clicks a command button labeled "Maximize," the form is maximized and the Resize event is triggered.

To try the example, add the following event procedures to a form named Contacts that contains a command button named Maximize:

Private Sub Maximize_Click()
    DoCmd.Maximize
End Sub

Private Sub Form_Resize()
    Forms!Contacts.Repaint
End Sub


 Resize Event - Macros

Resize Event — Macros

To run a macro when the Resize event occurs, set the OnResize property to the name of the macro.

Remarks

To repaint the screen every time a form is resized, use the RepaintObject action in the macro you specify for the Resize event.

You can't use the CancelEvent action in a Resize macro.


 Retreat Event - Event Procedures

Retreat Event — Event Procedures

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

Syntax

Private Sub sectionname_Retreat( )

The Retreat event procedure has the following argument.

Argument | Description
sectionname | The name of the report section whose Retreat event procedure you want to run.

Remarks

You can't cancel the Retreat event.


 Retreat Event - Macros

Retreat Event — Macros

To run a macro when the Retreat event occurs, set the OnRetreat property to the name of the macro.

Remarks

You can't use the CancelEvent action in a Retreat macro.


 Terminate Event - Event Procedure

Terminate Event — Event Procedure

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.


 Timer Event - Event Procedures

Timer Event — Event Procedures

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

Syntax

Private Sub Form_Timer( )

Remarks

You can't cancel the Timer event.


Timer Event - Event Procedures Example

Timer Event — Event Procedures Example

The following example demonstrates a digital clock you can display on a form. A label control displays the current time according to your computer's system clock.

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

Timer Event — Macros

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.


 Updated Event - Event Procedures

Updated Event — Event Procedures

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

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

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.


 Updated Event - Macros

Updated Event — Macros

To run a macro when the Updated event occurs, set the OnUpdated property to the name of the macro.

Remarks

You can use an Updated macro to display a message whenever an OLE object's data has been updated. However, macros can't return the code that determines how the OLE object was updated, so you typically use event procedures with this event.

You can't use the CancelEvent action in an Updated macro.


Microsoft Office Assistant Example

The following function creates a custom balloon for the Office Assistant and determines how the user responded to the balloon:

Function AssistantBalloon(Optional varCheck As Variant, Optional varLabel As Variant)
    Dim bch As BalloonCheckbox
    Dim intI As Integer
    Dim intReturn As Integer
    Dim strCheck(5) As String
    Dim strList As String

    ' Create new balloon.
    Set bal = Assistant.NewBalloon
    ' Specify balloon type.
    bal.BalloonType = msoBalloonTypeButtons
    ' Specify that balloon is modal.
    bal.Mode = msoModeModal

    ' Make Assistant visible.
    If Assistant.Visible = False Then Assistant.Visible = True
    ' Check if first argument has been passed.
    If Not IsMissing(varCheck) Then
        ' If too large, set to maximum number of check boxes (5).
        If varCheck > 6 Then
            varCheck = 5
        End If
        ' Set text property to alphabet character.
        For intI = 1 To varCheck
            bal.Checkboxes(intI).Text = Chr(64 + intI)
        Next intI
    End If

    If Not IsMissing(varLabel) Then
        ' If too large, set to maximum number of labels (5).
        If varLabel > 6 Then
            varLabel = 5
        End If
        For intI = 1 To varLabel
            ' Set text property to alphabet character.
            bal.Labels(intI).Text = Chr(64 + intI)
        Next intI
    End If
    ' Store return value.
    intReturn = bal.Show

    intI = 0
    ' Determine which check boxes were checked, if any.
    For Each bch In bal.Checkboxes
        If bch.Checked = True Then
            strCheck(intI) = bch.Text
            strList = strList & "'" & strCheck(intI) & "'" & Chr(32)
        End If
        intI = intI + 1
    Next
    If Len(strList) <> 0 Then
        MsgBox "You selected checkboxes " & strList & "."
    End If
    ' Determine which label was selected, if any.
    If intReturn > 0 Then
        MsgBox "You selected label " & bal.Labels(intReturn).Text & "."
    End If
End Function

You could call this function from the Debug window as follows:

? AssistantBalloon(4, 5)


Copying a Command Bar Example

The following example copies a command bar and its controls to a new command bar. You enter the name of the command bar you want to copy and the name for the new command bar in the EnterNewName procedure. This procedure calls the general function CopyCommandBar, which uses the names you entered to create the new command bar.

Sub EnterNewName()
    CopyCommandBar "Menu Bar", "New Menu Bar"
End Sub

Function CopyCommandBar(strOrigCBName As String, _
        strNewCBName As String) As Boolean
    ' This procedure copies command bar named in
    ' strOrigCBName variable to new command bar
    ' named in strNewCBName variable.
    Dim cbrOriginal As CommandBar, intOrigCount As Integer
    Dim cbrCopy As CommandBar, cbrCtl As CommandBarControl

    On Error GoTo CBCopy_Err

    Set cbrOriginal = CommandBars(strOrigCBName)
    intOrigCount = cbrOriginal.Controls.Count
    Set cbrCopy = CommandBars.Add(strNewCBName)
    ' Make sure new command bar is visible.
    cbrCopy.Visible = True

    For Each cbrCtl In cbrOriginal.Controls
        cbrCtl.Copy cbrCopy
    Next cbrCtl
Exit Function

CBCopy_Err:
    MsgBox Err.Description
    Exit Function
End Function


Creating a Custom Command Button Example

The following example creates a custom command button on a specified command bar. You enter the name of the command bar you want to add the command button to and the name for the new button in the SpecifyCommandBarAndButton procedure. This procedure calls the general function CreateCustomButton, which uses the names you entered to add the custom command button to the command bar.

Sub SpecifyCommandBarAndButton()
    CreateCustomButton "Menu Bar", "My custom button"
End Sub

Function CreateCustomButton(strBarName As String, _
        strName As String) As Integer
    Dim cmdBar As CommandBar, cmdBarCustomButton As _
        CommandBarButton

    Set cmdBar = CommandBars(strBarName)
    ' Show command bar if it's not already visible.
    If cmdBar.Visible = False Then cmdBar.Visible = True

    On Error Resume Next

    Set cmdBarCustomButton = cmdBar.Controls(strName)
    If Err <> 0 Then
        ' Custom button doesn't already exist, so create it.
        Set cmdBarCustomButton = cmdBar.Controls _
            .Add(msoControlButton, , , , True)
    End If
    With cmdBarCustomButton
        .Caption = strName
        .BeginGroup = True
        .OnAction = "=msgbox(""Hello World"")"
        ' Run your macro or custom function here.
        .Style = msoButtonCaption
    End With
End Function


HTML template file example

<HTML>

<!--The following token places the object name in the title bar of the Web browser.-->

<TITLE><!--AccessTemplate_Title--></TITLE>

<!--The following HTML tag creates a different background color than the Web browser default.-->

<BODY BACKGROUND = "gray.jpg">

<!--The following token places all object output inside the <BODY> tag.-->

<!--AccessTemplate_Body-->

</BODY>

<BR><BR>

<!--The following four tokens create four navigation text buttons that jump to the first, previous, next, and last pages of a report.-->

<A HREF = "<!--AccessTemplate_FirstPage-->">First</A>

<A HREF = "<!--AccessTemplate_PreviousPage-->">Previous</A>

<A HREF = "<!--AccessTemplate_NextPage-->">Next</A>

<A HREF = "<!--AccessTemplate_LastPage-->">Last</A>

<!--The following token inserts the text "Page n" , where n is the current report page number.-->

<P ALIGN = CENTER>Page <!--AccessTemplate_PageNumber-->.</P>

<!--The following HTML tag adds a company logo to the bottom of the Web page.-->

<IMG SRC = "company_logo.jpg">

</HTML>


AccessError Method 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
        ErrorString = AccessError(lngError)
    ElseIf Err.Description = "" Then
        MsgBox "No error string associated with this number."
    Else
        ErrorString = Err.Description
    End If
End Function


 Choose Function

Choose Function

You can also use the Choose function in a calculated control on a Microsoft Access form or report. For example, you can use the Choose function to set the value of a control based on the value of another field. Set the ControlSource property of the control to an expression containing the Choose function. The expression in the following example can be used to set the ControlSource property of a control based on the value of a field called ShipVia in an Orders table.

=Choose([ShipVia], "Speedy", "United", "Federal")

    In the preceding example, if ShipVia contains 1, the Choose function returns the first string, "Speedy". If it contains 2, the function returns the second string, "United", and so on. If ShipVia contains 0, the Choose function returns a Null.

    The next example shows how you can ensure that a string is returned even if the field contains 0.

    =Choose([ShipVia] + 1, "none", "Speedy", "United", "Federal")

      Note In a Visual Basic module, you can use the more full-featured Select Case statement to return a value from a set of several choices.


Choose Function Example

You can use the Choose function to create a calculated control whose value is determined by the value of a field in a table in your database. For example, suppose you have a Shippers table that contains a field called ShipperID. You could create a calculated control on a form to display a text name for the shipper based on the value of the ShipperID field.

=Choose([ShipperID], "Speedy", "United", "Federal")


 Command Function

Command Function

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've 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()


Command Function Example

The following example shows how to launch Microsoft Access with a command-line argument, then shows how to return the value of this argument 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 If
End Function

When you call this function, Microsoft Access will open the Orders form.

You can create a macro named AutoExec to call this function automatically when the database is opened. For more information on carrying out an action when a database opens, see Carry out an action when my database first opens.


DateAdd Function Example

The following example shows how you can create a calculated control by using the DateAdd function to display the date by which a particular order must be shipped — in this case, thirty days after the OrderDate. Suppose you have a form based on an Orders table, with a field called OrderDate. You can create another text box on the form to display the shipping date by setting the ControlSource property of this text box as in the following example.

= DateAdd("d", 30, [OrderDate])


DateDiff Function Example

The following examples use the DateDiff function to calculate the number of calendar weeks between the first of the year and today, and the number of days since February 1, 1995 respectively.

Debug.Print DateDiff("ww", "1-1", Now())
Debug.Print DateDiff("y", #1-Feb-1995#, Now())

The next example shows how to use the DateDiff function in a query expression. Suppose you have an Orders table that contains an OrderDate field and a ShippedDate field. You can create a calculated field in a query to display the time elapsed between an order date and a shipped date for each order. In the Query window, create a new query by adding the Orders table and dragging the OrderID field to the query design grid. In an empty Field cell, enter the following to create a calculated field.

DaysElapsed: DateDiff("y", [OrderDate], [ShippedDate])


DatePart Function Example

The following example uses the DatePart function to specify criteria for a select query. For example, suppose you want to create a query based on an Orders table to list all orders placed in the first quarter of 1996. Assuming your Orders table has a OrderID field and an OrderDate field, you can drag the OrderID field to the first cell in the query design grid, and enter the following in the Criteria cell beneath it.

(DatePart("q", [OrderDate]) = 1) and (DatePart("yyyy", [OrderDate]) = 1996)


 Date Function

Date Function

You can insert the current date on a form or report by clicking Date and Time on the Insert menu. This command creates a text box on a form or report and sets the ControlSource property of the text box to an expression containing the Date function. This expression will vary according to the format you have chosen to display the date. This command is available only in form Design view and report Design view.

You can also use the Date function in a query expression or in a macro. However, you must include the parentheses after the function when you use it anywhere other than a Visual Basic module, as in the expression Date().


DateSerial, Day, Month, and Year Function Example

DateSerial, Day, Month, and Year Function Examples

The following example uses the DateSerial function together with the Year, Month, and Day functions to return the number of days in a month. You can pass either a date or a string to the DaysInMonth function.

Function DaysInMonth(dteInput As Date) As Integer
    Dim intDays As Integer

    ' Add one month, subtract dates to find difference.
    intDays = DateSerial(Year(dteInput), _
        Month(dteInput) + 1, Day(dteInput)) _
        DateSerial(Year(dteInput), _
        Month(dteInput), Day(dteInput))
    DaysInMonth = intDays
    Debug.Print intDays
End Function

The following Sub procedure shows several different ways that you might call the DaysInMonth function.

Sub CallDaysInMonth()
    Dim intDays As Integer
    intDays = DaysInMonth(#4/1/96#)
    intDays = DaysInMonth("4-1-96")
    intDays = DaysInMonth("April 1, 1996")
End Sub


Date Function Example

You can use the Date function in a calculated control by setting the ControlSource property of the control as in the following example.

= Date()

You can also use the Date function to set criteria for a query. For example, if you have an Orders table that contains an OrderDate field, you can create a query on the Orders table to return all records that have an OrderDate between 4-1-95 and today's date. Enter the following in the Criteria cell under the OrderDate field.

Between #4-1-95# and Date()


DAvg 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 Double
dblX = 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 String
strCountry = "UK"
dblX = DAvg("[Freight]", "Orders", _
    "[ShipCountry] = '" & strCountry & "'OR _
    [ShippedDate] >= #1-1-96#")


DCount 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#")


 Different Formats for Different String Values (Format Function)

Different Formats for Different String Values (Format Function)

In Microsoft Access versions 1.x and 2.0, you could use the Format function to return one value for a zero-length string and another for a Null value. For example, you could use a format expression such as the following with the Format function to return the appropriate string value from code:

Dim varX As Variant, varStrX As Variant
' Assign some value to varStrX and pass to Format function.
varX = Format(varStrX, "@;ZLS;Null")

In Microsoft Access 97 and Microsoft Access 2000, you must test separately for the Null case, then return the appropriate value based on the result. For example, you could use the IIf function in an expression with the Format function such as the following:

varX = IIf(IsNull(varStrX),"Null", Format(varStrX, "@;ZLS"))

This change applies only when you use the Format function to format a string dependent on whether it's a zero-length string or a Null value. Other format expressions used with the Format function continue to work as they did in previous versions.

If you convert a database from Microsoft Access version 1.x or 2.0 to Microsoft Access 2000, you'll need to change code to test separately for the Null case.


DLookup Function 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 Variant
varX = 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 Variant
varX = DLookup("[CompanyName]", "Shippers", "[ShipperID] = " _
    & Forms!Shippers!ShipperID)

The next example uses a variable, intSearch, to get the value.

Dim intSearch As Integer, varX As Variant
intSearch = 1
varX = DLookup("[CompanyName]", "Shippers", _
    "[ShipperID] = " & intSearch)


DMin, DMax Functions 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 Currency
curX = DMin("[Freight]", "Orders", "[ShipCountry] = 'UK'")
curY = DMax("[Freight]", "Orders", "[ShipCountry] = 'UK'")

In the next example, the criteria argument includes the current value of a text box called OrderDate. The text box is bound to an OrderDate field in an Orders table. Note that the reference to the control 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 Currency
curX = DMax("[Freight]", "Orders", "[OrderDate] = #" _
    & Forms!Orders!OrderDate & "#")

In the next example, the criteria expression includes a variable, dteOrderDate. Note that number signs (#) are included in the string expression, so that when the strings are concatenated, they will enclose the date.

Dim dteOrderDate As Date, curX As Currency
dteOrderDate = #3/30/95#
curX = DMin("[Freight]", "Orders", _
    "[OrderDate] = #" & dteOrderDate & "#")


DoEvents Function

In Microsoft Access, the DoEvents function is ignored if you use it in:

  • A user-defined function or a procedure that calculates a field in a query, form, or report.

  • A user-defined function that creates a list to fill a combo box, a list box, or an OLE object.

If you include the DoEvents function in any of these, Microsoft Access will not relinquish control to the operating system.


DoEvents Function Example (Microsoft Access)

The following example uses the DoEvents function to return control to the operating system while a loop is executing. The DoEvents function always returns 0.

Sub LongLoop()
    Dim intI As Integer

    For intI = 1 To 1500             ' Start loop.
        If intI Mod 100 = 0 Then    ' If loop has repeated
                                            ' 100 times.
            DoEvents                        ' Yield to operating
                                            ' system.
            Debug.Print intI
        End If
    Next intI                            ' Increment loop counter.
End Sub


DStDev, DStDevP Functions 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 Double
strCountry = "UK"
dblX = DStDev("[Freight]", "Orders", _
    "[ShipCountry] = '" & strCountry & "'")
dblY = DStDevP("[Freight]", "Orders", _
    "[ShipCountry] = '" & strCountry & "'")


DSum Function 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 Currency
curX = 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 Currency
curX = DSum("[Freight]", "Orders", _
    "[ShipCountry] = 'UK' AND [ShippedDate] > #1-1-95#")

You can use a domain function in the Update To row of an update query. For 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 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 Example

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 Double
strCountry = "UK"
dblX = DVar("[Freight]", "Orders", "[ShipCountry] = '" _
    & strCountry & "'")


Eval Function Example

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

Sub CallSeries()
    Dim intI As Integer

    For intI = 1 To 50
        Eval("A" & intI & "()")
    Next intI
End Sub

The next example triggers a Click event as if the user had clicked a button on a form. If the value of the button's OnClick property begins with an equal sign (=), signifying that it is the name of a function, the Eval function calls the function, which is equivalent to triggering the Click event. If the value 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!HelpButton
If (Left(ctl.OnClick, 1) = "=") Then
    varTemp = Eval(Mid(ctl.OnClick,2))
Else
    DoCmd.RunMacro ctl.OnClick
End If


Fix Function

If you use the Fix function to create a new field in a make-table query, the data type of the new field will be dbDouble. You can determine the data type using the DAO Type property.


GUIDFromString 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


 IIf Function

IIf Function

You can also use the IIf function (immediate if) in a calculated control on a Microsoft Access form or report. You can use the IIf function to evaluate an expression and return either of two other values, depending on whether the expression evaluates to True (–1) or False (0). For example, you can use the IIf function to inspect a field on a form and determine whether its value is Null. If it is, you can force the function return an empty string. If the field has a value that is not Null, the function could return the field's contents.

The following example checks the ShipCountry field in an Orders table, and returns an empty string if it is Null.

=IIf(IsNull(Forms!Orders![ShipCountry]), "", _
     Forms!Orders![ShipCountry])

In Visual Basic, the IIf function evaluates both truepart and falsepart, even though it returns only one of them. In a Microsoft Access form or report, however, the IIf function evaluates either truepart or falsepart, whichever is appropriate. Therefore, you need not be concerned about the undesirable side effects of evaluating both arguments if you use the IIf function in a calculated control, query expression, or macro.

Note The Microsoft Access Nz function converts Null values to zero, a zero-length string, or another value that you specify. If your expression handles Null values, you may be able use the Nz function as an alternative to the IIf function.

The IIf function is most useful within expressions that are in a form or report, rather than in Visual Basic code. In Visual Basic, the more full-featured If...Then...Else statement offers greater versatility.


IIf Function Example

This example uses the IIf function to evaluate an OrderAmount field and returns the word "Large" if the amount is greater than 1000; otherwise, it returns the word "Small". You can enter the following expression in the ControlSource property of a calculated control.

= IIf([OrderAmount] > 1000, "Large", "Small")


InputBox Function

You can't open a Help file from a dialog box created by the InputBox function in Microsoft Access. If you specify values for the helpfile and context arguments, they will be ignored, and no Help button appears on the input box. However, Microsoft Access won't generate an error.


InputBox Function Example

The following example uses the InputBox function to return the user's name. Note that you can't open a Help file from a dialog box created by the InputBox function in Microsoft Access.

Sub Greeting()
    Dim strInput As String, strMsg As String

    strMsg = "Enter your name."
    strInput = InputBox(Prompt:=strMsg, _
        Title:="User Info", XPos:=2000, YPos:=2000)
    MsgBox "Hello, " & strInput
End Sub


IsDate Function Example

The following example prompts the user for a string value, uses the IsDate function to determine whether the string can be converted to a date, and then displays an appropriate message.

Sub CheckDate()
    Dim strDate As String

    strDate = InputBox("Enter string to display as a date.")
    ' Test variable.
    If IsDate(strDate) Then
        ' If string is date, format and display in dialog.
        MsgBox "The date is: " & Format(DateValue(strDate), _
            "Long Date")
    Else
        MsgBox "The value you entered is not a date."
    End If
End Sub


IsNull Function Example

The following example uses the IsNull function to determine whether the value of a control is Null. If it is, a message prompts the user to enter data. If the value is not Null, a message displays the value of the control.

Sub ControlValue(ctlText As Control)
    Dim strMsg As String

    ' Check that control is text box.
    If ctlText.ControlType = acTextBox Then
        ' If value of control is Null, prompt for data.
        If IsNull(ctlText.Value) Then
            strMsg = "No data in the field '" & ctlText.Name _
                    & "'." & vbCrLf & "Please enter data for " _
                    & "this field now."
                If MsgBox(strMsg, vbQuestion) = vbOK Then
                    Exit Sub
                End If
        ' If value is not Null, display value.
        Else
            MsgBox (ctlText.Value)
        End If
    End If
End Sub


IsObject Function Example

The following example uses the IsObject function to check whether an argument passed to the function is an object.

Sub CheckObject(varAny As Variant)
    Dim varX as Variant

    If IsObject(varAny) Then
        Set varX = varAny
    Else
        varX = varAny
    End If
End Sub


LoadPicture Method Example

The following example uses the LoadPicture method to load a metafile into an ActiveX control on an Employees form.

Sub DisplayGraphic()
    Const strConPathToBitmaps = "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 = objPicture
End Sub


 MsgBox Function

MsgBox Function

You can use the MsgBox function in Microsoft Access to create a formatted error message similar to built-in error messages displayed by Microsoft Access.

Note In Acc9TBD, this function does not permit you to separate a string into sections with the at sign (@).

The following example displays a formatted dialog box with a sectioned string.

MsgBox "Wrong button!" & chr(13) _
    & "This button doesn't work." & chr(13) –
    & "Try another.", vbOKOnly + vbExclamation

Note To display a message box without an icon in Microsoft Access, simply omit any constant that would denote an icon, or supply a value of zero for the buttons argument, as in the following example.

    MsgBox "No icons included.", 0


MsgBox Function Example

The following example uses the MsgBox function to create a formatted error message in Microsoft Access. Note the use of the at sign (@) to denote the different sections of the string.

Sub CustomMessage()
    Dim strMsg As String, strInput As String

    ' Initialize string.
    strMsg = "Number outside range.@You entered "
        & "a number that is less than 1 or greater "
        & "than 10.@Press OK to enter the number "
        & "again."
    ' Prompt user for input.
    strInput = InputBox("Enter a number between 1 "
        & "and 10.")
    ' Determine if user chose "Cancel".
    If strInput <> "" Then
        ' Test value of user input.
        Do While strInput < 0 Or strInput > 10
            If MsgBox(strMsg, vbOKCancel, "Error!") = _
                    vbOK Then
                strInput = InputBox("Enter a number between 1 and 10.")
            Else
                Exit Sub
            End If
        Loop
        ' Display user's correct input.
        MsgBox "You entered the number " & strInput & "."
    Else
        Exit Sub
    End If
End Sub


Now Function Example

You can use the Now function in a calculated control to return the current system date and time. For example, you can create a text box and set its ControlSource property to the following expression.

= Now()


Nz Function Example

The following example evaluates a control on a form and returns one of two strings based on the control's value. If the value of the control is Null, the procedure uses the Nz function to convert a Null value to a zero-length string.

Sub CheckValue()
    Dim frm As Form, ctl As Control
    Dim varResult As Variant

    ' Return Form 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 varResult
End Sub


Partition Function Example

Partition Function Example(MDB)

You can use the Partition function in the query design grid as well as in the SQL view of the Query window. In the query design grid, you can use the Partition function in a calculated field or to specify criteria for a select query.

The following example shows how you can use the Partition function to create a calculated field that lists how many records fall into each specified range. Suppose you have an Orders table that contains a Freight field. In the Query window, create a new Totals query by adding the Orders table and clicking on the Totals button in the Query command bar. Drag the Freight field to the first Field cell on the query design grid, and set the value of the Total cell to Count. In another field cell, enter the following expression.

Range: Partition([Freight], 0, 1000, 50)

Set the Total cell below this field to Group By, and run the query. The Partition function returns eleven ranges (0:99, 100:199, 200:299, and so on). The query shows the number of orders with freight charges falling into each range.

The next example shows how you can use the Partition function in the SQL view of the Query window. It creates a crosstab query that evaluates a Freight field in an Orders table. It calculates the number of orders for each customer for which freight cost falls within one of several ranges. The ranges are defined by the arguments to the Partition function: start = 0, stop = 1000, interval = 50.

Enter the following expression in SQL view. When you run this query, each range will appear as a column heading.

TRANSFORM Count(Orders.[OrderID]) AS [CountOfOrderID]
SELECT Orders.[CustomerID]
FROM Orders
GROUP BY Orders.[CustomerID]
PIVOT Partition(Int([Freight]), 0, 1000, 50);


StringFromGUID 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


 Switch Function

Switch Function

You can also use the Switch function in a calculated control on a Microsoft Access form or report. For example, you can use the Switch function to set the value of a control based on the value of another field. Set the ControlSourceproperty of the control to an expression containing the Switch function.

In the following example, the Switch function returns a string that is the name of a shipper based on the value of the Freight field. If the value of the Freight field is less than $25, the Switch function returns "Speedy"; if it is greater than or equal to $25 but less than or equal to $50, the Switch function returns "United"; if it is greater than $50, the Switch function returns "Federal".

=Switch([Freight] < 25, "Speedy", ([Freight] >= 25 _
     and [Freight] <= 50), "United", [Freight] > 50, _
     "Federal")

Note In Visual Basic code, you may want to use the more full-featured Select Case statement to return a value from a set of several choices.


Switch Function Example

The following example uses the Switch function to determine the appropriate language for a specified city based on the values of the ShipCountry and ShipCity fields in an Orders table. You can enter the following expression in a calculated control on a form or report. The expression is shown on multiple lines for clarity; you can also enter it on a single line.

= Switch([ShipCity] = "Madrid", "Spanish", _
    [ShipCity] = "Berlin", "German", _
    [ShipCity] = "Torino", "Italian", _
    [ShipCountry] = "France", "French", _
    True, "English")

If the city is Madrid, the Switch function returns "Spanish"; if it is Berlin, it returns "German"; and so on. If the city is not one of those listed, but the country is France, it returns "French". If the city in question is not in the list, the Switch function returns "English".


Timer Function Example

You can use the Timer function to time operations and events in your Microsoft Access application by placing the Timer function immediately before and after the operation in your code that you wish to time. The following example uses the name of a query as its argument, then calculates how long it takes the query to run.

Sub QueryTimer (strQueryName As String)
    Dim sngStart As Single, sngEnd As Single
    Dim sngElapsed As Single

    sngStart = Timer                            ' Get start time.
    DoCmd.OpenQuery strQueryName, acNormal    ' Run query.
    sngEnd = Timer                                ' Get end time.
    sngElapsed = Format(sngEnd - sngStart, "Fixed")
    ' Elapsed time.
    MsgBox ("The query " & strQueryName & " took " & sngElapsed _
        & " seconds to run.")
End Sub


 Time Function

Time Function

You can insert the current time on a form or report by clicking Date and Time on the Insert menu. This command creates a text box on a form or report and sets the ControlSource property of the text box to an expression containing the Time function. This expression will vary according to the format you have chosen to display the time. This command is available only in form Design view and report Design view.

You can also use the Time function in a query expression or in a macro. However, you must include the parentheses after the function when you use it anywhere other than in a Visual Basic module, as in the expression Time().


Time Function Example

You can use the Time function in a calculated control to return the current system time. For example, you can create a text box and set its ControlSource property to the following expression.

= Time()


TypeName Function Example

The following example creates several object variables and passes them to the TypeName function.

Sub ObjectTypes()
    Dim dbs As Database, tdf As TableDef
    Dim fld As Field

    ' Get current database.
    Set dbs = CurrentDb
    ' Return TableDef object pointing to Orders table.
    Set tdf = dbs.TableDefs("Orders")
    ' Return Field object pointing to OrderDate field.
    Set fld = tdf.Fields("OrderDate")
    ' Print value returned by TypeName for each object.
    Debug.Print TypeName(dbs)
    Debug.Print TypeName(tdf)
    Debug.Print TypeName(fld)

End Sub


 Add an action to a macro

Add an action to a macro

  1. In the Macro window, click the first empty row in the Action column. If you want to insert an action between two action rows, click the selector for the action row just below the row where you want to insert the new action, and then click Insert Row [image] on the toolbar.

  2. In the Action column, click the arrow to display the action list.

  3. Click the action you want to use.

  4. Type a comment for the action. Comments are optional.

  5. In the lower part of the window, specify arguments for the action, if any are required. For tips on setting action arguments, click [image] .

Tip For action arguments whose settings are a database object name, you can set the argument by dragging the object from the Database window to the action's Object Name argument box. For example, you can set the SelectObject action's Object Name argument to the name of a form by dragging the form to the argument box. To do this, click Tile Vertically on the Windows menu to position the Macro window and Database window so that they're side by side on your screen; in the Database window under Objects, click the object type you want, click the object, and then drag it to the argument box. Dragging the object also sets the Object Type argument.


 Add the What's This button to a form

Add the What's This button to a form

You might want to use this procedure for a custom dialog box or if you've disabled the title bar for a particular form or removed the What's This button [image] from the title bar for that form.

  1. Open the form in Design view.

  2. Double-click the form selector to display the form's property sheet.

  3. In the WhatsThisButton property box, click Yes.

Note If you haven't specified a custom Help file in the HelpFile property box for the form, the Microsoft Access Help file is displayed when you click the What's This button [image] and then click the form or a control on the form. Find out how to create custom Help for the What's This button.


 Create an unbound check box, option button, or toggle button

Create an unbound check box, option button, or toggle button

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the appropriate tool in the toolbox. If you're not sure which tool to use, place the pointer over the tool until the ToolTip appears.

    Note The toggle button is not available in data access pages.

  3. On the form, report, or data access page, click where you want to place the control. If you're placing the control in an option group on a form or report, Microsoft Access highlights the option group when you move the pointer over it to show that the control will become part of the option group.


Add a column to the design grid in a query or advanced filter

  1. Click anywhere in the column to the left of which you want to add a new column.

  2. On the Insert menu, click Insert Column.


 Create a command button that creates an e-mail message when clicked

Create a command button that creates an e-mail message when clicked

  1. Open a form in Design view.

  2. If the Control Wizards tool [image] in the toolbox is pressed in, click it to turn off the Control Wizard.

  3. In the toolbox, click the Command Button tool Command Button control .

  4. On the form, click where you want to place the command button.

  5. Make sure the command button is selected, and then click Properties [image] on the toolbar to open the property sheet for the command button.

  6. In the HyperlinkAddress property, click the Build button [image] .

  7. In the Insert Hyperlink dialog box, click E-mail Address under Link to.

  8. In the Text to display box, type the display text for the hyperlink. Microsoft Access automatically displays the value of the command button's Caption property in the box.

  9. Click ScreenTip and type the text you want to appear when the user rests the mouse pointer on the hyperlink. If you leave the ScreenTip text box blank, Access displays the e-mail address as the ScreenTip.

  10. In the E-mail address box, type an e-mail address. Or click an address from the Recently used e-mail addresses list.

  11. In the Subject box, type the information you want to appear in the Subject field of the e-mail message.

    Note Some Web browsers and e-mail programs might not recognize the subject line.

  12. Click OK.

    To test the link, right-click the command button, point to Hyperlink on the shortcut menu, and click Open. When you click the hyperlink, Access opens your mail program and creates a new message, with the address and subject filled in.


 Create a command button that's a hyperlink to an existing file or Web page

Create a command button that's a hyperlink to an existing file or Web page

  1. Open a form in Design view.

  2. If the Control Wizards tool [image] in the toolbox is pressed in, click it to turn off the Control Wizard.

  3. In the toolbox, click the Command Button tool Command Button control .

  4. On the form, click where you want to place the command button.

  5. Make sure the command button is selected, and then click Properties [image] on the toolbar to open the property sheet for the command button.

  6. In the HyperlinkAddress property, click the Build button [image] .

  7. In the Insert Hyperlink dialog box, click Existing File or Web Page under Link to.

  8. In the Text to display box, type the display text for the hyperlink. Microsoft Access automatically displays the value of the command button's Caption property in the box.

  9. Click ScreenTip, and type the text you want to appear when the user rests the mouse pointer on the hyperlink. If you leave the ScreenTip text box blank, Access displays the hyperlink address (and subaddress) as the ScreenTip.

  10. Specify the file or Web page you want to go to in one of these ways:
    • In the Type the file or Web page name box, type a path or a URL.

    • Under Or select from list, click Recent files, Browsed pages, or Inserted links. Then click an item in the list.

    • Click File to search for a file on your local machine, a network, or any accessible FTP or HTTP server.

    • Click Web page to search for a page on the Internet or an intranet. When you switch from Microsoft Internet Explorer or other Web browsers to Microsoft Access, Access puts the URL of the currently open Web page in the Type the file or Web page name boxes.
  11. To go to a specific location in an HTML file or to an object in a Microsoft Access database (.mdb) or a Microsoft Access project (.adp), click Bookmark. Click the bookmark or object you want in the list, and then click OK.

  12. Click OK in the Insert Hyperlink dialog box.

    To test the link, right-click the command button, point to Hyperlink on the shortcut menu, and then click Open.


 Create a new data access page and a command button that's a hyperlink to that page

Create a new data access page and a command button that's a hyperlink to that page

  1. Open a form in Design view.

  2. If the Control Wizards tool [image] in the toolbox is pressed in, click it to turn off the Control Wizard.

  3. In the toolbox, click the Command Button tool Command Button control .

  4. On the form, click where you want to place the command button.

  5. Make sure the command button is selected, and then click Properties [image] on the toolbar to open the property sheet for the command button.

  6. In the HyperlinkAddress property, click the Build button [image] .

  7. In the Insert Hyperlink dialog box, click Create New Page under Link to.

  8. In the Text to display box, type the display text for the hyperlink. Microsoft Access automatically displays the value of the command button's Caption property in the box.

  9. Click ScreenTip, and type the text you want to appear when the user rests the mouse pointer on the hyperlink. If you leave the ScreenTip text box blank, Access displays the hyperlink address as the ScreenTip.

  10. In the Name of new document box, type a name for the page.

    Tip You can create a different type of document, for example, a Word file or and Excel spreadsheet, by typing the three-letter file extension for the type of file you want to create. However, you can't create a Microsoft Access database (.mdb) or a Microsoft Access project (.adp).

  11. Microsoft Access creates the new page in the current folder. To specify a different location, click Change.

  12. Click an option under When to edit. You can edit the new page immediately or wait until later.

  13. Click OK.

    To test the link, right-click the command button, point to Hyperlink on the shortcut menu, and then click Open.


 Create a command button that's a hyperlink to an object in the current database

Create a command button that's a hyperlink to an object in the current database

  1. Open a form in Design view.

  2. If the Control Wizards tool [image] in the toolbox is pressed in, click it to turn off the Control Wizard.

  3. In the toolbox, click the Command Button tool Command Button control .

  4. On the form, click where you want to place the command button.

  5. Make sure the command button is selected, and then click Properties [image] on the toolbar to open the property sheet for the command button.

  6. In the HyperlinkAddress property, click the Build button [image] .

  7. In the Insert Hyperlink dialog box, click Object in This Database under Link to.

  8. In the Text to display box, type the display text for the hyperlink. Microsoft Access automatically displays the value of the command button's Caption property in the box.

  9. Click ScreenTip, and type the text you want to appear when the user rests the mouse pointer on the hyperlink. If you leave the ScreenTip text box blank, Access displays the hyperlink subaddress as the ScreenTip.

  10. Click the database object you want to go to from the list.

  11. Click OK.

    To test the link, right-click the command button, point to Hyperlink on the shortcut menu, and then click Open.

Note To link to an object in another database, create a link to the database file and then click Bookmark to select the object.


 Add a database object to a group

Add a database object to a group

  1. If you haven't already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  2. Right-click the database object you want to add to your group. You can also right-click a shortcut in one group to add it to another group.

  3. On the shortcut menu, point to Add to Group, and then click the name of the group you want to add the object to.

Notes

  • Adding an object to a group creates a shortcut to the object in that group, but it doesn't affect the object's actual location. For example, if you add a form to your group, and then click Forms [image] under Objects in the Database window, that form still appears in the list of all forms.

  • You can also add an object or a shortcut to a group by dragging it from the Object list to the icon for the group you want to add it to.


 Add an existing report to another existing report to create a subreport

Add an existing report to another existing report to create a subreport

If the subreport will be linked to the main report, make sure you've set up the table relationships correctly before using this procedure. For more information, click [image] .

  1. Open the report you want to use as the main report in Design view.

  2. Make sure the Control Wizards tool [image] in the toolbox is pressed in.

  3. Press F11 to switch to the Database window.

  4. Drag a report or datasheet from the Database window to the section you want the subreport to appear in on the main report.

Microsoft Access adds a subreport control to the report.

Notes

  • For information on referring to the value of a control on a subreport, click [image] .

  • For information on troubleshooting subreports, click [image] .


 Add fields to the design grid in a query or advanced filter

Add fields to the design grid in a query or advanced filter

In a query, you add only those fields whose data you want to view, set criteria on, group by, update, or sort. In an advanced filter, you add only the fields you want to use for sorting or specifying criteria, and Microsoft Access will automatically display all the fields in the filtered results.

  1. Open a query in Design view, or open a form or datasheet and display the Advanced Filter/Sort window.

  2. In a query, make sure the field list for the table or query containing the fields you want to add appears in the top portion of the window. You can add a table or query if the field list you need isn't in the query.

    How?

    In the Advanced Filter/Sort window, Microsoft Access displays the field list for the underlying table, query, or SQL statement automatically. You can't add more tables or queries to this window.

  3. Select one or more fields from the field list and drag them to the columns in the grid.

    How?


Add or modify a sort order

What do you want to do?

Sort records using the design grid of a query

Specify a sort order when using the asterisk in the design grid

Read about issues to consider when sorting records

Remove a sort order from a table, query, or form


 Create a form with more than one page (screen)

Create a form with more than one page (screen)

  1. Open the form in Design view.

  2. Click the Page Break tool [image] in the toolbox.

  3. Click the form where you want to place the page break. Place the page break above or below a control to avoid splitting data in that control.

    Microsoft Access marks the page break on the left border of the form with a short dotted line.

    Note If you want each page to be the same size, and each window to show only one page at a time, design the form so that each page break is an equal distance from the other. You can do this by positioning the page break controls with the vertical ruler.

  4. Double-click the form selector to open the property sheet, and click Current Page in the Cycle property box. When the Cycle property is set to Current Page, you can't press the TAB key to move between pages.

  5. Remove the vertical scroll bar by setting the ScrollBars property to Horizontal Only or Neither.

  6. Switch to Form view to test the form and size it so you can only see one page at a time. You can press the PAGE DOWN or PAGE UP keys to move between pages.

Notes

  • You may also want to set other properties in Design view. For example, you may want to set the BorderStyle property to Thin so that the form can't be sized, and you may want to set the MinMaxButtons property to None so that the form doesn't have Minimize and Maximize buttons. Also, you might want to add a command button to each page that you can use to move the focus to the next or previous page. The Employees (page break) form in the Northwind sample database has an example of this type of command button. To view this form, open the Northwind database in your Office folder's Samples folder and then open the Employees (page break) form in Design view.

  • A page break is active in Form view only when the DefaultView property of the form is set to Single Form.

  • For forms used in Form view, a page break marks where the form will scroll to when PAGE UP or PAGE DOWN is pressed. For printed forms, a page break marks the start of a new page within a section. To start a page at the beginning of a section, use the section's ForceNewPage property.


 Create a picture that creates an e-mail message when clicked

Create a picture that creates an e-mail message when clicked

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. On a form or report, click the Image tool Image frame control in the toolbox. On a data access page, click the Hotspot Image tool Hotspot Image control .

  3. Click where you want to create the picture.

  4. In the Insert Picture dialog box, locate the picture that you want to use, and then click OK.

    Microsoft Access adds an image control to the form or report.

    Note If you are creating a hotspot image on a data access page, skip to step 6.

  5. On the form or report, make sure the image control is selected, and then click Properties [image] on the toolbar to open the property sheet for the control.

  6. In the HyperlinkAddress property, click the Build button [image] to open the Insert Hyperlink dialog box.

  7. In the Insert Hyperlink dialog box, click E-mail address under Link to.

  8. Click ScreenTip, and type the text you want to appear when the mouse pointer hovers over the hyperlink. If you leave the ScreenTip text box blank, then Microsoft Access will display the e-mail address as the ScreenTip.

  9. In the E-mail address box, type an e-mail address. Or select an address from the Recently used e-mail addresses list.

  10. In the Subject box, type the information that you want to appear in the Subject field of the e-mail message.

    Note Some Web browsers and e-mail programs might not recognize the subject line.

  11. Click OK.

    To test the link in a form or report, right-click the picture, point to Hyperlink on the shortcut menu, and then click Open. To test the link on a data access page, switch to Page view and click the picture. Microsoft Access opens your mail program and creates a new message, with the address and subject filled in.


 Create a picture that's a hyperlink to an existing file or Web page

Create a picture that's a hyperlink to an existing file or Web page

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. On a form or report, click the Image tool Image frame control in the toolbox. On a data access page, click the Hotspot Image tool Hotspot Image control .

  3. Click where you want to create the picture.

  4. In the Insert Picture dialog box, locate the picture that you want to use, and then click OK.

    Microsoft Access adds an image control to the form or report.

    Note If you are creating a hotspot image on a data access page, skip to step 6.

  5. On the form or report, make sure that the image control is selected, and then click Properties [image] on the toolbar to open the property sheet for the control.

  6. In the HyperlinkAddress property, click the Build button [image] to open the Insert Hyperlink dialog box.

  7. In the Insert Hyperlink dialog box, click Existing file or Web page under Link to.

  8. Click ScreenTip, and type the text that you want to appear when the mouse pointer hovers over the hyperlink. If you leave the ScreenTip text box blank, then Microsoft Access will display the hyperlink address and/or subaddress as the ScreenTip.

  9. Specify the file or Web page that you want to link to in one of these ways:
    • In the Type the file or Web page name box, type a path or a URL.

    • Under Or select from list, click Recent files, Browsed pages, or Inserted links. Then click an item in the list.

    • Click File to search for a file on your local machine, a network, or any accessible ftp or http server.

    • Click Web page to search for a page on the Internet or an intranet. When you switch from Microsoft Internet Explorer or other Web browsers to Microsoft Access, Access puts the URL of the currently open Web page in the Type the file or Web page name box.
  10. To go to a specific location in an HTML file or to an object in a Microsoft Access database (.mdb) or a Microsoft Access project (.adp), click Bookmark. Click the bookmark or object you want in the list, and then click OK.

  11. Click OK in the Insert Hyperlink dialog box.

    To test the link on a form or report, right-click the picture, point to Hyperlink on the shortcut menu, and click Open. To test the link on a page, switch to Page view and click the picture.


 Create a new data access page and a picture that's a hyperlink to that page

Create a new data access page and a picture that's a hyperlink to that page

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. On a form or report, click the Image tool Image frame control in the toolbox. On a page, click the Hotspot Image tool Hotspot Image control .

  3. Click where you want to create the picture.

  4. In the Insert Picture dialog box, locate the picture that you want to use, and then click OK.

    Microsoft Access adds an image control to the form or report.

    Note If you are creating a hotspot image on a data access page, skip to step 6.

  5. On the form or report, make sure that the image control is selected, and then click Properties [image] on the toolbar to open the property sheet for the control.

  6. In the HyperlinkAddress property, click the Build button [image] to open the Insert Hyperlink dialog box.

  7. In the Insert Hyperlink dialog box, click Create new page under Link to.

  8. Click ScreenTip, and type the text you want to appear when the mouse pointer hovers over the hyperlink. If you leave the ScreenTip text box blank, then Microsoft Access will display the hyperlink address and/or subaddress as the ScreenTip.

  9. In the Name of new document box, type a name for the new data access page.

    Tip You can create a different type of document — for example, a Microsoft Word file or a Microsoft Excel spreadsheet — by typing the three-letter file extension for the type of file that you want to create. However, you can't create a Microsoft Access database (.mdb) or a Microsoft Access project (.adp).

  10. Microsoft Access creates the new document in the current folder. To specify a different location, click Change.

  11. Select an option under When to edit. You can edit the new document immediately or wait until later.

  12. Click OK.

    To test the link on a form or report, right-click the picture, point to Hyperlink on the shortcut menu, and then click Open. To test the link on a data access page, switch to Page view and click the picture.


 Create a picture that's a hyperlink to an object in the current database

Create a picture that's a hyperlink to an object in the current database

  1. Open a form in Design view or a report in Design view.

  2. Click the Image tool Image frame control in the toolbox, and then click where you want to create the picture.

  3. In the Insert Picture dialog box, locate the picture you want to use, and then click OK.

    Microsoft Access adds an image control to the form or report.

  4. Make sure that the image control is selected, and then click Properties [image] on the toolbar to open the property sheet for the control.

  5. In the HyperlinkAddress property, click the Build button [image] to open the Insert Hyperlink dialog box.

  6. In the Insert Hyperlink dialog box, click Object in this database under Link to.

  7. Click ScreenTip, and type the text you want to appear when the mouse pointer hovers over the hyperlink. If you leave the ScreenTip text box blank, then Microsoft Access will display the object name as the ScreenTip.

  8. From the list, select the database object that you want to link to.

  9. Click OK.

    To test the link, right-click the picture, point to Hyperlink on the shortcut menu, and then click Open.

Note To link to an object in another database, link to the database file and then click Bookmark to select the object.


 Add an existing form to another existing form to create a form with a subform

Add an existing form to another existing form to create a form with a subform

Before using this procedure, make sure you've set up your table relationships correctly.

  1. Open the form that you want to use as the main form in Design view. This is usually a form based on a table or query on the "one" side of a one-to-many relationship.

  2. Make sure the Control Wizards tool [image] in the toolbox is pressed in.

  3. Press F11 to switch to the Database window.

  4. Drag a form, table, or query from the Database window to the main form.

    Microsoft Access adds a subform control to the form. If you dragged a form displayed in Form view, Microsoft Access displays the subform in that view. If you dragged a form displayed in Datasheet view or a table or query, Microsoft Access displays the subform as a datasheet.

Notes

  • For information on changing the layout of a subform, click [image] .

  • For information on troubleshooting subforms, click [image] .


 Add a table or query to a query

Add a table or query to a query

  1. Open a query in Design view.

  2. On the toolbar, click Show Table [image] .

  3. In the Show Table dialog box, click the tab that lists the objects whose data you want to work with. If the table you need is in another database or application, first link the table to the active database.

    How?

  4. Click the name of the object you want to add to the query. To select additional objects one at a time, hold down CTRL while you click each object name. To select a block of objects, click the first name in the block, hold down SHIFT, and then click the last name in the block.

  5. Click Add, and then click Close.

Notes

  • You can also add a table or query to a query by dragging the table or query name from the Database window to the upper part of query Design view.

  • When you have multiple tables or queries in a query, they need to be joined together. For information on joining tables, click [image] .


 Add a text box or other control to an existing group

Add a text box or other control to an existing group

  1. Open a form in Design view or a report in Design view.

  2. While pressing the SHIFT key, select the control you want to add to the group, and then click any control in the group to select the group.

  3. On the Format menu, click Group.


 Add a watch expression to the Watch window of the Visual Basic Editor

Add a watch expression to the Watch window of the Visual Basic Editor

  1. Open a procedure in the Code window.

  2. On the Debug menu, click Add Watch.

  3. If you already selected an expression in the Code window, it is automatically displayed in the dialog box. If no expression is displayed, type the expression you want to evaluate. The expression can be a variable, a property, a function call, or any other valid expression.

    Instead of typing the expression, you can also select an expression in the Code window and drag it to the Watch window.

  4. To select the range for which the expression will be evaluated, select a module and procedure context under Context.

    Note Select the narrowest scope that fits your needs. Selecting all procedures or all modules could slow down code execution.

  5. To define how the system responds to the watch expression, select an option under Watch Type.
    • To display the value of the watch expression, click Watch Expression.

    • To pause execution if the expression evaluates to True, click Break When Value Is True.

    • To pause execution if the value of the expression changes, click Break When Value Changes.

When you run the code, the Watch window shows the value of the expression you set. To modify a watch expression, select the expression in the Watch window, and then click Edit Watch on the Debug menu. To delete the watch expression, click Delete in the Edit Watch dialog box.


 Change the direction scrolling text moves on a data access page

Change the direction scrolling text moves on a data access page

  1. Open a data access page in Design view.

  2. Select the scrolling text control, and then click Properties [image] on the toolbar to display the control’s property sheet.

  3. Do one of the following:
    • To make the scrolling text move from right to left in the control, click Left in the Direction property box.

    • To make the scrolling text move from left to right in the control, click Right in the Direction property box.

    • To make the scrolling text move from top to bottom in the control, choose Down in the Direction property box.

    • To make the scrolling text move from bottom to top in the control, choose Up in the Direction property box.


 Adjust the size of a picture displayed in an image control on a data access page

Adjust the size of a picture displayed in an image control on a data access page

  1. Open a data access page in Design view.

  2. Select the image control.

  3. Click Properties [image] on the toolbar to display the property sheet.

  4. In the Height and Width property boxes, type the number of pixels (px), centimeters (cm), inches (in), or points (pt) that you want for the height and width of the image that is displayed in the image control.


 Optimize Access database performance by using the Performance Analyzer

Optimize Access database performance by using the Performance Analyzer

You can use the Performance Analyzer to optimize the performance of a Microsoft Access database. You can also optimize the performance of a Microsoft Access project; however, the Performance Analyzer is available only in an Access database.

  1. Open the Access database you want to optimize.

  2. On the Tools menu, point to Analyze, and then click Performance.

  3. Click the tab for the type of database object that you want to optimize. Click the All tab to view a list of all database objects at once.

  4. Select the names of the database objects that you want to optimize. Click Select All to select all database objects in the list.

  5. Repeat steps 3 and 4 until you've selected all the objects you want to optimize, and then click OK.

    The Performance Analyzer lists three kinds of analysis results: Recommendation, Suggestion, and Idea. When you click an item in the Analysis Results list, information about the proposed optimization is displayed in the Analysis Notes box below the list. Suggestion optimizations have potential tradeoffs that you should consider before performing them. To view a description of the tradeoffs, click a Suggestion in the list and then read the information in the Analysis Notes box. Microsoft Access can perform Recommendation and Suggestion optimizations for you. You must perform Idea optimizations yourself.

  6. Click one or more of the Recommendation or Suggestion optimizations you want performed, and then click Optimize. The Performance Analyzer will perform the optimizations and then mark them as Fixed. Continue this process until the Performance Analyzer has completed all Recommendations and Suggestions that you want it to perform.

    To perform all Recommendation and Suggestion optimizations, click Select All, and then click Optimize.

    To perform an Idea optimization, click the optimization, and then follow the instructions displayed in the Analysis Notes box.

Note The Performance Analyzer doesn't provide suggestions on how to improve the performance of Microsoft Access itself or the system it is running on. For additional suggestions on improving performance in other areas not covered by the Performance Analyzer, click [image] .


 Apply a different theme to a data access page

Apply a different theme to a data access page

  1. Open the data access page you want to apply a different theme to in Design view.

  2. On the Format menu, click Theme.

  3. In the Choose a theme list, click the theme you want.


 Apply a theme to an existing data access page

Apply a theme to an existing data access page

  1. Open the data access page you want to apply a theme to in Design view.

  2. On the Format menu, click Theme.

  3. In the Choose a theme list, click the theme you want.

  4. Select the options you want.

    For Help on an option, click the question mark [image] and then click the option.


 Apply a theme to a new data access page

Apply a theme to a new data access page

  1. In the Database window, click Pages [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. In the New Page dialog box, click Page Wizard and follow the instructions in the Wizard.

  4. On the last screen in the Wizard, select the Do you want to apply a theme to your page check box.


 Assign an access key to a label or button on a form or report

Assign an access key to a label or button on a form or report

When you assign an access key to a label or button, you can press ALT + an underlined character to move the focus to the control that is attached to that label, or to the button.

  1. Open a form in Design view or a report in Design view.

  2. Make sure the label or button that you want to assign the access key to is selected, and then click Properties [image] on the toolbar to open the control's property sheet.

  3. In the Caption property box in the property sheet, type an ampersand (&) immediately before the character that you want to use as the access key.


Work with permissions

What do you want to do?

Learn how permissions work and who can assign them

Learn about types of permissions

Assign or remove permissions for a database and existing tables, queries, forms, reports, and macros

Assign default permissions for new tables, queries, forms, reports, and macros

Permit others to view or run my query but not change data or query design

Change default permissions of all new queries

Learn more about the RunPermissions property


 Create a compiled Help file that is displayed when you press F1

Create a compiled Help file that is displayed when you press F1

  1. Create the source file by using the text editor or word-processing program of your choice. For information about creating the source file, see the Help that comes with Microsoft Help Workshop. Make sure to save the source file in Rich Text Format.

  2. Compile the Help file by using Microsoft Help Workshop.

  3. Display the property sheet for the form or report and specify the file name for the compiled Help file in the HelpFile property box.

    Note For best results, put the Help file in the same folder as your application. That way, you can keep the setting for the HelpFile property the same for each site by using your application, but allow users to install the application in the folder of their choice. If you omit a path setting in this property, Microsoft Access looks for the Help file in the folder where your application is installed.

  4. In the HelpContextID property box for the form or report, type the number of the topic (a number other than 0) that will be displayed when a user presses F1. This topic would generally cover assistance for the whole form or report.

  5. In the HelpContextID property box for any control on a form that can receive the focus, type the number of the topic that will be displayed when a user presses F1. This topic would cover assistance specific to the control.

Notes

  • You must map the values set for the HelpContextID property to the context strings in your Help system. For more information, see the Help file that comes with Microsoft Help Workshop.

  • If a control has the focus when you press F1, but it doesn't have a custom Help topic, the custom Help topic for the form will be displayed. If there is no custom Help topic for the form, Microsoft Access displays the Office Assistant dialog box.

  • You can't display custom Help through the Office Assistant.

  • You can also use Microsoft HTML Help Workshop to create a Help file. For more information about creating custom Help, see "Adding Help to Your Custom Solution" in the Microsoft Office 2000/Visual Basic Programmer's Guide. Learn how to obtain a copy of this book.


 Automate importing, exporting, or linking of data by using a macro

Automate importing, exporting, or linking of data by using a macro

  1. Create a macro.

    How?

  2. Do one of the following:

    To import, export, or link data between the current Microsoft Access database and another database, click TransferDatabase in the action list of a blank action row.

    To import, export, or link data between the current Access database and a spreadsheet file, click TransferSpreadsheet in the action list of a blank action row.

    To import, export, or link data between the current Access database and a text file, click TransferText in the action list of a blank action row.

  3. Set the action arguments.

  4. Click Save [image] to save the macro.

  5. Run the macro.

    How?

For more information about the TransferDatabase action, click [image] .

For more information about the TransferSpreadsheet action, click [image] .

For more information about the TransferText action, click [image] .


Automate importing, exporting, or linking of data by using Visual Basic

  1. Create a Visual Basic procedure.

    How?

  2. Do one of the following:

    To import, export, or link data between the current Microsoft Access database and another database, use the TransferDatabase method to carry out the TransferDatabase action in the procedure.

    How?

    To import, export, or link data between the current Microsoft database and a spreadsheet file, use the TransferSpreadsheet method to carry out the TransferSpreadsheet action in the procedure.

    To import, export, or link data between the current Microsoft database and a text file, use the TransferText method to carry out the TransferText action in the procedure.

  3. Run the procedure.

    How?

For more information about the TransferDatabase method, click [image] .

For more information about the TransferSpreadsheet method, click [image] .

For more information about the TransferText method, click [image] .


 Compact an Access database or Access project automatically when you close it

Compact an Access database or Access project automatically when you close it

Microsoft Access can automatically compact a Microsoft Access database or Microsoft Access project every time you close it.

  1. Open the Access database or Access project that you want Microsoft Access to compact automatically.

  2. On the Tools menu, click Options.

  3. Click the General tab.

  4. Select the Compact On Close check box.

Note Compacting does not occur if you close a multiuser (shared) database while another user has it open.


 Automatically view the latest records for a form by using a macro

Automatically view the latest records for a form by using a macro

  1. Create a macro.

    How?

  2. In a blank action row, click Requery in the action list.

    To update records for a control that is based on a table or query, set the Control Name argument to the name of the control. To update the records for the form as a whole, leave the Control Name argument blank.

  3. Click Save [image] to save the macro.

  4. Run the macro.

    How?

For more information about the Requery action, click [image] .


 Automatically view the latest records for a form by using Visual Basic

Automatically view the latest records for a form by using Visual Basic

  1. Create a Visual Basic procedure.

    How?

  2. Add the Requery method to the procedure for the form or control whose records you want to update. For example, to view the latest records in a combo box called CategoryID, add the following method to the procedure:
    CategoryID.Requery

  3. Run the procedure.

    How?

For more information about the Requery method, click [image] .


 Bind a blank form or report to data in a table or other record source

Bind a blank form or report to data in a table or other record source

  1. In form Design view or report Design view, double-click the form selector or the report selector to open the property sheet.

  2. Click the arrow next to the RecordSource property box and select from a list of tables or queries.

  3. Use the field list to add controls bound to the fields in the record source to the form or report.

Switch to Form view or Datasheet view to see the data in the form. Switch to Print Preview to see the data in the report.


 Calculate a sum, average, count, or other total on all the records in a query

Calculate a sum, average, count, or other total on all the records in a query

  1. Create a select query in Design view. Add the tables whose records you want to use in the calculation, and then add the fields on which you want to perform calculations and specify criteria.

  2. Click Totals [image] on the toolbar.

    Microsoft Access displays the Total row in the design grid.

  3. For each field in the design grid, click its cell in the Total row, and then click one of the following aggregate functions: Sum, Avg, Min, Max, Count, StDev, or Var.

    Select aggregate functions in the Total row

    For information on each aggregate function, click [image] . (For special considerations when using the First and Last functions, click

  4. If you want, enter criteria to affect the results of the calculation.

    How?

  5. If you want, sort the results.

    How?

  6. Click View [image] on the toolbar to view the results.

If you didn't get the results you expected, click [image] .

Notes

  • When you use an aggregate function on a field, Microsoft Access combines the function and the field names to name the field in the datasheet (for example, AvgOfFreight). For information on renaming these fields to better indicate their contents, click [image] .

  • If you add a calculated field that includes one or more aggregate functions to a query in which you're calculating totals on all the records, you must set the calculated field's Total cell to Expression.


 Calculate a sum, average, count, or other total on groups of records in a query

Calculate a sum, average, count, or other total on groups of records in a query

  1. Create a select query in Design view. Add the tables whose records you want to use in the calculation, and then add the fields on which you want to perform calculations, define groupings, and specify criteria.

  2. Click Totals [image] on the toolbar.

    Microsoft Access displays the Total row in the design grid.

  3. For the field or fields you want to group on, leave Group By in the Total cell.

  4. For each field you want to calculate, click its cell in the Total row, and then click one of the following aggregate functions: Sum, Avg, Min, Max, Count, StDev, or Var.

    Aggregate function in the Total row

    For information on each aggregate function, click [image] . (For special considerations when using the First and Last functions, click

  5. If you want, enter criteria to affect the results of the calculation.

    How?

  6. If you want, sort the results.

    How?

  7. Click View [image] on the toolbar to view the results.

If you didn't get the results you expected, click [image] .

Notes

  • When you use an aggregate function on a field, Microsoft Access combines the function and the field names to name the field in the datasheet (for example, AvgOfFreight). For information on renaming these fields to better indicate their contents, click [image] .

  • If you add a calculated field that includes one or more aggregate functions in its expression, you must set the calculated field's Total cell to Expression.

  • To create a crosstab query that groups totals down the left and across the top of the datasheet, click [image] .

  • The Category Sales for 1995 query in the Northwind sample database has an example of calculating a sum for groups of records. To view this query, open the Northwind database in your Office folder's Samples subfolder, and then open the Category Sales for 1995 query in Design view. For information on opening Northwind, click [image] .


 Calculate a total or other value for one record on a grouped data access page

Calculate a total or other value for one record on a grouped data access page

  1. Open the data access page in Design view.

  2. If the expression will reference field names, then the fields need to be in the page's data definition. Either add the fields to the page as bound HTML controls, or add the fields as bound text boxes.

    Tip The page will load faster in Page view and in Microsoft Internet Explorer if you use bound HTML controls.

  3. Create another control by clicking the Bound HTML tool Bound HTML control or the Text Box tool Text Box control in the toolbox, and then releasing the mouse button where you want the upper-left corner of the control on the page.

  4. To display the property sheet, make sure that the control is selected, and then click Properties [image] on the toolbar.

  5. In the ControlSource property box, type an alias and an appropriate expression. To reference fields on the page, use the names of the fields in the expression. For example, if you want to compute the extended price for a record in the Order Details table, type:

    ExtendedPrice: UnitPrice*Quantity

    If you don't specify an alias, you must type an equal sign (=) before the expression. Access will automatically supply an alias; for example, Expr1.

Notes

  • If you don't want to display the values in the fields used in the expression in Page view or Internet Explorer, you can hide the controls or delete the controls. Even if you delete the controls after you define the expression, the fields will still be in the page's data definition.

  • If a page is based on a query, you can put the expression in the page's underlying query. If you are going to calculate totals for groups of records, it's easier to use the name of a calculated field.

  • See examples of other expressions you can use to calculate values for one record.

  • Learn more about creating expressions in a Microsoft Access database (.mdb).

  • Learn more about creating expressions in a Microsoft Access project (.adp).

  • To do complex calculations using spreadsheet functions, use the spreadsheet control.


 Change, add, or remove conditional formatting for a control on a form or report

Change, add, or remove conditional formatting for a control on a form or report

  1. Open the form in Design view or Form view, or the report in Design view.

  2. Make sure that the control is selected, and then on the Format menu, click Conditional Formatting.

  3. Do one of the following:
    • To change an existing condition, select the font style, color, or other formatting that you want to apply.

    • To add a new condition, click Add.

    • To remove one or more conditions, click Delete, and then select the check box for the condition or conditions you want to delete.
  4. Click OK.

Note Conditional formatting is not preserved when you output or export a form or a report to another file format.


 Change the color of the control that has focus on a form

Change the color of the control that has focus on a form

  1. Open the form in Design view or Form view.

  2. Make sure that the control is selected, and then, on the Format menu, click Conditional Formatting.

  3. In the Condition x area of the Conditional Formatting dialog box, click Field Has Focus in the first box.

  4. Select the font style, color, or other formatting that you want the field to have when it has focus.

Note When you open the Conditional Formatting dialog box, it displays the current default formatting for the selected control, including colors, font styles, and any expressions that you may have defined for the field.


 Change a column's width in the design grid of a query or advanced filter

Change a column's width in the design grid of a query or advanced filter

  1. In query Design view or in the Advanced Filter/Sort window, move the pointer to the right edge of the column selector for the column you want to change, until the pointer turns into a two-way arrow.

  2. Drag the edge to the left to make the column narrower or to the right to make it wider (or double-click to adjust the width to the longest visible entry in the design grid).

    Drag a column's right edge to change the column's width

Notes

  • To adjust the width of several columns at once, select the columns by dragging across their column selectors, and then use the preceding procedure.

  • Adjusting column widths in Design view or in the Advanced Filter/Sort window has no effect on the column width in the query or filtered datasheet.


 Change the default control style for new controls using an existing control in a form or report

Change the default control style for new controls using an existing control in a form or report

  1. Open a form in Design view or a report in Design view.

  2. Select the control that has the characteristics that you want to use as defaults.

  3. On the Format menu, click Set Control Defaults.

    Microsoft Access sets the default properties for that type of control based on the control you selected.

Tip You can copy formatting characteristics from one control to another by clicking Format Painter [image] on the toolbar. For more information, click [image] .


 Change the default control style for new controls using the property sheet in a form or report

Change the default control style for new controls using the property sheet in a form or report

  1. Open a form in Design view or a report in Design view.

  2. In the toolbox, click the tool for the type of control that you want to change. For example, if you want to change the default control style for text boxes, click the Text Box tool Text Box control .

  3. Display the property sheet by clicking Properties [image] on the toolbar.

    Microsoft Access changes the title bar of the property sheet to indicate that you've opened the default property sheet for that type of control.

  4. In the property sheet, change the property settings.


Change which switchboard automatically displays when you open the database

  1. Open the database.

  2. Do one of the following to open the Switchboard Manager dialog box:
    • If you created the switchboard by using the Database Wizard, click Change Switchboard Items in the opening switchboard.

    • If you created the switchboard by using the Switchboard Manager, click Add-ins on the Tools menu, and then click Switchboard Manager.
  3. If the switchboard that you want to use as the opening switchboard is displayed in the Switchboard Pages box, click it. Otherwise, create the switchboard.

    How?

  4. Click Make Default.

    The next time you open your database, Microsoft Access will automatically display the switchboard you specified.


Make a change to an existing switchboard

  1. Open the database.

  2. Do one of the following to open the Switchboard Manager dialog box:
    • If you created the switchboard by using the Database Wizard, click Change Switchboard Items in the opening switchboard.

    • If you created the switchboard by using the Switchboard Manager, click Add-ins on the Tools menu, and then click Switchboard Manager.
  3. Click the switchboard you want to edit, and then click Edit.

  4. Click the item on the switchboard you want to change, and then do one of the following:
    • To change the text of the item, the command performed by the item, or the object that's opened or run when you click the button, click Edit.

    • To add an item, click New, type the text for the item, and then click a command in the Command box. Depending on which command you click, Microsoft Access displays another box below the Command box. Click an item in this box, if necessary. For example, if you click one of the form commands in the Command box, click the name of the form you want to open.

    • To delete an item, click Delete.

    • To move an item, click Move Up or Move Down.
  5. When you've finished changing items, click Close.


 Change a field's caption in a query

Change a field's caption in a query

  1. Open a query in Design view.

  2. In the design grid, click anywhere in the column of the field whose caption you want to change, and then click Properties [image] on the toolbar.

  3. In the Caption property box, type the new caption for the field.


 Change a field name in Datasheet view

Change a field name in Datasheet view

  1. Open the table in Datasheet view.

  2. Double-click the field selector of the field that you want to change.

    Note If the Caption property has been set for this field, the text displayed in the field selector may be different from the actual field name. In this case, when you double-click the field selector, the caption text will be cleared and replaced with the field name. If you continue, you'll be editing the field name, and when you press ENTER to save this change, the caption text will be deleted. If you don't want to delete the caption text, press ESC immediately after double-clicking the field selector to cancel editing. For more information on using the Caption property, click [image] .

  3. Type the new field name, following Microsoft Access object-naming rules.

  4. Press ENTER to save the new name.

Caution If you have expressions or Visual Basic for Applications code that contain references to a field whose name you are changing, you must update all of those references to the new name.


 Change a field name in Design view

Change a field name in Design view

  1. Open the table in Design view.

  2. Double-click the field name you want to change.

  3. Type the new field name, following Microsoft Access object-naming rules.

  4. Click Save [image] on the toolbar to save your changes.

Caution If you have expressions, or Visual Basic for Applications code that contain references to a field whose name you are changing, you must update all of those references to the new name.


 Change the format of data in a text box or other control in a form or report

Change the format of data in a text box or other control in a form or report

  1. Open a form in Design view or a report in Design view.

  2. Make sure the control is selected, and then click Properties [image] on the toolbar to open its property sheet.

  3. In the Format property box, click one of the predefined formatting settings. You can create your own format if a predefined format doesn't meet your needs. For more information, click [image] .

Notes

To ensure consistency among applications, Microsoft Access uses the regional settings that are specified in Microsoft Windows Control Panel for some predefined Number and Date/Time formats. For more information, click [image] .

For controls that display numbers, you may also want to set the DecimalPlaces property.


 Change the format of a text box or other control on a form or report when it meets certain criteria

Change the format of a text box or other control on a form or report when it meets certain criteria

  1. Open the form in Design view or Form view or the report in Design view.

  2. Make sure that the control is selected, and then, on the Format menu, click Conditional Formatting.

  3. Do one of the following:
    • To use values in the selected control as the formatting criteria, click Field Value Is in the first box, click the comparison phrase in the second box, and then type a value in the third (and fourth) box. You can enter a constant value or an expression.

    • To use an expression as the formatting criteria (to evaluate data or a condition other than the values in selected controls), click Expression Is in the first box, and then enter the expression in the second box. The expression must return a logical value of TRUE or FALSE. Learn about creating an expression.
  4. Select the font style, color, or other formatting that you want to apply.

    Microsoft Access applies the selected formatting only if the control value meets the condition, or the expression returns a value of TRUE.

  5. To add another condition, click Add, and then repeat steps 3 and 4.

    You can specify up to three conditions. If none of the specified conditions are true, the control keeps its existing formatting.

Note If more than one specified condition is true, Access applies only the formatting of the first true condition.


 Optimize Filter By Form performance for all tables, queries, and forms

Optimize Filter By Form performance for all tables, queries, and forms

These settings affect all tables and queries, and all text box controls whose FilterLookup property is set to Database Default. For more information on setting this property, click [image] .

  1. On the Tools menu, click Options.

  2. Click the Edit/Find tab, and then set the Filter By Form Defaults according to the performance you want to achieve.
    • If the list of values takes too long to display in nonindexed fields only, try limiting the lists to indexed fields. You can do this by clearing the check box for Local Nonindexed Fields and ODBC Fields. If the lists take too long to display in indexed fields, clear the Local Indexed Fields check box as well since there are too many records in the indexes for the lists to display quickly.

      Note If you use the same nonindexed field repeatedly to filter records, consider indexing it to improve filtering and other search operations on the field. For more information, click [image] .

    • If lists aren't displaying the values from indexed or nonindexed fields, check under Show List Of Values In to make sure the appropriate boxes are selected, or try increasing the number in the Don't Display Lists Where More Than This Number Of Records Read box so that it's greater than or equal to the maximum number of records in any nonindexed field in the underlying table.

Note For information on how Microsoft Access reads records differently in indexed fields than in nonindexed fields and how this difference relates to the Don't Display Lists Where More Than This Number Of Records Read box, click [image] .


 Optimize Filter By Form performance for a specific form

Optimize Filter by Form performance for a specific form

For each text box control on a form, you can specify whether the values stored in the field appear on its list in the Filter By Form window.

  1. Open a form in Design view.

  2. Display the property sheet for any text box control.

    How?

  3. In the FilterLookup property box, set the property to the setting that will achieve the performance you want.
    • If the list takes too long to display in the Filter By Form window, either set the FilterLookup property to Never, or set it to Database Default and then make the appropriate changes in the Options dialog box (Tools menu). For more information, click [image] .

    • If the list in the Filter By Form window isn't displaying the values stored in that field, make sure the FilterLookup property isn't set to Never. If the FilterLookup property is set to Database Default or Always, make the appropriate changes in the Options dialog box (Tools menu). For more information, click [image] .


 Change the query in the RowSource property for a chart in a form or report

Change the query in the RowSource property for a chart in a form or report

  1. Open the form in form Design view or report in report Design view.

  2. Make sure the chart is selected, and then click Properties [image] .

  3. Click in the RowSource property box, and then click Build [image] to the right of the RowSource property box to open the Query Builder.

    The Query Builder displays the RowSource query in Design view.

  4. Change the query.

    To preview your changes, click Datasheet on the View menu.

  5. Close the Query Builder.

  6. To see the changes to the chart, you must open the form in Form view, or the report in Print Preview.

If changing the RowSource query doesn't work, you can try changing the data in the underlying table or other record source. For information on changing the data in the underlying table or other record source, click [image] .


 Change the starting value of an incrementing AutoNumber field

Change the starting value of an incrementing AutoNumber field

For a new table that contains no records, you can change the starting value of an AutoNumber field that has its NewValues property set to Increment to a number other than 1. For a table that contains records, you can also use this procedure to change the next value assigned in an AutoNumber field to a new number.

  1. Create a temporary table with just one field, a Number field; set its FieldSize property to Long Integer and give it the same name as the AutoNumber field in the table whose value you want to change.

    How?

  2. In Datasheet view, enter a value in the Number field of the temporary table that is 1 less than the starting value you want for the AutoNumber field. For example, if you want the AutoNumber field to start at 100, enter 99 in the Number field.

  3. Create and run an append query to append the temporary table to the table whose AutoNumber value you want to change.

    How?

    Note If your original table has a primary key, you must temporarily remove the primary key before running the append query. Also, if your original table contains fields that have the Required property set to Yes, the Indexed property set to Yes (No Duplicates), or field and/or record ValidationRule property settings that prevent Null entries in fields, you must temporarily disable these settings.

  4. Delete the temporary table.

  5. Delete the record added by the append query.

  6. If you had to disable property settings in step 3, return them to their original settings.

When you enter a record in the remaining table, Microsoft Access uses an AutoNumber field value 1 greater than the value you entered in the temporary table.

Note If you want to compact the database after changing the starting AutoNumber value, make sure to add at least one record to the table first. If you don't, when you compact the database, the AutoNumber value for the next record added will be reset to 1 more than the highest previous value. For example, if there were no records in the table when you reset the starting value, compacting would set the AutoNumber value for the next record added to 1; if there were records in the table when you reset the starting value and the highest previous value was 50, compacting would set the AutoNumber value for the next record added to 51.


 Change the layout of a subform displayed in Datasheet view

Change the layout of a subform displayed in Datasheet view

In Form view of the main form, you can do any of the following in the subform:

  • To change the width of a column, drag the right edge of the column selector. To automatically size the column to fit its data, double-click the right edge of the column selector.

  • To change the order of columns, click a column heading to select the column. Then click the column heading again, hold down the mouse button, and drag the column to a new location.

  • To change the height of all the rows, drag the bottom edge of the row selector.

  • To hide a column, click anywhere in the column, and then click Hide Columns on the Format menu.

  • To show a hidden column, click Unhide Columns on the Format menu, and select the check box of the column you want to show.

  • To freeze a column, click anywhere in the column, and then click Freeze Columns on the Format menu.

Notes

  • If you need to adjust the size of the subform itself, size the subform control in Design view of the main form.

  • If the AllowDesignChanges property of the main form is set to All Views, you can change the design of the subform datasheet by using the property sheet in Form view.


 Change the layout of a subform displayed as a single or continuous form

Change the layout of a subform displayed as a single or continuous form

  1. Open the main form in Design view. The subform is displayed in Design view in the subform control.

  2. Make sure the subform control is selected. After it’s selected, you can click again inside the control to select the form, a section, or a control, just as you would if you opened the subform in Design view from the Database window.

  3. Make changes to the subform’s design.

  4. To make changes to the subform control — for example, to resize it or set its properties — first click the border of the control to select it.

  5. Switch to Form view to see the changes.

Notes

  • If you change the width of a form displayed as a subform, you must also adjust the width of the subform control on the main form.

  • If the AllowDesignChanges property of the main form is set to All Views, you can change the design of the subform by using the property sheet in Form view. You can’t, however, make changes to the subform control.


Change a table's design from the Relationships window

  1. In the Relationships window, right-click the table you want to change, and then click Table Design.

  2. Make the desired changes to the table's definition.


 Change the title bar text for a form in Form view

Change the title bar text for a form in Form view

  1. Open a form in Design view.

  2. Double-click the form selector to open the property sheet.

  3. In the Caption property box, type the title bar text.

  4. To see the title bar text, switch to Form view.

Tip If you don't want to have any title bar text, type a space in the Caption property box.


 Change the type of link for a picture or other object on a form or report

Change the type of link for a picture or other object on a form or report

When you link to an object that was created in another application, Microsoft Access creates an automatic link by default. You can change the type of link to manual, or vice versa.

Note This type of link is different from a hyperlink that is used on a form or report to jump to another document, object, or page. For more information on hyperlinks, click [image] .

  1. Do one of the following:
    • If the object is unbound, click the object in form or report Design view.

    • If the object is bound, open the form in Form view (or open a datasheet), find the record that you want to change, and click the object.
  2. On the Edit menu, click OLE/DDE Links.

  3. In the Links box, click the link that you want to change. To select multiple links, hold down the CTRL key while you click each link.

  4. Click Automatic or Manual.

Notes

  • When you make any changes to a link for a bound object frame, you are changing the link only for the current record. To make a change in a different record, move to that record and repeat the process.

  • This procedure only applies to pictures in unbound object frames and bound object frames. Background pictures and pictures in image controls are always updated automatically.


 Choose fields for a new table from existing tables

Choose fields for a new table from existing tables

  • Use the Table Wizard to choose the fields for your table from a variety of predefined tables such as business contacts, household inventory, or medical records.

    Create a table using the Table Wizard


 Change the speed of scrolling text on a data access page

Change the speed of scrolling text on a data access page

  1. Open a data access page in Design view.

  2. Select the scrolling text control, and then click Properties [image] on the toolbar to display the control’s property sheet.

  3. In the TrueSpeed property box, click True.

  4. In the ScrollDelay property box, type the number of milliseconds to delay between each repetition of the scrolling text.

  5. In the ScrollAmount property box, type the number of pixels you want the scrolling text to move in the time that you specified in the ScrollDelay property box. The ScrollAmount property sets the spacing between each repetition of text.

Note When the TrueSpeed property is set to True, scrolling text speed is determined by the ScrollDelay and ScrollAmount properties. For example, if the ScrollDelay property is set to 65 and the ScrollAmount property is set to 10, the scrolling text advances 10 pixels every 65 milliseconds. When the TrueSpeed property is set to False, the shortest delay between repetitions of text is 60 milliseconds.


 Clear all the fields in the Filter By Form window

Clear all the fields in the Filter By Form window

  • Click Clear Grid [image] on the toolbar.


 Clear the design grid in a query or advanced filter

Clear the design grid in a query or advanced filter

  • In query Design view or in the Advanced Filter/Sort window, click Clear Grid on the Edit menu.


 Combine data in fields from two or more tables using a union query

Combine data in fields from two or more tables using a union query

Union queries combine corresponding fields from two or more tables or queries into one field. When you run a union query, it returns the records from corresponding fields in the included tables or queries.

  1. In the Database window, click Queries [image] under Objects, and then click New on the Database window toolbar.

  2. In the New Query dialog box, click Design View, and then click OK.

  3. Without adding tables or queries, click Close in the Show Table dialog box.

  4. On the Query menu, point to SQL Specific, and then click Union.

  5. Enter SQL SELECT statements combined with either the UNION operation if you don't want to return duplicate records or the UNION ALL operation if you do want to return duplicate records.

    Note Each SELECT statement must return the same number of fields, in the same order. The corresponding fields are required to have compatible data types with one exception: You can use a Number and a Text field as corresponding fields.

    A union query combines data from two or more tables

    For information on SELECT statements, click [image] For information on the UNION and UNION ALL operations, click [image] .

  6. If you want to specify sorting in a union query, add a single ORDER BY clause to the end of the last SELECT statement. In the ORDER BY clause, specify the field name to sort, which must come from the first SELECT statement. For information on the ORDER BY clause, click [image] .

  7. To see the query's results, click View [image] on the toolbar.

Caution If you convert a union query to another type of query, such as a select query, you'll lose the SQL statement that you just entered.

Notes

  • The query Customers and Suppliers by City in the Northwind sample database is an example of a union query. To view this query, open the Northwind database in your Office folder's Samples subfolder, and then open the Customers and Suppliers by City query in Design view. For information on opening Northwind, click [image] .

  • A union query takes its column names from the column names in the first table or SELECT statement. If you want to rename a field in the results, use the AS clause to create an alias for the fields. For an example, click [image] .


 Compact an Access database or Access project that is not open

Compact an Access database or Access project that is not open

  1. Close the current Microsoft Access database or Microsoft Access project. If you are compacting a multiuser (shared) database that is located on a server or shared folder, make sure no one else has it open.

  2. On the Tools menu, point to Database Utilities, and then click Compact and Repair Database.

  3. In the Database To Compact From dialog box, specify the Access database or Access project you want to compact, and then click Compact.

  4. In the Compact Database Into dialog box, specify a name, drive, and folder for the compacted Access database or Access project.

  5. Click Save.

    If you use the same name, drive, and folder, and the Access database or Access project is compacted successfully, Microsoft Access replaces the original file with the compacted version.

Note You can stop the compacting process by pressing CTRL+BREAK or ESC.


 Compact the current Access database or Access project

Compact the current Access database or Access project

  1. If you are compacting a multiuser (shared) database that is located on a server or shared folder, make sure that no one else has it open.

  2. On the Tools menu, point to Database Utilities, and then click Compact and Repair Database.

Note You can stop the compacting process by pressing CTRL+BREAK or ESC.


 Convert a previous-version database to Microsoft Access 2000

Convert a previous-version database to Microsoft Access 2000

  1. Make a backup copy of the Access database you're going to convert, to keep until you're comfortable working with the Microsoft Access 2000 database.

  2. Close the Microsoft Access database you're going to convert.

    If the Access database is a multiuser database located on a server or in a shared folder, make sure that no one else has it open.

  3. In Microsoft Access 2000, point to Database Utilities on the Tools menu; point to Convert Database and then click To Current Access Database Version.

  4. In the Database To Convert From dialog box, select the database you want to convert and then click Convert.

  5. In the Convert Database Into dialog box, do one of the following:
    • Type a new name (without the .mdb extension) for the Microsoft Access 2000 database file.

    • Select a different location for the Microsoft Access 97 database file. (You can keep the same name, or change it.)

    You cannot convert an Access database into a file with the same name and location as the original database.

  6. Click Save.

Microsoft Access converts the database to Access 2000 format.

Learn more about converting a replicated database.

Notes

  • You can convert a secured Access database. However, user-level security no longer protects modules. You can protect the modules in the converted Access database by protecting the Visual Basic for Applications (VBA) code with a password.

  • When you convert a previous-version Microsoft Access database that has linked tables, make sure that the external tables are in the same folder that they were originally in. If Microsoft Access can't find the tables that are linked to a database that's being converted, you won't be able to use the converted database. Once you convert the Access database, you can move these tables and use the Linked Table Manager to re-link them. Converting a database that has tables linked to it does not convert the linked tables.

  • You can also convert a previous-version Access database by importing its database objects into a new Access 2000 database. You can use this method if you don't want all of objects in the previous-version database to exist in the Access 2000 database.


 Convert Code That Calls a DLL

Convert Code That Calls a DLL

Calling Procedures in the Windows Application Programming Interface

If a database created in previous versions of Microsoft Access called procedures in the Microsoft Windows application programming interface (API), you will need to make some changes in your code when you convert a version 2.0 or earlier database to Microsoft Access 2000.

The Windows API consists of a set of dynamic-link libraries (DLLs) containing system-related procedures that include functions, messages, data structures, data types, and statements you can use in creating applications that run under Windows 95 or the Windows NT platform. In order to call these procedures from Visual Basic, you must first declare them by using a Declare statement. You can then call them as you would any other procedure.

In versions 1.x and 2.0 of Microsoft Access were 16-bit applications and ran on 16-bit versions of Windows. Microsoft Access 2000 is a 32-bit application and runs only under Windows 95 and the Windows NT platform. If your existing Access Basic code made calls to a 16-bit Windows API, you will need to modify these calls when you convert your database to Microsoft Access 2000. The following list provides some tips for converting your code.

  • Check any Declare statements to ensure that they refer to the correct DLLs. The following table shows the new names for the 32-bit Windows DLLs.

    16-bit Windows DLL | 32-bit Windows DLL
    User.dll | User32.dll
    Kernel.dll | Kernel32.dll
    GDI.dll | GDI32.dll

  • The names of some functions in the 32-bit Windows API have changed. Additionally, functions in the 32-bit Windows API are case-sensitive. Check to make sure that you've entered the procedure name and alias name correctly.

  • Some functions have new parameter data types in the 32-bit Windows API. Consult one of the references listed later in this topic to determine which function calls you must update.

  • If a16-bit version of a DLL with the same name as a 32-bit DLL exists on your computer, Microsoft Access may try to call a function in that DLL if the directory in which it resides precedes the directory that contains the new version in your path.

  • Some 32-bit DLLs contain functions with slightly different versions to accommodate both Unicode and ANSI strings. An A at the end of the function name specifies the ANSI version. A W at the end of the function name specifies the Unicode version. If the function takes string-type arguments, try appending an A to the function name.

For more information on using 32-bit Windows API procedures and on porting your existing database applications to 32-bit Microsoft Access 2000, consult the following resources:

  • The Windows API Viewer, available in the Microsoft Office 2000 Developer, includes Visual Basic syntax for all 32-bit declarations, data types, and constants.

  • The Microsoft Office 2000 Resource Kit contains information on porting your 16-bit Microsoft Office-based solutions, including applications developed with previous versions of Microsoft Access, to 32-bit solutions.

  • The Microsoft Win32 Software Development Kit provides complete reference information on 32-bit Windows API procedures.

Calling Code in Other DLLs

If your database application calls procedures in other DLLs, you must create or obtain 32-bit versions of those DLLs and make any necessary modifications to your code when you convert your database to Microsoft Access 2000.

If you can't obtain a 32-bit version of a DLL, then you'll need an intermediary DLL that can convert 32-bit calls to 16-bit calls. For more information, see the preceding resources list.


 Convert global macros to Visual Basic

Convert global macros to Visual Basic

  1. In the Database window, click Macros [image] under Objects.

  2. Click the name of the macro you want to convert.

  3. On the File menu, click Save As.

  4. In the Save As dialog box, click Module and click OK.

  5. In the Convert macro dialog box, select the options you want, and click Convert.


 Convert macros on a form or report to Visual Basic

Convert macros on a form or report to Visual Basic

  1. Open the form or report in form or report Design view.

  2. Point to Macro on the Tools menu, and then click Convert Form's Macros To Visual Basic or Convert Report's Macros To Visual Basic.


 Convert an OLE object on a form or report to a later version of that object

Convert an OLE object on a form or report to a later version of that object

  1. Do one of the following:
    • If the object is unbound, click the object in form or report Design view.

    • If the object is bound, open the form in Form view (or open a datasheet), find the record that you want to change, and click the object.
  2. On the Edit menu, point to the appropriate Object command (for example, point to Worksheet Object for a Microsoft Excel object), and then click Convert.

  3. In the Convert dialog box, click the version that you want to convert to. For example, you could convert a Graph 3.0 object to a Graph 5.0 object.


 Convert a bound picture or other object on a form to an image

Convert a bound picture or other object on a form to an image

  1. Open the form in Form view.

  2. Click the object and then click Copy [image] on the toolbar.

  3. On the Edit menu, click Paste Special.

  4. In the As list, click Picture, or one of the bitmap choices, depending on whether you want to create a metafile or a bitmap.

  5. Microsoft Access converts the object to an image. The bound object frame remains on the form, but you can't open the application that was used to create the object (the OLE server application) from the form. If the object is a sound object, just the icon remains. If it's a video object, just the first frame of the video remains. You can't play the sound or video object.

Notes

  • When you make any changes to an object in a bound object frame, you're changing the object only for the current record. To make a change in a different record, move to that record and repeat the process.

  • If you convert the object to an image as described in this procedure, the form will open faster. If you just want to prevent users from editing an object, and performance isn't an issue, you can instead set the Locked property of the bound object frame to Yes and the Enabled property to No.


 Convert an unbound picture or other object so it can't be edited on a form or report

Convert an unbound picture or other object so it can't be edited on a form or report

  1. Open the form in Design view or the report in Design view.

  2. Click the object.

  3. On the Format menu, point to Change To, and then click Image.

    Microsoft Access converts the unbound object frame to an image control. The object remains on the form or report, but you can't open the application that was used to create the object (the OLE server application) from the form or report. If the object is a sound object, just the icon remains. If it's a video object, just the first frame of the video remains. You can't play the sound or video object.


 Copy or move an Access database or Access project

Copy or move an Access database or Access project

  1. Close the Microsoft Access database or Microsoft Access project. In a multiuser environment, confirm that all users have closed the Access database.

  2. In My Computer or Windows Explorer, find the database (.mdb) or project (.adp) file and then click it.

    To select more than one file to copy or move, hold down the CTRL key and click each file.

  3. To copy the file, click Copy on the Edit menu.

    To move the file, click Cut on the Edit menu.

  4. Open the folder or disk where you want to put the file.

  5. On the Edit menu, click Paste.

    To undo the paste operation, click Undo Copy or Undo Move on the Edit menu.

Notes

  • When you copy or move an Access database or Access project that contains links to data access pages, Access leaves the pages in their original folder and automatically updates links to the pages so they continue to work as before.

  • When you copy or move an Access project file, you are not copying or moving the Microsoft SQL Server database to which the Access project is connected.

Tip If the destination where you're placing the file is already visible, you can quickly move the file by dragging it to the new destination, or you can copy the file by holding down the CTRL key while you drag the file.


 Use the Copy command to copy a database object

Use the Copy command to copy a database object

  1. In the Database window under Objects, click the type of database object that you want to copy.

  2. Click the object in the Object list, and then click Copy [image] on the toolbar.

  3. If you are copying the object to a different Microsoft Access database or Microsoft Access project, close the current Access database or Access project, and then open the Access database or Access project into which you want to paste the object.

  4. With the Database window displayed, click Paste [image] on the toolbar.

  5. Provide the information requested in the Paste As dialog box. The name of the new object must be unique and must follow Microsoft Access object-naming rules. If you are in an Access database that is a Design Master, and if you want the new object to be replicated to other databases, select the Make Replicable check box.

Notes

  • When you copy a table, the Paste Table As dialog box offers the options to paste the table structure only, paste the structure and the data, or append the data to an existing table.

  • When you use this procedure to create a copy of a data access page, Microsoft Access prompts you to provide a name for the new HTML file.

  • Learn more about saving changes to a shared Access database

  • If you have problems copying a table's data, click [image] . It may be easier to copy a large number of records in an Access database with an append query. For more information, click


 Create a hyperlink by pasting one from a Microsoft Office document

Create a hyperlink by pasting one from a Microsoft Office document

  1. Open a Microsoft Office document that contains a defined hyperlink.

  2. Right-click the defined hyperlink that you want to copy. Point to Hyperlink on the shortcut menu, and then click Copy Hyperlink.

    Note When you copy a defined hyperlink in an Office document, make sure to copy just the hyperlink itself. If you copy characters that surround the hyperlink but aren't part of the hyperlink, Microsoft Access will link to the text that you selected instead of to the hyperlink address.

  3. Switch to Microsoft Access and open a form in Design view or a report in Design view.

  4. Click Paste As Hyperlink on the Edit menu.

    Microsoft Access adds a label to the form or report. To test the link, right-click the label, point to Hyperlink on the shortcut menu, and then click Open.


 Move an action in a macro

Move an action in a macro

  1. In the Macro window, click the selector for the action row.

  2. Click the selector again and drag the row to a new position.


 Rename an Access database or Access project

Rename an Access database or Access project

  1. Close the Microsoft Access database or Microsoft Access project. In a multiuser environment, confirm that all users have closed the Access database.

  2. Click Open [image] on the toolbar.

  3. In the Open dialog box, locate the Access database or Access project you want to rename, and then right-click the file.

  4. On the shortcut menu, click Rename.

  5. Type the new name. Include the .mdb or .adp extension only if you've set up Microsoft Windows to display MS-DOS file extensions. Press ENTER.

    The file name can be up to 255 characters, including spaces.

Note You can also rename an Access database or Access project from outside Access. Close the file, right-click the file in Windows Explorer or My Computer, and then click Rename on the shortcut menu.


 Enter a hyperlink by pasting text from a Microsoft Office document

Enter a hyperlink by pasting text from a Microsoft Office document

  1. Open the Microsoft Office document that you want to link to. For example, open a Microsoft Word document.

  2. Select the text that you want to link to.

    Note By selecting text, you can create a hyperlink to a data access page but not other Microsoft Access objects.

  3. On the Edit menu, click Copy.

  4. Switch to Microsoft Access and do one of the following:
    • In a Microsoft Access database (.mdb), open the table or query in Datasheet view.

    • In an Access database or Microsoft Access project (.adp), open the form in Datasheet or Form view.
  5. Place the insertion point in the hyperlink field in the datasheet or in the text box or other control that accepts hyperlinks on the form.

  6. Click Paste on the Edit menu.

    Microsoft Access adds the hyperlink to the field or control. On a form or datasheet, you can click the hyperlink to open the target document or Web page.


 Create a hyperlink by pasting text from a Microsoft Office document

Create a hyperlink by pasting text from a Microsoft Office document

  1. Open the Microsoft Office document that you want to link to. For example, open a Microsoft Word document.

    Note You can create a hyperlink by using text that you select in a data access page, but not text from other Microsoft Access objects.

  2. Select the text you want to link to.

  3. On the Edit menu, click Copy.

  4. Switch to Microsoft Access and open a form in Design view or a report in Design view.

  5. On the Edit menu, click Paste As Hyperlink.

    Microsoft Access adds a label to the form or report. To test the link, right-click the label, point to Hyperlink on the shortcut menu, and then click Open.


 Create a value list field in Datasheet view

Create a value list field in Datasheet view

  1. Open the table in Datasheet view.

  2. To insert a value list field within the table, click in the column to the right of where you want to insert the field, and then on the Insert menu, click Lookup Column.

  3. In the first dialog box of the Lookup Wizard, select the option that indicates you will type in the values that you want.

  4. Click Next and follow the directions in the remaining Lookup Wizard dialog boxes.

    When the Lookup Wizard is finished, the value list field is added to your datasheet. By default, the new value list field will be given a name in the form, "Field#," where # is some number. You can change this name if you want. To find out how to change a field name in Datasheet view, click [image] .

Note When you use the Lookup Wizard to create a fixed value list, Microsoft Access sets certain field properties based on the choices you made in the wizard. Once you've created the field, if you add it to a form, Microsoft Access copies its definition into the form. The combo box or list box is created automatically for the form. However, if you change the definition of the value list field in the table after adding it to a form, those changes will not be reflected in that form. To correct this, delete the field from the form and then add it again. For information on the properties that the Lookup Wizard sets, click [image] .


 Create a value list field in Design view

Create a value list field in Design view

  1. Open the table in Design view.

  2. To insert the field within the table, click in the row below where you want to add the field, and then click Insert Rows [image] on the toolbar.

    To add the field to the end of the table, click in the first blank row.

  3. In the Field Name column, type the name for the field, following Microsoft Access object-naming rules.

  4. In the Data Type column, click the arrow and select Lookup Wizard.

  5. In the first Lookup Wizard dialog box, click the option that indicates you will type in the values that you want.

  6. Click Next and follow the directions in the remaining Lookup Wizard dialog boxes.

Note When you use the Lookup Wizard to create a fixed value list, Microsoft Access sets certain field properties based on the choices you made in the wizard. Once you've created the field, if you add it to a form, Microsoft Access copies its definition into the form. The combo box or list box is created automatically for the form. However, if you change the definition of the value list field in the table after adding it to a form, those changes will not be reflected in that form. To correct this, delete the field from the form and then add it again. For information on the properties that the Lookup Wizard sets, click [image] .


Create all tables, forms, and reports for a database in one operation

  • Use the Database Wizard to create in one operation all the tables, forms, and reports required for an entire database. The Database Wizard creates a new database; it can't be used to add new tables, forms, or reports to an existing database.

    Create a database using the Database Wizard


 Work with tables or indexes by using an SQL data-definition query

Work with tables or indexes by using an SQL data-definition query

Use SQL data-definition queries to create, delete, or alter tables or create indexes in the current database.

  1. In the Database window, click Queries [image] under Objects, and then click New on the Database window toolbar.

  2. In the New Query dialog box, click Design View, and then click OK.

  3. Without adding tables or queries, click Close in the Show Table dialog box.

  4. On the Query menu, point to SQL Specific, and then click Data Definition.

  5. Enter the SQL statement for your data-definition query. Each data-definition query consists of just one data-definition statement. Microsoft Access supports these data-definition statements:
    • CREATE TABLE creates a table. For more information, click [image] .

    • ALTER TABLE adds a new field or constraint to an existing table. For more information, click [image] .

    • DROP deletes a table from a database or removes an index from a field or group of fields. For more information, click [image] .

    • CREATE INDEX creates an index for a field or group of fields. For more information, click [image] .
  6. To run the query, click Run [image] on the toolbar.

Caution If you convert a data-definition query to another type of query, such as a select query, you'll lose the SQL statement that you entered.

Notes

  • For examples of data-definition queries, click [image] .

  • To create or change objects in ODBC database servers, such as Microsoft FoxPro, use pass-though queries instead of data-definition queries.


 Create a parameter query that gets criteria from a custom dialog box

Create a parameter query that gets criteria from a custom dialog box

You can use a custom dialog box to enter criteria for the query underlying a form, report, or Web page. For example, a custom dialog box can determine what records a printed report includes.

  1. Create or open the query that will collect its criteria values from the dialog box.

  2. Make sure that the query includes the tables you want to use.

  3. Add to the query design grid the fields associated with each of the dialog box controls where you'll enter criteria values. For each of these fields, enter an expression in the Criteria cell that tells Microsoft Access to refer to the control on the dialog box for the criteria values. If you need help creating the expression, use the Expression Builder. For more information, click [image] .

  4. Add to the query design grid the fields whose values you want returned.

For example, you could create a dialog box form named Customer Info with a control for the CustomerID field. By entering a customer ID in the dialog box, you could have the query return the correct customer's company name, address, and city. To create this query, you'd do the following:

  • Add the CustomerID field to the query design grid. In its Criteria cell, enter the expression that tells Microsoft Access to refer to the Customer ID control in the dialog box for the criteria values the query uses. In this case, you'd enter the expression Forms![Customer Info]![CustomerID].

  • Add to the query design grid the fields whose values you want returned based on the CustomerID value: CompanyName, Address, and City fields.

To read more about using forms to collect and display information, see "Using Forms to Collect, Filter, and Display Information" in Building Applications with Forms and Reports.


 Create a blank data access page

Create a blank data access page

  1. In the Database window, click Pages [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. In the New Data Access Page dialog box, click Design View.

  4. Click OK.

Microsoft Access displays the data access page in Design view, where you can modify the page.


 Create a bound list box, combo box, or drop-down list box that retrieves data from a table or query in a Microsoft Access project or a data access page Access project

Create a bound list box, combo box, or drop-down list box that retrieves data from a table or query in a Microsoft Access project or a data access page

  1. Create a new form, report, or data access page based on a record source that includes a foreign key field.

  2. In the toolbox, make sure the Control Wizards tool [image] is pressed in.

    Note Wizards are not available in a stand-alone data access page, or when you point a data access page to a database other than the one currently open. In both cases, you will have to create the list box or drop-down list box on your own.

  3. Click the List Box tool List Box control , Combo Box tool , or Dropdown List tool, and then click where you want to place the control on the form, report, or data access page.

  4. Follow the instructions in the wizard dialog boxes. When the wizard asks you how you want to get the values for the list, select the option that says you want to look up the values in a table or query.

  5. In a form or report, when the wizard asks if you want to store the value in the field, select the option to store the value in the field and select the field from the list.

  6. In the last wizard dialog box, click Finish.

  7. In a data access page, click Properties [image] on the toolbar to open the property sheet for the control. In the ControlSource property box, select the field to bind the list box or the drop-down list box to.

Notes

  • For information on properties that determine how a list box or combo box works in a form, click [image] .

  • For information on properties that determine how a list box or drop-down list box works in a data access page, click [image] .


 In a form, create a bound list box or combo box that displays data in an Access database

In a form, create a bound list box or combo box that displays data in an Access database

You can create a list box or combo box that retrieves information from a Lookup field in a table in a Microsoft Access database (.mdb). There are no Lookup fields in the tables in a Microsoft Access project (.adp), but you can create a bound list box, combo box, or drop-down list box that displays data without using a Lookup field.

  1. Create a Lookup field in table Design view.

    How?

    Note You can create a lookup list box or combo box without creating a Lookup field, but if you create a Lookup field in a table, you only need to create the list box or combo box once. Then you can use the same lookup list on any form. If you don't plan to use the same lookup list in more than one form, you can use the List Box Wizard or Combo Box Wizard in form Design view.

  2. Do one of the following:
    • Create a new form that is based on a record source that includes the Lookup field that you created in step 1. Microsoft Access automatically creates the lookup list box or combo box.

    • Open an existing form that is based on a record source that includes the Lookup field you created in step 1. In form Design view, click Field List [image] on the toolbar to display the field list, and then drag the Lookup field from the field list to the form. Microsoft Access automatically creates the lookup list box or combo box.
  3. Switch to Form view to test the list box or combo box.

Notes

  • For information on properties that determine how a list box or combo box works, click [image] .

  • When you use a wizard to create a list box or combo box that is based on a table or query, Microsoft Access creates an SQL statement based on the fields that you select, and then sets the RowSource property for the control to that SQL statement. If the list box or combo box isn't sorted the way that you want, you can modify the SQL statement by clicking the Build button [image] next to the RowSource. For information on specifying a sort order in the SQL Statement Builder, click [image] .

  • For information on troubleshooting list boxes and combo boxes, click [image] .


 Add a bound object frame on a form or report

Add a bound object frame on a form or report

  1. If you haven't already done so, create a field in a table, and set the field's data type to OLE Object in a Microsoft Access database (.mdb), or to image in a Microsoft Access project (.adp).

    How?

  2. Create a form or report (or open an existing form or report) that includes the OLE Object field or image column in its record source.

  3. In form or report Design view, click Field List [image] on the toolbar to display the field list.

  4. Drag the OLE Object field or image column from the field list to the form or report.

    Microsoft Access creates a bound object frame that's bound to the OLE Object field or image column.

Note If you've already created the bound object frame, you can bind it to a field in an underlying record source by setting the ControlSource property for the bound object frame to the name of the field.


 Create a bound scrolling text control that displays data on a data access page

Create a bound scrolling text control that displays data on a data access page

  1. Open a data access page in Design view.

  2. Click the Scrolling Text tool Scroll Text control in the toolbox.

  3. Click Field List [image] on the toolbar to display the field list.

  4. From the field list, drag the selected field to the data access page. Place the upper-left corner of the icon where you want the upper-left corner of the scrolling text control to be.


 Create a bound text box

Create a bound text box

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click Field List [image] on the toolbar. The field list appears. In a form or report, if the field list button or command isn't available, you need to bind the form or report to a recordsource. If the field list is empty in a data access page, you must connect the page to a database.

  3. Do one of the following:
    • Select one or more fields in the field list on a form or report.
    To select | Do this
    One field | Click the field.
    A block of fields | Click the first field in the block, hold down the SHIFT key and click the last field in the block.
    Nonadjacent fields | Hold down the CTRL key and click the name of each field that you want to include.
    All fields | Double-click the field list title bar.

    • Select a field, table, or query in the field list on a data access page.
    To select | Do this
    One field | Click the field.
    A table or query | Click the Wizard tool [image] in the toolbox if it's not already pressed in, and then click the table or query.
  4. Do one of the following:
    • Drag the field or fields from the field list and position them on the form or report.

    • Drag the field, table, or query from the field list and position it on the data access page. In the Layout Wizard dialog box, click Individual Controls.

    Note You must drag the field or fields from the field list. If you click the field or fields in the field list and then click the form, report, or data access page, Microsoft Access won't create the control.

    Access places one text box on the form, report, or data access page for each field that you select in the field list. Each text box is bound to one field in the underlying data source. Each text box also has an attached label by default.

  5. Size the text box so that it's the appropriate size for the data you want to show.

  6. Change the label text if necessary.

  7. Switch to Form view, Datasheet view, Page view, or Print Preview to test the control.

Note For text boxes on forms that have many lines of text, you may want to add a vertical scroll bar.

How?


 Create a check box, toggle button, or option button that's bound to data

Create a check box, toggle button, or option button that's bound to data

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the appropriate tool in the toolbox. If you're not sure which tool to use, place the pointer over the tool until the ToolTip appears.

    Note The toggle button is not available in data access pages.

  3. Click Field List [image] on the toolbar. The field list appears. In a form or report, if the field list button or command isn't available, you need to bind the form or report to a record source. In a data access page, if the field list is empty, you must connect the page to a database.

  4. Click the appropriate field (a field with a Yes/No data type in a Microsoft Access database or a column with a Bit data type in a Microsoft Access project) in the field list, and drag it to the form, report, or data access page.

    Note You must drag the field from the field list. If you click the field in the field list and then click the form, report, or data access page, the control won't be bound.

  5. Change the label text if necessary.

  6. Switch to Form view, Datasheet view, Page view, or Print Preview to test the control.

Tip If you often display the same Yes/No field or Bit column as a check box on different forms and reports in a database, you can set the DisplayControl property of the field so that when you drag it from the field list, it automatically creates a check box (you don't have to click the Check Box tool first). For more information, click [image] .


Create Column Example

The following example creates a new table with two new columns. One of the columns is set to AutoNumber. The procedure also makes the Autonumber column the primary key in the table.

Note Auto increment property not available in an ADP via the SQL provider shipped with Microsoft Access 2000. A reference to "Microsoft ADO ext. 2.1 for DDL and Security" must be set to use this example.

Sub NewTable()
    Dim tbl As New ADOX.Table
    Dim cat As New ADOX.Catalog
    Dim idx As New ADOX.Index

    ' Return reference to current database.
    Set cat.ActiveConnection = CurrentProject.Connection
       With tbl
        .Name = "Contacts"
        With .Columns
            .Append "ContactID", adInteger
            .Append "ContactName", , 50

        'If in an ADP omit the following with clause.
          With !ContactID
                Set .ParentCatalog = cat
                .Properties("AutoIncrement")=True
         End With
        End With
    End With

    ' Create primary key index.
    idx.Name = "PrimaryKey"

    ' Append index Column.
    idx.Columns.Append "ContactID", adInteger

     ' Set PrimaryKey property.
    idx.PrimaryKey = True
    ' Append index.
    tbl.Indexes.Append idx
    ' Append TableDef object.
    cat.Tables.Append tbl

    Set tbl = Nothing
    Set cat = Nothing
End Sub


Create a command button that's a hyperlink on a form or report

What do you want to do?

Create a link to an existing file or Web page

Create a link to a table, query, form, report, or data access page in the current database

Create a new data access page and create a hyperlink to that page

Create a hyperlink that opens my e-mail program and creates a message to the specified e-mail address


 Create a command button without a wizard

Create a command button without a wizard

  1. Open a form in Design view or a data access page in Design view.

  2. Click the Control Wizards tool [image] in the toolbox if it's pressed in. This turns off the wizard.

  3. In the toolbox, click the Command Button tool Command Button control .

  4. On the form or data access page, click where you want to place the command button.

  5. Make sure that the command button is selected, and then click Properties [image] on the toolbar to open the command button's property sheet.

  6. In the OnClick property box on a form, enter the name of the macro or event procedure that you want to run when the button is clicked, or click the Build button [image] to use the Macro Builder or Code Builder. On a data access page, you can attach code written in either JScript or Microsoft Visual Basic Scripting Edition (VBScript) to a command button by using the Microsoft Script Editor. How to create an event procedure for a command button on a data access page.

  7. If you want to display text on the command button, type the text in the Caption property box of a form or the Value property of a data access page. If you don't want text on the button in a form, you can use a picture instead.

    How?

Tip On a form, to create a command button that runs a macro; drag the macro from the Database window to form Design view.

For an overview of events and event procedures, click [image] .


 Create a command button with a wizard

Create a command button with a wizard

  1. Open a form in Design view or a data access page in Design view.

  2. Click the Control Wizards tool [image] in the toolbox if it's not already pressed in.

  3. In the toolbox, click the Command Button tool Command Button control .

  4. On the form or data access page, click where you want to place the command button.

  5. Follow the directions in the wizard dialog boxes. In the last dialog box, click Finish to display the command button in Design view.

Note Wizards are not available in a stand-alone data access page, or when you point a data access page to a database other than the one that is currently open. The Command Button Wizard is also not available if the data access page isn't bound to a table or query. You will have to create a command button on your own if wizards aren't available.


 Create a custom dialog box

Create a custom dialog box

  1. Create the form. The form can have any combination of controls.

  2. In form Design view, double-click the form selector to open the property sheet for the form.

  3. In the PopUp property box, click Yes.

  4. In the Modal property box, click Yes.

  5. In the BorderStyle property box, click Dialog. If you select the Dialog setting, the form has a thick border and can include only a title bar and a Control menu. The form can't be maximized, minimized, or resized.

  6. Create a macro or event procedure that opens the form.

  7. Attach the macro or event procedure to a form or report by specifying the macro name or event procedure as the setting for the appropriate event property. For example, type the name of the macro or event procedure in the OnClick property box of a command button.

Notes

  • A custom dialog box usually contains one or more command buttons that run macros or event procedures that use the information entered in the dialog box to perform other actions. These buttons are often named OK and Cancel. You can control which button has the focus and which button will work as the Cancel button by setting the Default and Cancel properties for these types of command buttons. For more information about the Default property, click [image] . For more information about the Cancel property, click [image] .

  • To position a custom dialog box on the screen, open the form in Design view, maximize the Microsoft Access window, position the dialog box where you want it, and then save the form. The dialog box will appear in this location when it's opened (assuming the AutoCenter property is set to No).

  • For information about other properties that you might want to set for a custom dialog box, click [image] .

  • For information about creating a custom dialog box that prompts you to enter report criteria, click [image] .

  • For information about creating a query that gets its criteria from a custom dialog box in a Microsoft Access database (.mdb), click [image] . For information about creating a stored procedure that gets its criteria from a custom dialog box in a Microsoft Access project (.adp), click [image] .

  • If you want to use the form as a normal form as well as a dialog box, you can use the Dialog setting of the OpenForm action to open the form temporarily as a dialog box instead of using this procedure. For more information, click [image] .


 Create a group

Create a group

  1. If you haven't already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  2. Click the Groups bar.

  3. Right-click anywhere under the Groups bar. On the shortcut menu, click New Group.

  4. Type a name for your group in the New Group Name box.


Create custom database properties for use in locating a Microsoft Access database or Microsoft Access project

  1. With the database open, click Database Properties on the File menu.

  2. Click the Custom tab, and then type values for the new property in the Name, Type, and Value boxes.

  3. Click Add.

  4. When you have finished adding properties, click OK.


 Calculate a total or other value for one record on a data access page used for data entry

Calculate a total or other value for one record on a data access page used for data entry

  1. Open the data access page in Design view.

  2. If they aren't already on the page, add the controls that will contain the data you want to use in the calculation.

  3. Click the Office Spreadsheet tool Office Spreadsheet control in the toolbox, and then release the mouse button where you want the upper-left corner of the spreadsheet control on the data access page.

  4. In any cell in the spreadsheet, enter a formula that uses the HTML Document function to refer to the fields used in the calculation, and the specific operation you want to perform on the field's values expressed as a combination of operators, identifiers, and values.

    Example To multiply the value in the Quantity field by the value in the UnitPrice field, type:

    =document.Quantity.value*document.UnitPrice.value

    Example To multiply the value in the UnitPrice field by a percentage rate stored in spreadsheet cell C1, type:

    =$C$1*document.UnitPrice.value

Notes

  • To see the name of a spreadsheet, select its control, and then display the property sheet. The property sheet title bar displays the spreadsheet name.

  • See more examples of formulas that refer to controls on a data access page.

  • You can use spreadsheet functions, which, in Microsoft Access, are only available in this control.

  • Most likely, you'll want the calculated value to display in an area that looks like the other controls on the data access page. To do this you can modify the appearance of the spreadsheet control so it looks like a text box control.


 Create a data access page by using AutoPage

Create a data access page by using AutoPage

AutoPage creates a data access page that contains all fields (except fields that store pictures) and records in the underlying table, query, or view.

  1. In the Database window, click Pages [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. In the New Data Access Page dialog box, click AutoPage: Columnar. In the finished data access page, each field will appear on a separate line with a label to its left.

  4. Click the table, query, or view that contains the data you want to base your page on.

  5. Click OK.

    If the resulting page doesn't look the way you want, you can modify the page in Design view.

Notes

  • Microsoft Access applies the default theme to the page. If you haven't set a default theme, then Access uses the Straight Edge theme.

  • When you create a page by using AutoPage, Microsoft Access automatically saves the page as an HTML file in the current folder, and adds a shortcut to the page in the Database window. Rest the pointer over the shortcut in the Database window to display the path to the file.


 Make an existing Web page into a data access page

Make an existing Web page into a data access page

  1. In the Database window, click Pages [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. In the New Data Access Page dialog box, click Existing Web page.

  4. Click OK.

  5. In the Locate Web Page dialog box, find the Web page or HTML file that you want to open.

  6. Click Open.

Microsoft Access displays the page in Design view, where you can modify the page.

Notes

  • When you save a Web page in Microsoft Access, Access creates a shortcut to the HTML file in the Database window.

  • You can find a Web page by using the Search the Web button in the Locate Web Page dialog box. Save a copy of the page by using the Save As command on the File menu in Internet Explorer and then begin this procedure again to open the page in Design view.


 Create a data access page by using a wizard

Create a data access page by using a wizard

  1. In the Database window, click Pages [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. In the New Data Access Page dialog box, click Page Wizard.

  4. Click the name of the table, query, or view that includes the data that you want to base your data access page on.

    Note You don't need to do this step now — you can specify the record sources for the page in the wizard.

  5. Click OK.

  6. Follow the directions in the wizard dialog boxes.

    If the resulting page doesn't look the way you want, you can modify the page in Design view.

Note When you create a page by using a wizard, Microsoft Access automatically saves the page as an HTML file in the current folder and adds a shortcut to the page in the Database window. Place the mouse pointer over the shortcut in the Database window to display the path to the file.


Create a data access page on your own

You can use the steps in this topic to guide you through creating a data access page from start to finish. You'll use many of the steps to create every page. The others you'll use when you create a particular kind of page — for example, one that requires grouping records by categories or calculating totals. You need to use only the steps that are relevant to the type of page that you're creating. For other tasks related to creating data access pages, ask the Answer Wizard.

Read an overview of what data access pages are and how they work.

Learn about grouping records on a data access page.

Learn about using data access pages for data entry.

  1. Start your data access page

    Create a blank data access page

  2. Display data, text, and totals on the data access page

    Learn about displaying data, text, and totals in text boxes, labels, and other controls

    Learn about using the field list to display data

    Display data from a table or query

    Display a title or other informational text

    Calculate a total for one record

    Calculate a total for a group of records

    Calculate a grand total

    Get more information about text boxes, labels, and other controls

  3. Sort or group the data in your data access page

    Set the default sort order for records

    Change the size of a header, footer, or other section

    Group records on a page that you use only for viewing data

  4. Format, move, size, and align labels, text boxes, and other controls

    Make the text in a label, text box, or other control bold, italic, or underlined

    Move a text box or other control and its label

    Change the size of a label, text box, or other control

    Align text boxes and other controls

    Customize a record navigation control

  5. View the data access page in Page view or Microsoft Internet Explorer

    Open a page in Page view or Internet Explorer

    Switch between views of an open page

  6. Publish a data access page to make it available to other users

    Learn about sharing the database a data access page is connected to

    Publish a data access page to Web Folders or any Web server


 Create a database using the Database Wizard

Create a database using the Database Wizard

  1. When Microsoft Access first starts up, a dialog box is automatically displayed with options to create a new database or open an existing one. If this dialog box is displayed, click Database Wizard, and then click OK.

    If you have already opened a database or closed the dialog box that displays when Microsoft Access starts up, click New Database [image] on the toolbar.

  2. On the Databases tab, double-click the icon for the kind of database you want to create.

  3. Specify a name and location for the database.

  4. Click Create to start defining your new database.


 Create a database without using a wizard

Create a database without using a wizard

  1. When Microsoft Access first starts up, a dialog box is automatically displayed with options to create a new database or open an existing one. If this dialog box is displayed, click Blank Database, and then click OK.

    If you have already opened a database or closed the dialog box that displays when Microsoft Access starts up, click New Database [image] on the toolbar, and then double-click the Blank Database icon on the General tab.

  2. Specify a name and location for the database and click Create.

After you create a blank database, you must perform additional steps to define the objects that will make up your database.


 Create and insert a bound object on a form

Create and insert a bound object on a form

  1. If you haven't already done so, create a bound object frame on a form.

    How?

  2. Switch to Form view or Datasheet view.

  3. Move to the record in which you want to insert the object, and click the OLE Object field in a Microsoft Access database (.mdb), or the image column in a Microsoft Access project (.adp).

  4. On the Insert menu, click Object.

  5. In the Insert Object dialog box, click Create New if it's not already selected, and then click the kind of object that you want to create in the Object Type box.

  6. Select the Display As Icon check box if you want the object to appear as an icon instead of the object itself. Displaying an object as an icon can be helpful when an object contains supplementary information that doesn't have to be displayed. Displaying an object as an icon also uses significantly less disk space.

  7. Click OK.

  8. Create the object by using the application that you chose in step 5, and then do one of the following:
    • If you created the object in place, click the form outside the bound object frame. If you click Exit on the File menu, you'll quit Microsoft Access.

    • If the object that you created opened in a separate window, click Exit on the File menu of the OLE server application. If you're prompted to update the document, click OK.
  9. If you're in Form view, Microsoft Access displays the object. If you're in Datasheet view, Microsoft Access displays the name of the object, for example, "Bitmap Image."

  10. If you need to edit the object, double-click it.

Notes

  • You can adjust the size and proportions of the object after you paste it.

    How?

  • You can also insert a bound object in a table or query datasheet. Just select the field that you want to insert the object into (it must be an OLE Object field or an image column), and then follow steps 4 through 9. To see the object, you must create a bound object frame on a form or report.


 Create and insert an unbound object on a form or report

Create and insert an unbound object on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Click the Unbound Object Frame tool [image] in the toolbox.

  3. On the form or report, click where you want to insert the object.

  4. In the Insert Object dialog box, click Create New if it's not already selected, and then in the Object Type box, click the object type you want to create.

  5. Select the Display As Icon check box if you want the object to appear as an icon instead of as the object itself. Displaying an object as an icon can be helpful when an object contains supplementary information that doesn't have to be displayed. Displaying an object as an icon also uses significantly less disk space.

  6. Click OK. Microsoft Access creates an unbound object frame.

  7. Create the object by using the application that you chose in step 4, and then do one of the following:
    • If you created the object in place, click the form outside the bound object frame. If you click Exit on the File menu, you'll quit Microsoft Access.

    • If the object that you created opened in a separate window, click Exit on the File menu of the OLE server application. If you're prompted to update the document, click OK.

If you want to edit the object, double-click it.

Notes

  • You can adjust the size and proportions of the object after you paste it.

    How?

  • In many cases, you'll edit an unbound object from form or report Design view. If you want to be able to edit the object from Form view also, then set the Enabled property of the unbound object frame to Yes and the Locked property to No.


 Create a field that performs custom calculations or manipulates field values in a query

Create a field that performs custom calculations or manipulates field values in a query

You can create a new field that displays the results of a calculation you define with an expression.

  1. Open the query in Design view.

  2. Do one of the following:
    • Type an expression in an empty cell in the Field row. If the expression includes a field name, you must place brackets around the name.

    Brackets around field names in an expression

    • If you need help creating the expression, use the Expression Builder. To display it, right-click in the Field cell where you're adding the calculated field, and then click Build. For information on how to use the Expression Builder, click [image] .

      After you press ENTER or move to another cell, Microsoft Access enters the default field name ExprN, where N is an integer incremented for each new expression field in the query. The name appears before the expression and is followed by a colon. In a datasheet, this name is the column heading.

    Replace Expr1 to change the expression's default field name

    You can select ExprN and type a more descriptive name, such as NewPrice.

  3. If the expression includes one or more aggregate functions (Sum, Avg, Count, Min, Max, StDev, or Var), and if the design grid includes another field or fields that you want to use for grouping, click Totals [image] on the toolbar (unless the Total row is already displayed). Leave Group By in the Total cell for the grouping field, and in the calculated field, change Group By to Expression.

    To group records, add Group By and Expression in the Total row

  4. If you want, do any of the following to complete the query:
    • Enter criteria to affect the calculation. For more information, click [image] .

    • Sort the results. For more information, click [image] .

    • Set field properties such as Format (since the field doesn't inherit properties from the underlying table). For more information, click [image] .

Notes

  • The Order Details Extended query in the Northwind sample database has an example of a calculated field called ExtendedPrice. The Order Subtotals query has an example of a calculated field called Subtotal that calculates on groups of records. To view these queries, open the Northwind database in your Office folder's Samples subfolder and then open the Order Details Extended or Order Subtotals query in Design view. For information on opening Northwind, click [image] .

  • To enter or view an entire expression without scrolling, press SHIFT+F2 to display the Zoom box.

  • To see examples of expressions, click [image] .


 Create a field that looks up data from another table in Design view

Create a field that looks up data from another table in Design view

  1. In Design view, open the table where you want to add the lookup field.

  2. Do one of the following:
    • To insert a new field within the table, click in the row below where you want to add the field, and then click Insert Rows [image] on the toolbar, or to add a new field at the end of the table, click in the first blank row. Type the name for the field in the Field Name column, following Microsoft Access object-naming rules.

    • If the field you want to use as the foreign key for the Lookup field already exists, click in that field's row. For example, if you have a Products table that has a SupplierID field already defined, and you want to change it to a Lookup field to display supplier names from your Suppliers table, click in the SupplierID field's row.
  3. In the Data Type column, click the arrow and select Lookup Wizard.

  4. Click the option that indicates you want the Lookup field to look up the values in a table or query.

  5. Click Next and follow the directions in the remaining Lookup Wizard dialog boxes.

    When you click the Finish button, Microsoft Access creates the Lookup field and sets certain field properties based on the choices you made in the wizard. Once you've created a Lookup list field, if you add the field to a form, Microsoft Access copies its definition into the form. The combo box or list box is created automatically for the form. However, if you change the definition of a Lookup or value list field in the table after adding it to a form, those changes will not be reflected in that form. To correct this, delete the field from the form and then add it again. For information on the properties that the Lookup Wizard sets, click [image] .

Note It is also possible to add a Lookup field to a table that displays values from the same table that contains the Lookup field. For example, in the Employees table of the Northwind sample database the ReportsTo field is a Lookup field that displays data from the FirstName and LastName fields by looking up the corresponding EmployeeID in the same table.


 Create a field that looks up data from another table in Datasheet view

Create a field that looks up data from another table in Datasheet view

  1. In Datasheet view, open the table where you want to add the lookup field.

  2. To insert the Lookup field within the table, click in the column to the right of where you want to insert the field, and then on the Insert menu, click Lookup Column.

  3. In the first dialog box of the Lookup Wizard, select the option that indicates you want the Lookup field to look up the values in a table or query.

  4. Click Next and follow the directions in the remaining Lookup Wizard dialog boxes.

    When the Lookup Wizard is finished, the Lookup field is added to your datasheet. By default, the new Lookup field will be given a name in the datasheet, "Field#," where # is some number. You can change this name if you want. To find out how to change a field name in Datasheet view, click [image] .

Notes

  • When you use the Lookup Wizard to create a Lookup list, Microsoft Access sets certain field properties based on the choices you made in the wizard. Once you've created a Lookup list field, if you add the field to a form, Microsoft Access copies its definition into the form. The combo box or list box is created automatically for the form. However, if you change the definition of the field in the table after adding it to a form, those changes will not be reflected in that form. To correct this, delete the field from the form and then add it again. For information on the properties that the Lookup Wizard sets, click [image] .

  • It is also possible to add a Lookup field to a table that displays values from the same table that contains the Lookup field. For example, in the Employees table of the Northwind sample database, the ReportsTo field is a Lookup field that displays data from the FirstName and LastName fields by looking up the corresponding EmployeeID.


 Create a field to store paths to pictures

Create a field to store paths to pictures

  1. Create a field in a table and set the field's data type to Text in a Microsoft Access database or varchar in a Microsoft Access project. How to add a field to a table in Design view in a Microsoft Access database. How to insert a column into a table in an Access project.

  2. In Datasheet view, type the path to the image (a .bmp, .jpeg, .gif, .dib, .wmf, or .emf file) in the field you created.


 Create a filter that finds records on an ungrouped data access page

Create a filter that finds records on an ungrouped data access page

  1. Open the data access page in Design view.

  2. If the fields you want to display aren't in the section already, add the fields as bound text boxes. Make sure you add the field you want to use to filter records.

    Note If there is no section on the page, add an unbound section.

  3. Click the Dropdown list tool in the toolbox.

  4. In the field list, use the right mouse button to drag the field whose values you want to use to filter records.

  5. On the shortcut menu, click Group Filter Control.

  6. Customize the record navigation control. For example, on a page that finds one record at a time, not all of the buttons will be enabled. You can show only the New, Delete, Save, Undo, and Help buttons on the record navigation toolbar.

    Test the filter in Page view or Microsoft Internet Explorer. Once you select a value from the drop-down list, the records that contain that value are displayed on the page, and the record navigation bar is enabled.


 Create a form by using AutoForm

Create a form by using AutoForm

AutoForm creates a form that displays all fields and records in the underlying table or query. If the record source you select has related tables or queries, the form will also include all the fields and records from those record sources.

  1. In the Database window, click Forms [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. In the New Form dialog box, click one of the following wizards:
    • AutoForm: Columnar Each field appears on a separate line with a label to its left.

    • AutoForm: Tabular The fields in each record appear on one line, with the labels displayed once at the top of the form.

    • AutoForm: Datasheet The fields in each record appear in row-and-column format, with one record in each row and one field in each column. The field names appear at the top of each column.
  4. Click the table or query that contains the data you want to base your form on.

  5. Click OK.

Microsoft Access applies the last autoformat you used to the form. If you haven't created a form with a wizard before or haven't used the AutoFormat command on the Format menu, it uses the Standard autoformat.

Tip You can also create a columnar AutoForm based on the open record source or the record source that's selected in the Database window. Click AutoForm on the Insert menu, or click the arrow next to the New Object button on the toolbar, and then click AutoForm. If the record source you select has related tables, AutoForm adds a subform control that contains the related tables displayed as datasheets and subdatasheets.


 Create a form with a subform that contains another subform

Create a form with a subform that contains another subform

Before using this procedure, make sure you've set up your table relationships correctly.

You can use this procedure to create a form and two levels of subforms that have a one-to-many relationship. The main form has a one-to-many relationship with the first subform, and the first subform has a one-to-many relationship with the second subform.

  1. Create a form with a subform.

    How?

    Note Make sure to select the Tabular (the equivalent of Form view) option when the wizard asks what layout you want for the subform. If you select the Datasheet option, you won't be able to insert a subform inside the subform.

  2. In Design view of the main form, make sure the subform control is selected. After it’s selected, you can click again inside the control to select the form, a section, or a control, just as you would if you opened the subform in Design view from the Database window.

  3. Do one of the following:
    • Use the Subform Wizard to create the second subform.

      How?

    • Drag a form, table, or query from the Database window to the subform.

      Microsoft Access creates another subform inside the first subform and creates a form for the subform.

  4. Switch to Form view to see the form and subforms.

Notes

  • For information on changing the layout of a subform, click [image] .

  • For information on troubleshooting subforms, click [image] .


 Create a blank form and select a record source

Create a blank form and select a record source

  1. In the Database window, click Forms [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. In the New Form dialog box, click Design View.

  4. Click the name of the table or other record source that includes the data you want to base your form on. If the form won't contain data (for example, if you want to create a form to use as a switchboard to open other forms or reports, or if you want to create a custom dialog box), don't select anything from this list.

    Note If you want to create a form that uses data from more than one table, base your form on a query.

  5. Click OK.

Microsoft Access displays the form in Design view. For information on what you can do in Design view, click [image] .


 Create a form and a subform at the same time

Create a form and a subform at the same time

Before using this procedure, make sure you've set up your table relationships correctly.

  1. In the Database window, click Forms [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. In the New Form dialog box, double-click Form Wizard in the list.

  4. In the first wizard dialog box, select a table or query from the list. For example, to create a Categories form that displays products for each category in a subform, select the Categories table (the "one" side of the one-to-many relationship).

  5. Double-click the fields you want to include from this table or query.

  6. In the same wizard dialog box, select another table or query from the list. Using the same example, select the Products table (the "many" side of the one-to-many relationship in the Categories form example).

    Note It doesn't matter which table or query you choose first.

  7. Double-click the fields you want to include from this table or query.

  8. When you click Next, if you set up the relationships correctly before starting the wizard, the wizard asks which table or query you want to view by. Using the same example, to create the Categories form, click By Categories.

  9. In the same wizard dialog box, select the Form With Subform(s) option.

  10. Follow the directions in the remaining wizard dialog boxes. When you click Finish, Microsoft Access creates two forms, one for the main form and subform control, and one for the subform.

Notes

  • For information on changing the layout of a subform that the wizard creates, click [image] .

  • For information on troubleshooting subforms, click [image] .


 Create a form with two subforms

Create a form with two subforms

Before using this procedure, make sure you've set up your table relationships correctly.

You can use this procedure to create a form and two subforms that have a one-to-many-to-many relationship. The main form has a one-to-many relationship with the first subform, and the first subform has a one-to-many relationship with the second subform.

  1. In the Database window, click Forms [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. In the New Form dialog box, double-click Form Wizard in the list.

  4. In the first wizard dialog box, select the table or query for the main form. For example, suppose you want to create a Customers form that has two subforms — an Orders subform and an Order Details subform. Select the Customers table (the "one" side of the first one-to-many relationship).

  5. Double-click the fields you want to include from this table or query.

  6. In the same wizard dialog box, select the table or query for the first subform. Using the same example, select the Orders table (the "many" side of the first one-to-many relationship), and then double-click the fields you want to include from this table or query.

    Note It doesn't matter which table or query you choose first.

  7. In the same wizard dialog box, select the table or query for the second subform. Using the same example, select the Order Details table (the "many" side of the second one-to-many relationship), and then double-click the fields you want to include from this table or query.

  8. When you click Next, if you set up the relationships correctly before starting the wizard, the wizard asks which table or query you want to view by. Using the same example, to create the Customers form, click By Customers.

  9. In the same wizard dialog box, select the Form With Subform(s) option.

  10. Follow the directions in the remaining wizard dialog boxes. When you click Finish, Microsoft Access creates a main form with two subform controls. It also creates two other forms, one for each subform.

Notes

  • When you use a wizard to create a form with two subforms, Microsoft Access synchronizes the subforms by attaching an event procedure to the OnCurrent property of the first subform. You can copy and modify this event procedure if you want to synchronize more subforms on the same form. To see this event procedure, open the first subform in Design view, double-click the form selector, and then click the Build button [image] next to the OnCurrent property.

  • The Customer Orders form in the Northwind sample database is a form with two subforms. To view this form, open the Northwind database in your Office folder's Samples folder, and then open the Customer Orders form in Design view. For information on opening Northwind, click [image] .

  • For information on changing the layout of a subform that the wizard creates, click [image] .

  • For information on troubleshooting subforms, click [image] .


 Create a form with a wizard

Create a form with a wizard

  1. In the Database window, click Forms [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. In the New Form dialog box, click the wizard that you want to use. A description of the wizard appears in the left side of the dialog box.

  4. Click the name of the table or other record source that includes the data you want to base your form on.

    Note You don't need to do this step if you click the Form Wizard option — you can specify the record source for the form in the wizard.

  5. Click OK.

  6. If you clicked Form Wizard, Chart Wizard, or PivotTable Wizard in step 3, follow the directions in the wizard dialog boxes. If you clicked AutoForm: Columnar, AutoForm: Tabular, or AutoForm: Datasheet, Microsoft Access automatically creates your form.

    If the resulting form doesn't look the way you want, you can change it in Design view.

    How?

Note If you click one of the AutoForm options, Microsoft Access uses the autoformat you last specified, either in the Form Wizard or using the AutoFormat command on the Format menu in Design view.


 Create a filter that finds records on a grouped data access page

Create a filter that finds records on a grouped data access page

  1. Open the data access page in Design view.

  2. If the fields you want to display aren't in the section already, add the fields to the page as bound HTML controls, or add the fields as bound text boxes. Make sure you add the field you want to use to filter records.

    Notes

    • The page will load faster in Page view and in Internet Explorer if you use bound HTML controls.

    • If there is no section on the page, add an unbound section.
  3. Make sure the control bound to the field whose values you want to use to filter records is selected.

  4. Do one of the following:
    • To group just on that one field, click Promote [image] on the toolbar.

    • To group on the whole table or query that contains that field, click Group By Table [image] on the toolbar.

    Microsoft Access adds a group header with an expand control and a record navigation section with a record navigation control. If you grouped on one field, Access moves the control you grouped on to the group header. If you grouped on a table or query, Access moves all the controls, including controls bound to fields that are in that table or query and controls bound to Lookup fields, to the group header.

  5. Click the Dropdown list tool in the toolbox.

  6. In the field list, use the right mouse button to drag the field whose values you want to use to filter records to the group header you created in step 4.

  7. On the shortcut menu, click Group Filter Control.

The following steps are optional. They remove features that were added by default for a grouped page but aren't necessary when using the group filter control.

  8. Select the expand control in the header that contains the filter control, and then press DELETE.

  9. Select the record navigation section for the group level that contains the filter control, and then press DELETE. Access deletes the section and the navigation control that it contains.

  10. Customize the record navigation control for the lower group level. For example, hide the buttons that add and delete records.

Notes

  • If the group header also contains a control that calculates a total or other aggregate, when you choose a group from the group filter, the calculated control displays the correct total or other aggregate for that group of records.

  • You can have multiple group levels, each with one group filter. For example, you can create a group filter for a Country field, then in the next lower group level, create a group filter for the City field, and so on.


 Create an input mask for a control

Create an input mask for a control

  1. Open a form in Design view.

  2. Select a text box or a combo box, and then click Properties [image] on the toolbar to open the control's property sheet.

  3. Do one of the following:
    • Type the input mask definition. For information on how to define an input mask, click [image] .

    • In a Microsoft Access database (.mdb), click the Build button [image] in the InputMask property box to start the Input Mask Wizard, and then follow the instructions in the wizard dialog boxes.


 Create a new data access page and create a hyperlink to the page at the same time

Create a new data access page and create a hyperlink to the page at the same time

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. On the Insert menu, click Hyperlink.

  3. In the Insert Hyperlink dialog box, click Create new page under Link to.

  4. In the Text to display box, type the text that you want displayed in the field or text box. If you leave the box blank, then Microsoft Access will use the hyperlink address and/or subaddress as the display text.

  5. Click ScreenTip, and type the text that you want to appear when the user rests the pointer on the hyperlink. If you leave the ScreenTip text box blank, Microsoft Access will display the hyperlink address and/or subaddress as the ScreenTip.

  6. In the Name of new document box, type a name for the new page.

    Tip You can create a different type of document — for example, a Microsoft Word file or a Microsoft Excel spreadsheet — by typing the three-letter file extension for the type of file you want to create. However, you can't create a Microsoft Access database (.mdb) or a Microsoft Access project (.adp).

  7. Microsoft Access creates the new page in the current folder. To specify a different location, click Change.

  8. Select an option under When to edit. You can edit the new page immediately or wait until later.

  9. Click OK.

    Microsoft Access adds the hyperlink in a hyperlink control to the data access page. In a form or report, it adds the hyperlink in a label. To test the link on a data access page, switch to Page view and click the hyperlink. To test the link on a form or report, right-click the label, point to Hyperlink on the shortcut menu, and then click Open.


 Create a hyperlink to an object in the current database

Create a hyperlink to an object in the current database

  1. Open a form in Design view or a report in Design view.

  2. Click Insert Hyperlink [image] on the toolbar.

  3. In the Insert Hyperlink dialog box, click Object in this database under Link to.

  4. In the Text to display box, type the text that you want displayed in the field or text box. If you leave the box blank, then Microsoft Access will use the type of object and the object name as the display text.

  5. Click ScreenTip, and type the text that you want to appear when the mouse pointer hovers over the hyperlink. If you leave the ScreenTip text box blank, then Microsoft Access will display the type of object and the object name as the ScreenTip.

  6. From the list, select the database object that you want to link to.

  7. Click OK.

    Microsoft Access adds the hyperlink in a label. To test the link, right-click the label, point to Hyperlink on the shortcut menu, and then click Open.

Note To link to an object in another database, link to the database file and then click Bookmark to select the object.


 Create a hyperlink that creates an e-mail message when clicked

Create a hyperlink that creates an e-mail message when clicked

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. On the Insert menu, click Hyperlink.

  3. In the Insert Hyperlink dialog box, click E-mail address under Link to.

  4. In the Text to display box, type the text that you want displayed in the field or text box. If you leave the box blank, then Microsoft Access will use the e-mail address as the display text.

  5. Click ScreenTip, and type the text that you want to appear when the mouse pointer hovers over the hyperlink. If you leave the ScreenTip text box blank, then Microsoft Access will display the e-mail address as the ScreenTip.

  6. In the E-mail address box, type an e-mail address. Or select an address from the Recently used e-mail addresses list.

  7. In the Subject box, type the information that you want to appear in the Subject field of the e-mail message.

    Note Some Web browsers and e-mail programs might not recognize the subject line.

  8. Click OK.

    On a data access page, Microsoft Access adds the hyperlink in a hyperlink control. In a form or report, it adds the hyperlink in a label. To test the link on a page, switch to Page view and click the hyperlink. To test the link in a form or report, right-click the label, point to Hyperlink on the shortcut menu, and then click Open. Microsoft Access opens your mail program and creates a new message, with the address and subject filled in.


 Create a link to a Web page by using an image on a data access page

Create a link to a Web page by using an image on a data access page

  1. Open a data access page in Design view.

  2. Click the Hotspot Image tool Hotspot Image control in the toolbox.

  3. Click on the data access page where you want to place the image.

  4. In the Insert Picture dialog box, select the graphic that you want to place on the page. You can use .bmp, .wmf, .emf, .gif, and .jpeg file formats.

  5. Click OK.

  6. In the Insert Hyperlink dialog, type the Internet address to link the image to, or select it from the list.

  7. Click OK.


 Create a macro

Create a macro

  1. In the Database window, click Macros [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. In the Action column, click in the first cell and then click the arrow to display the action list.

  4. Click the action you want to use.

  5. Type a comment for the action. Comments are optional, but make your macro easier to understand and maintain.

  6. In the lower part of the window, specify arguments for the action, if any are required. For tips on setting action arguments, click [image] .

  7. To add more actions to the macro, move to another action row, and repeat steps 3 through 6. Microsoft Access carries out the actions in the order you list them.

Tip To quickly create a macro that carries out an action on a specific database object, drag the object from the Database window to an action row in the Macro window. For example, you can create a macro that opens a form by dragging the form to an action row. To do this, click Tile Vertically on the Windows menu to position the Macro window and Database window so that they're side by side on your screen; in the Database window under Objects, click the object type you want, click the object, and then drag it to an action row. Dragging a macro or stored procedure adds an action that runs the macro or procedure, while dragging other database objects adds an action that opens the object.


 Create a modeless pop-up form

Create a modeless pop-up form

  1. Create the form. The form can include any combination of controls.

  2. In form Design view, double-click the form selector to open the property sheet for the form.

  3. In the PopUp property box, click Yes.

  4. In the BorderStyle property box, click Thin if you don't want the form to be sizable; otherwise, skip to the next step. If you select the Thin setting, you can move the pop-up form, but you can't size it.

  5. Create a macro or event procedure that opens the form.

    Note To see an example of an event procedure that displays a modeless pop-up form, click the Build button [image] next to the OnClick property box of the Review Products button on the Suppliers form in the Northwind sample application.

  6. Attach the macro or event procedure to a form or report by specifying the macro name or event procedure as the setting for the appropriate event property. For example, type the name of the macro or event procedure in the OnClick property box of a command button.

Notes

  • To position a pop-up form on the screen, open the form in Design view, maximize the Microsoft Access window, position the form where you want it, and then save the form. The form will appear in this location when it's opened (assuming the AutoCenter property is set to No and you haven't specified its position in the event procedure that opens the pop-up form).

  • For information on other properties you might want to set for a pop-up form, click [image] .


 Create a multiple-field index

Create a multiple-field index

  1. Open the table in Design view.

  2. Click Indexes [image] on the toolbar.

  3. In the first blank row in the Index Name column, type a name for the index. You can name the index after one of the index fields, or use some other appropriate name.

  4. In the Field Name column, click the arrow and select the first field for the index.

  5. In the next row in the Field Name column, select the second field for the index. (Leave the Index Name column blank in that row.) Repeat this step until you have selected all the fields you want to include in this index. You can use up to 10 fields.

Note The default sort order is Ascending. Select Descending in the Sort Order column of the Indexes window to sort the corresponding field's data in descending order.


Create a new switchboard that you can open from the opening switchboard

  1. Open the database.

  2. Do one of the following to open the Switchboard Manager dialog box:
    • If you created the switchboard by using the Database Wizard, click Change Switchboard Items in the opening switchboard.

    • If you created the switchboard by using the Switchboard Manager, click Add-ins on the Tools menu, and then click Switchboard Manager.
  3. Click New.

  4. Type the name of the new switchboard, and then click OK.

    Microsoft Access adds the switchboard to the Switchboard Pages box.

  5. Click the new switchboard, and then click Edit.

  6. Click New.

  7. Type the text for the first switchboard item in the Text box, and then click a command in the Command box. For example, type View Recording Artists, and then click Open Form In Edit Mode in the Command box.

  8. Depending on which command you click, Microsoft Access displays another box below the Command box. Click an item in this box, if necessary. For example, if you clicked Open Form In Edit Mode in step 7, click the name of the form you want to open in the Form box, such as Recording Artists, and then click OK.

  9. Repeat steps 6 through 8 until you've added all the items to the switchboard. If you want to edit or delete an item, click the item in the Items On This Switchboard box, and then click Edit or Delete. If you want to rearrange items, click the item in the box, and then click Move Up or Move Down.

  10. When you've finished creating the switchboard, click Close.


 Create an option group without a wizard

Create an option group without a wizard

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the Control Wizards tool [image] in the toolbox if it's pressed in. This turns off the wizard.

  3. In the toolbox, click the Option Group tool [image] .

  4. Do one of the following:
    • If you want to create an unbound option group, click where you want to place the group frame.

    • If you want to create a bound option group, click Field List [image] on the toolbar to display the field list, and then drag the appropriate field or column from the field list to the form, report, or data access page. Fields and columns are placed in the option group as text boxes. In a form or report, if the field list button or command isn't available, you need to bind the form or report to a record source. In a data access page, if the field list is empty, you must connect the page to a database.

    Note You must drag the field or column from the field list. If you click the field in the field list and then click the form, report, or data access page, the control won't be bound.

  5. In the form or report toolbox, click the Check Box Check Box control , Option Button [image] , or the Toggle Button tool [image] . In the data access page toolbox, click the Option Button [image] .Then click inside the group frame where you want the upper-left corner of the check box, option button, or toggle button to appear. When the user rests the pointer over the frame in a form or report, Microsoft Access highlights the option group to indicate that controls placed within it become part of the option group.

    When Access creates the first control inside an option group on a form or report, it sets the control's OptionValue property to 1. On a data access page, you must set the Value property of each option button to a number or any text that’s meaningful for the field the group frame is bound to.

  6. Repeat step 5 for each control you add to the option group. On a form or report, Access sets the OptionValue property of the second option to 2, the third to 3, and so on.

Notes

  • For information on aligning the controls in the group frame to each other in forms and reports, click [image] . For information on aligning the controls in a group frame to each other in data access pages click [image] .

  • For information on spacing controls evenly in forms and reports, click [image] .

  • To facilitate data entry, you can make the most commonly chosen option the default.

    How?

  • If you create a check box, option button, or toggle button outside an option group, and you want to add that control to an option group, you must cut and paste the control into the option group (select the option group frame before you paste). When you cut and paste, Microsoft Access sets the OptionValue property for the control on a form or report to -1 so that you must reset the property to the value you want. If you drag an existing control into a group frame, the control doesn't become part of the option group.


 Create an option group with a wizard on a form or report

Create an option group with a wizard on a form or report

For best results in a Microsoft Access database, create option groups only for fields whose data type is Number (and whose FieldSize property is set to Integer or Long Integer) or Yes/No. In a Microsoft Access project, create option groups only for columns whose data type is Int, SmallInt, TinyInt, and Bit. For fields or columns with other data types, use a list box, drop-down list box, or combo box.

  1. Open a form in Design view or a report in Design view.

  2. Click the Control Wizards tool [image] in the toolbox if it's not already pressed in.

  3. In the toolbox, click the Option Group tool [image] .

  4. On the form or report, click where you want to place the upper-left corner of the option group.

  5. Follow the directions in the wizard dialog boxes. In the last dialog box, click Finish to display the option group in Design view.


 Create a picture as a hyperlink

Create a picture as a hyperlink

You can use a picture as a hyperlink on a form, report, or data access page. Although hyperlinks in a report won't work when viewed in Microsoft Access, the hyperlinks will work when you output the report to Microsoft Word, to Microsoft Excel, or to HTML.

What do you want to do?

Create a link to an existing file or Web page

Create a data access page and create a hyperlink to that page

Create a link from one data access page to another in the current database

Create a link to a table, query, form, report, or data access page in the current database

Create a hyperlink that opens my e-mail program and creates a message addressed to the specified e-mail address


Create Views/Procedures/Queries Example

This example creates and executes both an action query and a standard select query by creating an ADO command object and appending it to the ADO procedures and views collections.

Notes

Currently creating procedures and views is not supported in ADPs with the version of the SQL provider shipped with Microsoft Access 2000. A reference to "Microsoft ADO ext. 2.1 for DDL and Security" must be set to use this example.

The RunQuery function is required for this procedure to run.

Sub CreateQueryX()
    Dim catNorthwind As New ADOX.Catalog
    Dim cdView As New ADODB.Command
    Dim cdProc As New ADODB.Command
    Dim tblTemp As New ADOX.Table

    Set catNorthwind.ActiveConnection = CurrentProject.Connection

    With catNorthwind
        Set cdProc.ActiveConnection = CurrentProject.Connection
        Set cdView.ActiveConnection = CurrentProject.Connection

        With tblTemp
            .Name = "tblTemp"
            With .Columns
                .Append "EmpID", adInteger
                .Append "LastName", adVarWChar
                .Append "FirstName", adVarWChar
            End With
        End With
        .Tables.Append tblTemp

        ' Create a new action Query.
        cdProc.CommandText = "Insert Into tbltemp " _ & "(EmpID, LastName, FirstName) Select EmployeeID, " _ & "LastName, FirstName From Employees Where Title =" _ & "'Sales Representative'"

        ' Append to database
        .Procedures.Append "PopulateTmptbl", cdProc

        RunQuery "PopulateTmptbl"

        ' Create new select Query
        cdView.CommandText = "SELECT * FROM tblTemp"
        .Views.Append "NewQuery", cdView

        RunQuery "NewQuery"

 ' Delete new objects because this is a demonstration.
        .Views.Delete "NewQuery"
        .Procedures.Delete "PopulateTmptbl"
        .Tables.Delete tblTemp.Name
    End With
    Set catNorthwind = Nothing
End Sub

Function RunQuery(qryName As String)
    Dim qryTemp As Object
    Dim cat As New ADOX.Catalog
    Dim intNumRecs As Integer

    Set cat.ActiveConnection = CurrentProject.Connection

    On Error Resume Next
    Set qryTemp = cat.Procedures(qryName)
    If Err.Number <> 0 Then
        Set qryTemp = cat.Views(qryName)
        Err.Number = 0
    End If
    On Error GoTo 0

    If TypeOf qryTemp Is ADOX.View Then
        'If Select query display number of records
        Debug.Print "Number records in " & qryName
          Debug.Print DLookup("Count(*)", qryName)
    Else
        'If Action query display affected records
        qryTemp.Command.Execute intNumRecs
        Debug.Print "Number of Records affected"
          Debug.Pring intNumRecs
    End If

    Set cat = Nothing
    Set qryTemp = Nothing

End Function


 Create a report using AutoReport

Create a report using AutoReport

AutoReport creates a report that displays all fields and records in the underlying table or query.

  1. In the Database window, click Reports [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. In the New Report dialog box, click one of the following wizards:
    • AutoReport: Columnar. Each field appears on a separate line with a label to its left.

    • AutoReport: Tabular. The fields in each record appear on one line, and the labels print once at the top of each page.
  4. Click the table or query that contains the data you want to base your report on.

  5. Click OK.

    Microsoft Access applies the last autoformat you used to the report. If you haven't created a report with a wizard before or haven't used the AutoFormat command on the Format menu, it uses the Standard autoformat.

Tip You can also create a single-column report based on the open table or query or on the table or query selected in the Database window. Click AutoReport on the Insert menu, or click the arrow next to the New Object button on the toolbar, and then click AutoReport. Reports created with this method don't have a report header and footer or a page header and footer.


 Create a blank report and select a record source

Create a blank report and select a record source

  1. In the Database window, click Reports [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. In the New Report dialog box, click Design View.

  4. Click the name of the table or query that contains the data you want to base your report on. (If you want an unbound report, don't select anything from this list.)

    Tip If you want to create a report that uses data from more than one table, base your report on a query.

  5. Click OK.

    Microsoft Access displays the report in Design view. For information on what you can do in Design view, click [image] .


 Create a report with a wizard

Create a report with a wizard

  1. In the Database window, click Reports [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. In the New Report dialog box, click the wizard that you want to use. A description of the wizard appears in the left side of the dialog box.

  4. Click the table or query that contains the data you want to base your report on.

    Note Microsoft Access uses this table or query as the default record source for the report. However, you can change the record source in the wizard and select fields from other tables and queries.

  5. Click OK.

  6. If you clicked Report Wizard, Chart Wizard, or Label Wizard in step 3, follow the directions in the wizard dialog boxes. If you click AutoReport: Tabular or AutoReport: Columnar, Microsoft Access automatically creates your report.

    If the resulting report doesn't look the way you want, you can change it in Design view.


 Create an unbound scrolling text control on a data access page

Create an unbound scrolling text control on a data access page

  1. Open a data access page in Design view.

  2. Click the Scrolling Text tool Scroll Text control in the toolbox.

  3. In the data access page, click where you want the upper-left corner of the scrolling text control to be; Microsoft Access creates a default-sized control. To create a scrolling text control of a particular size, click in the data access page and then drag until the control is the size you want.

  4. Select the default text in the scrolling text control, and then type the message you want to appear.


 Create separate tables for multiple sets of records from a pass-through query

Create separate tables for multiple sets of records from a pass-through query

  1. After creating the pass-through query, create a make-table query based on the pass-through query.

    How?

  2. In the make-table query, include all fields from the pass-through query by dragging the asterisk (*) to the design grid.

    When you run the make-table query, you get one table for each result. The first table created has the name defined in the query; subsequent tables have that name concatenated with a sequential number starting at 1. For example, if you want four tables created for four result sets and you choose "NewTable" as the new table name, the tables created will be named NewTable, NewTable1, NewTable2, and NewTable3.


 Create a single-field index

Create a single-field index

  1. Open a table in Design view.

  2. In the upper portion of the window, click the field that you want to create an index for.

  3. In the lower portion of the window on the General tab, click in the Indexed property box, and then click Yes (Duplicates OK) or Yes (No Duplicates).

    Click Yes (No Duplicates) if you want to ensure that no two records have the same data in this field.


 Create a subform and add it to an existing form

Create a subform and add it to an existing form

Before using this procedure, make sure you've set up your table relationships correctly.

  1. Open the form that you want to add the subform to in Design view.

  2. Make sure the Control Wizards tool [image] in the toolbox is pressed in.

  3. Click the Subform/Subreport tool [image] in the toolbox.

  4. On the form, click where you want to place the subform.

  5. Follow the directions in the wizard dialog boxes.

  6. When you click Finish, Microsoft Access adds a subform control to your form. It also creates a separate form for the subform.

Notes

  • For information on changing the layout of a subform that the wizard creates, click [image] .

  • For information on troubleshooting subforms, click [image] .


 Create a subreport in an existing report

Create a subreport in an existing report

If the subreport will be linked to the main report, make sure you've set up the table relationships correctly before using this procedure. For more information, click [image] .

  1. Open the report you want to use as the main report in Design view.

  2. Make sure the Control Wizards tool [image] in the toolbox is pressed in.

  3. Click the Subform/Subreport tool [image] in the toolbox.

  4. On the report, click where you want to place the subreport.

  5. Follow the directions in the wizard dialog boxes.

When you click the Finish button, Microsoft Access adds a subreport control to your report. It also creates a separate report that is displayed as the subreport.

Notes

  • For information on referring to the value of a control on a subreport, click [image] .

  • For information on troubleshooting subreports, click [image] .


 Create a switchboard form by using the Switchboard Manager

Create a switchboard form by using the Switchboard Manager

When you use the Database Wizard to create a database, the wizard creates a switchboard that makes it easy to navigate between the forms and reports in your database. If you want to build the same type of switchboard for a database you created yourself, you can use the Switchboard Manager.

  1. On the Tools menu, point to Add-ins, and then click Switchboard Manager.

  2. If Microsoft Access asks if you'd like to create a switchboard, click Yes.

  3. In the Switchboard Manager dialog box, click Edit.

  4. In the Edit Switchboard Page dialog box, type a name for the switchboard in the Switchboard Name box, and then click New.

  5. In the Edit Switchboard Item dialog box, type the text for the first switchboard button in the Text box, and then click a command in the Command box. For example, type Review Products in the Text box, and then click Open Form In Edit Mode in the Command box.

  6. Depending on which command you click, Microsoft Access displays another box below the Command box. Click an item in this box, if necessary. For example, if you clicked Open Form In Edit Mode in the Command box in step 5, click the name of the form you want to open in the Form box, such as Review Products, and then click OK.

  7. Repeat steps 4 through 6 until you've added all the items to the switchboard. If you want to edit or delete an item, click the item in the Items On This Switchboard box, and then click Edit or Delete. If you want to rearrange items, click the item in the box, and then click Move Up or Move Down.

  8. Click Close.

Notes

  • You can use the Switchboard Manager to create a switchboard that branches to other switchboards. Use the preceding procedure to create one or more switchboards. To make a switchboard the switchboard that's automatically opened when you open the database, click the switchboard name in the Switchboard Manager dialog box, and then click Make Default. To have a switchboard branch to another switchboard, choose the Go To Switchboard command in the Command box in step 5 in the preceding procedure, and then specify the switchboard you want to go to.

  • When you create a switchboard with the Switchboard Manager, Microsoft Access creates a Switchboard Items table that describes what the buttons on the form display and do. If you make changes to the Switchboard form later in form Design view, the application may no longer work. If you expect to customize your switchboard form extensively, it's better to create the form from scratch and then specify it as the startup form. For information on designing a startup form, see "Creating an Application" in Building Applications with Forms and Reports.


 Create a table by entering data in a datasheet

Create a table by entering data in a datasheet

  1. If you haven't already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  2. Click Tables [image] under Objects, and then click New on the Database window toolbar.

  3. Double-click Datasheet View. A blank datasheet is displayed. The default column names are Field1, Field2, and so on.

  4. Rename each column you will use: double-click the column name, type a name for the column following Microsoft Access object-naming rules and then press ENTER.

  5. You can insert additional columns at any time: click in the column to the right of where you want to insert a new column, and then on the Insert menu, click Column. Rename the column as described in step 4.

  6. Enter your data in the datasheet.

    Enter each kind of data in its own column (each column is called a field in Microsoft Access). For example, if you are entering names, enter the first name in its own column and the last name in a separate column. If you are entering dates, times, or numbers, enter them in a consistent format so that Microsoft Access can create an appropriate data type and display format for the column. Any columns you leave empty will be deleted when you save the datasheet.

  7. When you've added data to all the columns you want to use, click Save [image] on the toolbar to save your datasheet.

  8. Microsoft Access asks you if you want to create a primary key. If you haven't entered data that can be used to uniquely identify each row in your table, such as part numbers or ID numbers, it's recommended that you click Yes. If you have entered data that can uniquely identify each row, you can specify this field as your primary key.

    How?

Microsoft Access will assign data types to each field (column) based on the kind of data you entered. If you want to customize a field's definition further — for example, to change its data type, or define a validation rule, use Design view.

Note In addition to renaming and inserting columns, you can delete or reorder columns at any time, before or after saving your new datasheet. For information on deleting a column, click [image] . For information on reordering columns, click [image] .


 Create a table from scratch in Design view

Create a table from scratch in Design view

  1. If you haven't already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  2. Click Tables [image] under Objects, and then click New on the Database window toolbar.

  3. Double-click Design View.

  4. Define each of the fields in your table.

    How?

  5. Define a primary key field before saving your table.

    How?

    Note You don't have to define a primary key, but it's usually a good idea. If you don't define a primary key, Microsoft Access asks if you want it to create one for you when you save the table. For more information on primary keys, click [image] .

  6. When you are ready to save your table, click Save [image] on the toolbar, and then type a name for the table following Microsoft Access object-naming rules.

Note For information on properties you can use to customize fields in a table, click [image] .


Create a table on my own

You can use the steps in this topic to guide you through creating a table from start to finish. You’ll use many of these steps in creating every table. The others you’ll use when you design a table to contain a particular type of data or define how a field appears. You need to use only the steps that are relevant to the type of data or field definitions specific to the table that you’re creating. For other tasks related to creating tables, ask the Answer Wizard.

See examples of what tables are and how they work

1 Create a table

Create a table from scratch using Design view

See examples of the kinds of tools you have to work with when designing a table

2 Add fields to the table that contain data

Create a field for text or memos

Create a field for numbers or currency

Create a field for dates or times

Create a field that looks up or lists values in tables

3 Define how a field appears or handles data

Define the number of decimal places to display in a field

Create an input mask to control how data is entered in a field

See examples of input masks

Define a default value that is automatically entered in a field

See examples of default values in fields

Define validation rules to control what values can be entered into a field

See examples of field validation rules

4 Create a primary key to uniquely identify records

Set or change the primary key

5 Create an index to find and sort records faster

Create a single-field index

Create a multiple-field index

6 Define relationships to bring data together from two or more tables

Define relationships between tables

Define the default join type for a relationship between two tables

7 Make final adjustments

Change a field name in Design view

Move a field in table Design view

Delete a field from a table in Design view


 Create tables automatically from your data

Create tables automatically from your data

  • Enter data directly into a blank datasheet. When you save the new datasheet, Microsoft Access will analyze your data and automatically assign the appropriate data type and format for each field.

    Create a table by entering data in a datasheet


 Create a table by using the Table Wizard

Create a table by using the Table Wizard

  1. If you haven't already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  2. Click Tables [image] under Objects, and then click New on the Database window toolbar.

  3. Double-click Table Wizard.

  4. Follow the directions in the Table Wizard dialog boxes.

Note If you want to modify or extend the resulting table, you can do so in Design view when you have finished using the Table Wizard.


Create New Table Example

Create Table Example

The following example creates a new Table object and appends it to the Tables collection of the current database.

Note A reference to "Microsoft ADO ext. 2.1 for DDL and Security" must be set to use this example.

Sub NewTable()
    Dim cat As New ADOX.Catalog, tbl As New ADOX.Table

    ' Return reference to current database.
    Set cat.ActiveConnection = CurrentProject.connection

    tbl.Name = "Contacts"

    ' Define column to table.
    tbl.Columns.Append "ContactName", adVarWChar, 40

    ' Append Table object to Tables collection of Catalog.
    cat.Tables.Append tbl
    cat.Tables.Refresh
    Set cat = Nothing
End Sub


 Create an unbound list box, drop-down list box, or combo box that displays fixed values

Create an unbound list box, drop-down list box, or combo box that displays fixed values

  1. Open a form in Design view or a data access page in Design view.

  2. Make sure that the Control Wizards tool [image] is pressed in the toolbox.

    Note Wizards are not available in a stand-alone data access page, or when you point a data access page to a database other than the one currently open. In this case, you will have to create a list box or drop-down list box on your own.

  3. Click the List Box tool List Box control , the Dropdown List tool , or the Combo Box tool in the toolbox.

  4. On the form or data access page, click where you want to place the list box, drop-down list box, or combo box.

  5. Follow the instructions in the wizard dialog boxes. When the wizard asks how you want to get the values for the list, select the option that says you'll type in the values that make up the list. When the wizard asks whether you want to store the value or remember it for later use, select the option that says you'll remember it for later use.

Notes

  • For information on properties that determine how a list box or combo box works in a form, click [image] . For information on properties that determine how a list box or drop-down list box works in a data access page, click [image] .

  • For information on troubleshooting list boxes, drop-down list boxes, and combo boxes, click [image] .


 Create an unbound list box, drop-down list box, or combo box that displays values from a table or query query

Create an unbound list box, drop-down list box, or combo box that displays values from a table or query

  1. Open a form in Design view or a data access page in Design view.

  2. Make sure that the Control Wizards tool [image] is pressed in the toolbox.

    Note Wizards are not available in a stand-alone data access page or when you point a data access page to a database other than the one currently open. In both cases, you will have to create the list box or drop-down list box on your own.

  3. Click the List Box tool List Box control , the Dropdown List tool , or the Combo Box tool in the toolbox.

  4. On the form or data access page, click where you want to place the list box, drop-down list box, or combo box.

  5. Follow the instructions in the wizard dialog boxes. When the wizard asks how you want to get the values for the list, select the option that says you want to look up values in a table or query. When the wizard asks whether you want to store the value or remember it for later use, select the option that says you'll remember it for later use.

Notes

  • For information on properties that determine how a list box or combo box works in a form, click [image] . For information on properties that determine how a list box or drop-down list box works in a data access page, click [image] .

  • When you use a wizard to create a list box or combo box based on a table or query in a form, Microsoft Access creates an SQL statement based on the fields you select and sets the RowSource property for the control to that SQL statement. If the list box or combo box isn't sorted the way that you want, you can modify the SQL statement by clicking the Build button [image] next to the RowSource property. For information on specifying a sort order in the SQL Statement Builder, click [image] .

  • When you use a wizard to create a drop-down list box based on a table or query in a data access page, Access sets the ListRowSource property to the table you specified in the wizard. If the drop-down list box isn't sorted the way that you want, you can create a query with a new sort order and select the query in the ListRowSource property box.

  • For information on troubleshooting list boxes, drop-down list boxes, and combo boxes, click [image] .


 Create an unbound text box

Create an unbound text box

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. Click the Text Box tool Text Box control in the toolbox.

  3. Click anywhere on the form, report, or data access page to create a default-sized text box, or drag to create a text box that's the size you want.


 Create a Microsoft Access user profile

Create a Microsoft Access user profile

To create a Microsoft Access user profile

  1. Start the Registry Editor.

    How

  2. Navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE subkey.

  3. Add three nested subkeys by using the following format to ensure uniqueness: \Your Company\Your Application\Your Application Version Number.

  4. Under the \Your Application Version Number subkey, re-create any of the subkeys located under the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\9.0\Access subkey that contain values that you want to modify (except the \Profiles subkey, which you will create in step 7), and then copy the appropriate values under each subkey.

  5. Modify the values that you want to change.

  6. Navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\9.0\Access subkey.

  7. Add a new subkey, and name it \Profiles.

  8. Add a string value to the \Profiles subkey, and give it the name that you want to use on the command line.

  9. For the value's data, enter a string that points to the location of the subkeys you created in step 3: \SOFTWARE\Your Company\Your Application\Your Application Version Number

  10. Create a command line for your application that specifies the name you entered in step 8, and enclose the name in double quotation marks ("). For example: MSAccess.exe /profile "Your Profile" "Your Application.mdb"

To override any of the Microsoft Jet 4.0 database engine default settings for Access

  1. Navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE\Your Company\Your Application\Your Application Version Number profile subkey.

  2. Create a subkey named \Jet\4.0\Engines.

  3. For each built-in driver's settings you want to override:

    Add an appropriately named subkey below the subkey created in step 2, for example, to override Jet Paradox settings, add a subkey named "Paradox."

    Add values of the appropriate name and type to that subkey, and then specify the settings.

    • You can model your subkeys and values after the subkeys and values in \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines.

Notes

  • You can use the acSysCmdProfile argument of the SysCmd method to determine whether your application has properly loaded your Access user profile (for example, your users might accidentally open your application through Windows Explorer and bypass the /profile command-line option). For more information, click [image] .

  • You can also use the Data Access Object (DAO) method DBEngine.SetOption to dynamically modify Jet registry values at run time for a single session, without permanently modifying the values in the Windows registry. For more information, click [image] .

  • In a Microsoft Access database or Microsoft Access project, it's possible to have the same registry key set in three different ways; but only one value can be used. In a case like this, an Access user profile setting takes precedence over an Access database or Access project setting, which in turn takes precedence over a Microsoft Jet setting. The following table illustrates this order of precedence by using the ODBC ConnectionTimeout setting as an example.
    Order | Location | Registry setting under \HKEY_LOCAL_MACHINE\SOFTWARE…
    1 | user profile | \Your Company\Your Application\Your Application Version Number\ODBC\ConnectionTimeout=100
    2 Microsoft Access \Microsoft\Office\9.0\Access\Jet\4.0\Engines
    \ODBC\ConnectionTimeout=300
    3 Microsoft Jet \Microsoft\Jet\4.0\Engines
    \ODBC\ConnectionTimeout=600

    If you start your application by using a command line that specifies the Access user profile, Access uses the ConnectionTimeout value of 100. If you start your application without using the Access user profile, Access uses the ConnectionTimeout value of 300.


 Create a validation rule for a control

Create a validation rule for a control

  1. Open a form in Design view.

  2. Make sure the control is selected, and then click Properties [image] on the toolbar to open the control's property sheet.

  3. In the ValidationRule property box, type the validation rule; or, in a Microsoft Access database (.mdb), click the Build button [image] to use the Expression Builder to create the validation rule.

    To see examples of validation rules, click [image] .

  4. In the ValidationText property box, type the error message that you want displayed if the text entered violates the validation rule.

Notes

  • If you need more room to type in a property box, press SHIFT+F2 to open the Zoom box.

  • In an Access database, if you set the ValidationRule property for the field in table Design view and also set the ValidationRule property for a control bound to that field, Microsoft Access enforces both rules — the control validation rule doesn't override the field validation rule.

  • Access validates a field when you change data and try to leave the field, save the record, switch views, or close the form.


 Create What's This tips for forms or controls

Create What's This tips for forms or controls

  1. Create the source file by using the text editor or word-processing program of your choice. For information about creating the source file, see the Help that comes with Microsoft Help Workshop. Make sure to save the source file in Rich Text Format.

  2. Compile the Help file by using Microsoft Help Workshop.

  3. Display the property sheet for the form and specify the file name for the compiled Help file in the HelpFile property box.

    Note For best results, put the Help file in the same folder as your application. That way, you can keep the setting for the HelpFile property the same for each site that uses your application, but allow users to install the application in the folder of their choice. If you omit a path setting in this property, Microsoft Access looks for the Help file in the folder where your application is installed.

  4. In the HelpContextID property box for the form, type the number of the topic (a number other than 0) that will be displayed when a user clicks the What's This button [image] and then clicks the background of the form. This topic would generally cover assistance for the whole form.

  5. In the HelpContextID property box for each control on the form that can receive the focus, type the number of the topic that will be displayed when the user clicks the What's This button [image] and then clicks the control.

Notes

  • You must map the values set for the HelpContextID property to the context strings in your Help system. For more information, see the Help file that comes with Microsoft Help Workshop.

  • If a control doesn't have a custom Help topic, the custom Help topic for the form will be displayed when the user clicks the What's This button [image] and then clicks the control. If there is no custom Help topic for the form, Microsoft Access displays the Office Assistant dialog box.

  • If you enter the context ID of the Help file topic as a positive number, the Help topic will be displayed in a full Help topic window. If you add a minus sign (–) in front of the context ID, the Help topic will be displayed in a pop-up window. It is important to note that the context ID does not have a negative number when authored in Microsoft Help Workshop. You must add the minus sign when setting the property to make the topic display in the pop-up window.

  • You can't display custom What's This tips through the Office Assistant.


 Create an expression without using the Expression Builder

Create an expression without using the Expression Builder

You create an expression by combining identifiers, operators, and values to produce the result you want. For example, the following expression increases the value displayed in the Freight control on the Orders form by 10 percent:

= [Forms]![Orders]![Freight] * 1.1

In this expression:

  • Forms![Orders]![Freight] is an identifier that refers to the value of the Freight control on the Orders form.

  • * is the multiplication operator.

  • 1.1 is the value by which Microsoft Access multiplies the value of the Freight control.

Depending on the result you want, you can combine identifiers, operators, and values in a variety of ways. You use expressions to combine strings of text, add or multiply numeric values, call functions, refer to objects and their values, and perform many other operations.

Some expressions produce a true or false result. For example, if you enter an expression in the Condition column of a macro, Microsoft Access carries out the specified action only when the expression evaluates to true. The following expression is true only if UK is the value displayed in the Country control on the Employees form:

Forms![Employees]![Country] = "UK"

For more information on using identifiers in expressions, click [image] .

For more information on operators, click [image] .

For more information on using values in expressions, click [image] .


 Customize Microsoft Excel driver settings

Customize Microsoft Excel driver settings

  1. Start the Registry Editor.

    How?

  2. Navigate to the \HKEY_LOCAL_MACHINE
    \SOFTWARE\Microsoft\Jet\4.0\Engines\Excel subkey and make the desired changes.

    For information on Microsoft Excel driver settings, click [image] .

  3. Exit the Registry Editor.

  4. Exit and restart Microsoft Access to use the new settings.

Important Changes to settings in these subkeys will affect all programs installed on the computer that use the Microsoft Jet database engine to access Microsoft Excel data. In addition to Microsoft Access 2000, this includes Microsoft Excel 2000, Microsoft Visual Basic 6.0 or later, and possibly others. To make changes that apply only to Access 2000, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE
\Microsoft\Office\9.0\Access\Jet\4.0\Engines
\Excel subkey, and then modify values there. If the \Excel subkey does not exist, create the subkey, and then add the values.

Note You can also use the Data Access Object (DAO) method, Application.DBEngine.SetOption to dynamically modify Microsoft Jet registry values at run-time for a single session, without permanently modifying the values in the Windows registry. For more information, click [image] .


 Customize Exchange driver settings

Customize Exchange driver settings

  1. Start the Registry Editor.

    How?

  2. Navigate to the \HKEY_LOCAL_MACHINE
    \SOFTWARE\Microsoft\Jet\4.0\Engines\Exchange subkey and make the desired changes.

    For information on Exchange driver settings, click [image] .

  3. Exit the Registry Editor.

  4. Exit and restart Microsoft Access to use the new settings.

Important Changes to settings in this subkey will affect all programs installed on the computer that use the Microsoft Jet database engine to access Microsoft Exchange data. In addition to Microsoft Access 2000, this includes Microsoft Excel 2000, Microsoft Visual Basic 6.0 or later, and possibly others. To make changes that apply only to Access 2000, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE
\Microsoft\Office\9.0\Access\Jet\4.0\Engines
\Exchange subkey, and then modify values there. If the \Exchange subkey does not exist, create the subkey, and then add the values.

Note You can also use the Data Access Object (DAO) method, Application.DBEngine.SetOption to dynamically modify Microsoft Jet registry values at run-time for a single session, without permanently modifying the values in the Windows registry. For more information, click [image] .


 Customize dBASE driver settings

Customize dBASE driver settings

  1. Start the Registry Editor.

    How?

  2. Navigate to the \HKEY_LOCAL_MACHINE
    \SOFTWARE\Microsoft\Jet\4.0\Engines\Xbase subkey and make the desired changes.

    For information on dBASE driver settings, click [image] .

  3. Exit the Registry Editor.

  4. Exit and restart Microsoft Access to use the new settings.

Important Changes to settings in these subkeys will affect all programs installed on the computer that use the Microsoft Jet database engine to access dBASE data. In addition to Microsoft Access 2000, this includes Microsoft Excel 2000, Microsoft Visual Basic 6.0 or later, and possibly others. To make changes that apply only to Access 2000, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE
\Microsoft\Office\9.0\Access\Jet\4.0\Engines
\Xbase subkey, and then modify values there. If the \Xbase subkey does not exist, create the subkey, and then add the values.

Note You can also use the Data Access Object (DAO) method, Application.DBEngine.SetOption to dynamically modify Microsoft Jet registry values at run-time for a single session, without permanently modifying the values in the Windows registry. For more information, click [image] .


 Customize HTML driver settings

Customize HTML driver settings

  1. Start the Registry Editor.

    How?

  2. Navigate to the \HKEY_LOCAL_MACHINE
    \SOFTWARE\Microsoft\Jet\4.0\Engines\Text subkey and make the desired changes.

    For information on HTML driver settings, click [image] .

  3. Exit the Registry Editor.

  4. Exit and restart Microsoft Access to use the new settings.

Important Changes to settings in these subkeys will affect all programs installed on the computer that use the Microsoft Jet database engine to access HTML data. In addition to Microsoft Access 2000, this includes Microsoft Excel 2000, Microsoft Visual Basic 6.0 or later, and possibly others. To make changes that apply only to Access 2000, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE
\Microsoft\Office\9.0\Access\Jet\4.0\Engines
\Text subkey, and then modify values there. If the \Text subkey does not exist, create the subkey, and then add the values.

Note You can also use the Data Access Object (DAO) method, Application.DBEngine.SetOption to dynamically modify Microsoft Jet registry values at run-time for a single session, without permanently modifying the values in the Windows registry. For more information, click [image] .


 Customize Microsoft Jet version 2.x database engine settings

Customize Microsoft Jet version 2.x database engine settings

Note Microsoft Jet database engine settings apply only to Microsoft Access databases, not to Microsoft Access projects.

  1. Start the Registry Editor.

    How?

  2. Navigate to the \HKEY_LOCAL_MACHINE
    \SOFTWARE\Microsoft\Jet\4.0\Engines\Jet 2.x subkey and make the desired changes.

    For information on the names, types, and default values of Microsoft Jet 2.x database engine settings, click [image] .

  3. Exit the Registry Editor.

  4. Exit and restart Microsoft Access to use the new settings.

Important Changes to settings in this subkey will affect all programs installed on the computer that use the Microsoft Jet database engine to access Microsoft Access 1.x and 2.0 databases. In addition to Microsoft Access, this includes Microsoft Excel, Microsoft Visual Basic, and possibly others. To make changes that apply only to Microsoft Access, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE
\Microsoft\Office\9.0\Access\Jet\4.0\Engines
\Jet 2.x subkey, and then modify values there. If the \Jet 2.x subkey does not exist, create the subkey, and then add the values.

Note You can also use the Data Access Object (DAO) method, Application.DBEngine.SetOption to dynamically modify Microsoft Jet registry values at run-time for a single session, without permanently modifying the values in the Windows registry. For more information, click [image] .


 Customize Microsoft Jet version 4.0 database engine settings

Customize Microsoft Jet version 4.0 database engine settings

Note Microsoft Jet database engine settings apply only to Microsoft Access databases, not to Microsoft Access projects (except when you import, link, or export data or database objects from an Access project).

  1. Start the Registry Editor.

    How?

  2. Navigate to the \HKEY_LOCAL_MACHINE
    \SOFTWARE\Microsoft \Jet\4.0\Engines\Jet 4.0 subkey and make the desired changes.

    For information on the names, types, and default values of Microsoft Jet 4.0 database engine settings, click [image] .

  3. Exit the Registry Editor.

  4. Exit and restart Microsoft Access to use the new settings.

Important Changes to settings in this subkey will affect all programs installed on the computer that use the Microsoft Jet database engine to access Microsoft Access 2000 databases. In addition to Microsoft Access, this includes Microsoft Excel 2000, Microsoft Visual Basic 6.0 or later, and possibly others. To make changes that apply only to Microsoft Access, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE
\Microsoft\Office\9.0\Access\Jet\4.0\Engines
\Jet 4.0 subkey, and then modify values there. If the \Jet 4.0 subkey does not exist, create the subkey, and then add the values.

Note You can also use the Data Access Object (DAO) method, Application.DBEngine.SetOption to dynamically modify Microsoft Jet registry values at run-time for a single session, without permanently modifying the values in the Windows registry. For more information, click [image] .


 Customize Microsoft Jet version 3.x database engine settings

Customize Microsoft Jet version 3.x database engine settings

Note Microsoft Jet database engine settings apply only to Microsoft Access databases, not to Microsoft Access projects.

  1. Start the Registry Editor.

    How?

  2. Navigate to the \HKEY_LOCAL_MACHINE
    \SOFTWARE\Microsoft\Jet\4.0\Engines\Jet 3.x subkey and make the desired changes.

    For information on the names, types, and default values of Microsoft Jet 3.x database engine settings, click [image] .

  3. Exit the Registry Editor.

  4. Exit and restart Microsoft Access to use the new settings.

Important Changes to settings in this subkey will affect all programs installed on the computer that use the Microsoft Jet database engine to access Microsoft Access 95 or Microsoft Access 97 databases. In addition to Microsoft Access, this includes Microsoft Excel, Microsoft Visual Basic, and possibly others. To make changes that apply only to Microsoft Access, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE
\Microsoft\Office\9.0\Access\Jet\4.0\Engines
\Jet 3.x subkey, and then modify values there. If the \Jet 3.x subkey does not exist, create the subkey, and then add the values.

Note You can also use the Data Access Object (DAO) method, Application.DBEngine.SetOption to dynamically modify Microsoft Jet registry values at run-time for a single session, without permanently modifying the values in the Windows registry. For more information, click [image] .


 Customize Lotus driver settings

Customize Lotus driver settings

  1. Start the Registry Editor.

    How?

  2. Navigate to the \HKEY_LOCAL_MACHINE
    \SOFTWARE\Microsoft\Jet\4.0\Engines\Lotus subkey and make the desired changes.

    For information on Lotus driver settings, click [image] .

  3. Exit the Registry Editor.

  4. Exit and restart Microsoft Access to use the new settings.

Important Changes to settings in this subkey will affect all programs installed on the computer that use the Microsoft Jet database engine to access Lotus 1-2-3 data. In addition to Microsoft Access 2000, this includes Microsoft Excel 2000, Microsoft Visual Basic 6.0 or later, and possibly others. To make changes that apply only to Access 2000, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE
\Microsoft\Office\9.0\Access\Jet\4.0\Engines
\Lotus subkey, and then modify values there. If the \Lotus subkey does not exist, create the subkey, and then add the values.

Note You can also use the Data Access Object (DAO) method, Application.DBEngine.SetOption to dynamically modify Microsoft Jet registry values at run-time for a single session, without permanently modifying the values in the Windows registry. For more information, click [image] .


 Customize ODBC driver settings

Customize ODBC driver settings

  1. Start the Registry Editor.

    How?

  2. Navigate to the \HKEY_LOCAL_MACHINE
    \SOFTWARE\Microsoft\Jet\4.0\Engines\ODBC subkey and make the desired changes.

    For information on the names, types, and default values of ODBC drivers settings, click [image] .

  3. Exit the Registry Editor.

  4. Exit and restart Microsoft Access to use the new settings.

Important Changes to settings in this subkey will affect all programs installed on the computer that use the Microsoft Jet database engine to access ODBC databases. In addition to Microsoft Access 2000, this includes Microsoft Excel 2000, Microsoft Visual Basic 6.0 or later, and possibly others. To make changes that apply only to Access 2000, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE
\Microsoft\Office\9.0\Access\Jet\4.0\Engines
\ODBC subkey, and then modify values there. If the \ODBC subkey does not exist, create the subkey, and then add the values.

Note You can also use the Data Access Object (DAO) method, Application.DBEngine.SetOption to dynamically modify Microsoft Jet registry values at run-time for a single session, without permanently modifying the values in the Windows registry. For more information, click [image] .


 Specify whether OLE links are saved in OLE version 2.x or 1.x format

Specify whether OLE links are saved in OLE version 2.x or 1.x format

You can specify whether Microsoft Access saves OLE links in OLE version 2.x format, which saves both relative and absolute link source references, or OLE 1.x format, which saves only absolute references. (An absolute link source reference obtains data from an object that's stored as a file. A relative link source reference obtains data from an object that may be embedded within a document.) In an environment where both Microsoft Access 2000 and Microsoft Access version 1.x are used, set this option to 1 to ensure consistency of OLE linking operations in Microsoft Access 1.x databases.

  1. Start the Registry Editor.

    How?

  2. Navigate to the \HKEY_LOCAL_MACHINE
    \SOFTWARE\Microsoft\Office\9.0\Access subkey of the registry.

  3. Double-click the \Options subkey. If AllowOLE1LinkFormat is already listed in the Name column on the right pane of the Registry Editor, skip to step 6.

  4. On the Edit menu, point to New, and then click DWORD Value.

  5. Type AllowOLE1LinkFormat and press ENTER.

  6. Double-click AllowOLE1LinkFormat, and then, in the Value Data box, enter 1 to save in OLE 1.x link format or 0 to save in OLE 2.x link format.

  7. Exit the Registry Editor.

  8. Exit and restart Microsoft Access to use the new settings.


 Customize Paradox driver settings

Customize Paradox driver settings

  1. Start the Registry Editor.

    How?

  2. Navigate to the \HKEY_LOCAL_MACHINE
    \SOFTWARE\Microsoft\Jet\4.0\Engines\Paradox subkey and make the desired changes.

    For information on Paradox driver settings, click [image] .

  3. Exit the Registry Editor.

  4. Exit and restart Microsoft Access to use the new settings.

Important Changes to settings in these subkeys will affect all programs installed on the computer that use the Microsoft Jet database engine to access Paradox data. In addition to Microsoft Access 2000, this includes Microsoft Excel 2000, Microsoft Visual Basic 6.0 or later, and possibly others. To make changes that apply only to Access 2000, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE
\Microsoft\Office\9.0\Access\Jet\4.0\Engines
\Paradox subkey, and then modify values there. If the \Paradox subkey does not exist, create the subkey, and then add the values.

Note You can also use the Data Access Object (DAO) method, Application.DBEngine.SetOption to dynamically modify Microsoft Jet registry values at run-time for a single session, without permanently modifying the values in the Windows registry. For more information, click [image] .


 Customize text driver settings

Customize text driver settings

  1. Start the Registry Editor.

    How?

  2. Navigate to the \HKEY_LOCAL_MACHINE
    \SOFTWARE\Microsoft\Jet\4.0\Engines\Text subkey and make the desired changes.

    For information on text driver settings, click [image] .

  3. Exit the Registry Editor.

  4. Exit and restart Microsoft Access to use the new settings.

Important Changes to settings in these subkeys will affect all programs installed on the computer that use the Microsoft Jet database engine to access text data. In addition to Microsoft Access 2000, this includes Microsoft Excel 2000, Microsoft Visual Basic 6.0 or later, and possibly others. To make changes that apply only to Access 2000, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE
\Microsoft\Office\9.0\Access\Jet\4.0\Engines
\Text subkey, and then modify values there. If the \Text subkey does not exist, create the subkey, and then add the values.

Note You can also use the Data Access Object (DAO) method, Application.DBEngine.SetOption to dynamically modify Microsoft Jet registry values at run-time for a single session, without permanently modifying the values in the Windows registry. For more information, click [image] .


 Define the data display format for a field in query Design view

Define the data display format for a field in query Design view

  1. Open a query in Design view.

  2. In the query design grid, place the insertion point in the column for the field you want to format. You can place the insertion point in any row for that field.

  3. Click Properties [image] on the toolbar to open the property sheet for that field.

  4. On the General tab, click the arrow next to the Format property box, and then click one of the predefined formats. If the predefined formats don't suit your needs, you can type a custom format in the Format property box for any field data type other than OLE Object. For information on how to define a custom format, click [image] .

Note To ensure consistency among applications, Microsoft Access uses the regional settings that are specified by double-clicking Regional Settings in Windows Control Panel for some predefined number and date/time formats. For more information, click [image] .


 Define an input mask for a field in a table

Define an input mask for a field in a table

  1. Open a table in Design view.

  2. In the upper portion of the window, click the field you want to define an input mask for.

  3. In the lower portion of the window on the General tab, click the Build button [image] next to the InputMask property box to start the Input Mask wizard, and then follow the instructions in the wizard dialog boxes.

Note You can also enter the input mask definition in the property sheet without using the wizard. In most cases, it's easiest to use the wizard, but for Number and Currency fields, you must enter the input mask definition manually. For information on how to define an input mask manually, click [image] .


 Set the number of decimal places to display for a control

Set the number of decimal places to display for a control

  1. Open a form in Design view or a report in Design view.

  2. Make sure the control you want to change is selected, and then click Properties [image] on the toolbar to open the property sheet for the control.

  3. Click the DecimalPlaces property box, click the arrow, and then select the desired number of decimal places.

    The DecimalPlaces property provides a default setting, Auto, and the option to specify from 0 to 15 decimal places. When set to Auto, fields with Format property settings of Currency, Fixed, Standard, Percent and Scientific display two decimal places. The DecimalPlaces property has no effect unless the field or control has a Format property setting. For information on setting a data display format, click [image] .

Note The DecimalPlaces property setting affects only the number of decimal places that display, not how many decimal places are stored. For example, if you set the DecimalPlaces property to 2 for a Number field with the FieldSize property set to Integer, it will display with two decimal places, but because only whole number (integer) values will be stored, zeros will fill the two decimal places. To change the number of decimal places that will be stored, you must change a Number field's FieldSize property. For information on setting a field's FieldSize property, click


 Set the number of decimal places to display for a field in query Design view

Set the number of decimal places to display for a field in query Design view

  1. Open a query in Design view.

  2. In the query design grid, place the insertion point in the column for the field you want to change. You can place the insertion point in any row for that field.

  3. Click Properties [image] on the toolbar to open the property sheet for that field.

  4. On the General tab, click the arrow next to the DecimalPlaces property box, and then click the desired number of decimal places.

    The DecimalPlaces property provides a default setting, Auto, and the option to specify from 0 to 15 decimal places. When set to Auto, fields with Format property settings of Currency, Fixed, Standard, Percent and Scientific display two decimal places. The DecimalPlaces property has no effect if the Format property hasn't been set. For information on setting a field's data display format, click [image] .

Note The DecimalPlaces property setting affects only the number of decimal places that display, not how many decimal places are stored. For example, if you set the DecimalPlaces property to 2 for a Number field with the FieldSize property set to Integer, it will display with two decimal places, but because only whole number (integer) values will be stored, zeros will fill the two decimal places. To change the number of decimal places that will be stored, you must change a Number field's FieldSize property. For information on setting a field's FieldSize property, click


 Define the data display format for a field in table Design view

Define the data display format for a field in table Design view

  1. Open a table in Design view.

  2. In the upper portion of the window, click the field you want to format.

  3. In the lower portion of the window on the General tab, click the arrow next to the Format property box, and then click one of the predefined formats. If the predefined formats don't suit your needs, you can type a custom format in the Format property box for any field data type other than OLE Object. For information on how to define a custom format, click [image] .

Note To ensure consistency among applications, Microsoft Access uses the regional settings that are specified by double-clicking Regional Settings in the Windows Control Panel for some predefined Number and Date/Time formats. For more information, click [image] .


 Define an input mask for a field in a query

Define an input mask for a field in a query

  1. Open a query in Design view.

  2. In the query design grid, place the insertion point in the column for the field you want to change. You can place the insertion point in any row for that field.

  3. Click Properties [image] on the toolbar to open the property sheet for that field.

  4. On the General tab, click the Build button [image] next to the InputMask property to start the Input Mask wizard, and then follow the instructions in the wizard dialog boxes.

Note You can also enter the input mask definition in the property sheet without using the wizard. In most cases, it's easiest to use the wizard, but for Number and Currency fields, you must enter the input mask definition manually. For information on how to define an input mask manually, click [image] .


 Set the number of decimal places to display for a field in table Design view

Set the number of decimal places to display for a field in table Design view

  1. Open a table in Design view.

  2. In the upper portion of the window, click the field you want to define decimal places for.

  3. In the lower portion of the window on the General tab, click the arrow next to the DecimalPlaces property box, and then click the desired number of decimal places.

    The DecimalPlaces property provides a default setting, Auto, and the option to specify from 0 to 15 decimal places. When set to Auto, fields with Format property settings of Currency, Fixed, Standard, Percent and Scientific display two decimal places. The DecimalPlaces property has no effect if the Format property hasn't been set. For information on setting a field's data display format, click [image] .

Note The DecimalPlaces property setting affects only the number of decimal places that display, not how many decimal places are stored. For example, if you set the DecimalPlaces property to 2 for a Number field with the FieldSize property set to Integer, it will display with two decimal places, but because only whole number (integer) values will be stored, zeros will fill the two decimal places. To change the number of decimal places that will be stored, you must change a Number field's FieldSize property. For information on setting a field's FieldSize property, click


Modify or delete custom database properties

  1. With the database open, click Database Properties on the File menu.

  2. Click the Custom tab.

  3. Click the name of the property you want to delete or modify in the Name column in the Properties box.

  4. To modify the property, type the changes in the Type or Value boxes, and then click Modify.

    To delete the property, click Delete.

Note If you try to modify the name of the property, it becomes a new property, and you can only add it. To modify the name of the property, delete the existing property and add it with the new name.


 Delete an Access database or Access project

Delete an Access database or Access project

  1. Close the Microsoft Access database or Microsoft Access project. In a multiuser environment, confirm that all users have closed the Access database.

  2. Click Open [image] on the toolbar.

  3. In the Open dialog box, locate the Access database or Access project you want to delete, and then right-click the file.

  4. On the shortcut menu, click Delete.

Notes

  • If you want to get your file back, look in the Recycle Bin. Your deleted file will remain in the bin until you empty it.

  • When you delete an Access database or Access project that includes data access pages, you are not deleting the page HTML files.

  • When you delete an Access project, you are not deleting the Microsoft SQL Server database to which the Access project is connected.

  • You can also delete an Access database or Access project from outside Access. Close the file, right-click the file in Windows Explorer or My Computer, and then click Delete on the shortcut menu.


 Automatically delete duplicate records from a table

Automatically delete duplicate records from a table

In this procedure, you create a copy of the structure of the table that contains duplicates, make primary keys of all the fields that contain duplicates, and then run an append query from the original table to the new table. Because fields that are primary keys can't contain duplicate records, this procedure produces a table without duplicate records.

To create a new table

  1. In the Database window, click Tables [image] under Objects.

  2. Click the name of the table you want to delete duplicate records from.

  3. Click Copy [image] on the toolbar.

  4. Click Paste [image] on the toolbar.

  5. In the Paste Table As dialog box, type a name for the copied table, click Structure Only, and then click OK.

  6. Open the new table in Design view, and select the field(s) that contained duplicates in the table you copied.

  7. Click Primary Key [image] on the toolbar to create a primary key based on the selected fields.

  8. Save and close the table.

To append only unique records to the new table

  1. Create a new query based on the original table containing duplicates.

  2. In query Design view, click the Query Type [image] on the toolbar, and then click Append Query.

  3. In the Append dialog box, click the name of the new table from the Table Name list, and then click OK.

  4. Include all the fields from the original table by dragging the asterisk (*) to the query design grid.

  5. Click Run [image] on the toolbar.

  6. Click Yes when you receive the message that you're about to append rows.

  7. Click Yes when you receive the message that Microsoft Access can't append all the records in the append query. This transfers only unique records to your new table and discards the duplicates.

  8. To see the results, open the table by clicking Tables [image] under Objects in the Database window and clicking Open on the Database window toolbar.

  9. When you're sure the new table has the correct unique records, you can delete the original table, and then rename the new table using the name of the original table.


 Delete a field from a table in Datasheet view

Delete a field from a table in Datasheet view

  1. Open the table in Datasheet view.

  2. Click the field selector of the column you want to delete.

  3. On the Edit menu, click Delete Column.

Notes

  • If other database objects contain references to a deleted field, you need to delete those references as well. For example, if a report includes a control bound to a deleted field, Microsoft Access won't be able to find the data from the field and will generate a message.

  • You can't delete a field that's part of a relationship. You must delete the relationship first.


 Delete a field from a table in Design view

Delete a field from a table in Design view

  1. Open the table in Design view.

  2. Select the field(s) you want to delete.

    To select one field, click that field's row selector.

    To select a group of fields, drag through the row selectors of those fields.

  3. Click Delete Row [image] on the toolbar.

Notes

  • If other database objects contain references to a deleted field, you need to delete those references as well. For example, if a report includes a control bound to a deleted field, Microsoft Access won't be able to find the data from the field and will generate a message.

  • You can't delete a field that's part of a relationship. You must delete the relationship first.


 Delete a picture or other object on a form or report

Delete a picture or other object on a form or report

  1. Do one of the following:
    • If the object is an unbound object frame or an image control, click the object in form or report Design view.

    • If the object is bound, open the form in Form view (or open a datasheet), find the record you want to change, and click the object.
  2. Press the DELETE key.

    If the object is bound, then Microsoft Access removes it from the bound object frame and the underlying record source, but the bound object frame remains on the form or report. If the object is an unbound object frame or an image control, Microsoft Access removes the object and the control.

Note If you want to delete a bound object frame and all the objects stored in the underlying field, delete the bound object frame in form Design view or report Design view, and then, in a Microsoft Access database (.mdb), delete the OLE Object field in table Design view; or, in a Microsoft Access project (.adp), delete the image column in Column Properties view in the database diagram.


 Delete records from one table or tables in a one-to-one relationship

Delete records from one table or tables in a one-to-one relationship

For information on important considerations when using a query that deletes records, click [image] .

  1. Create a new query that contains the tables from which you want to delete records.

    How?

  2. In query Design view, click the arrow next to Query Type [image] on the toolbar, and then click Delete Query.

  3. For the tables you want to delete records from, drag the asterisk (*) from the field list to the query design grid.

    From appears in the Delete cell under these fields, as shown in the illustration that follows.

  4. To specify criteria for deleting records, drag to the design grid the fields on which you want to set criteria.

    Where appears in the Delete cell under these fields, as shown in the following illustration.

    Specifying criteria for deleting records

  5. In the Criteria cell for the fields that you have dragged to the grid, type the criteria.

    For information on specifying criteria, click [image] .

  6. To preview the records that will be deleted, click View [image] on the toolbar. To return to query Design view, click View [image] on the toolbar again. Make any changes you want in Design view.

  7. Click Run [image] on the toolbar to delete the records.

Note To stop a query after you start it, press CTRL+BREAK.


 Delete records by using a query that includes both tables in a one-to-many relationship

Delete records by using a query that includes both tables in a one-to-many relationship

For information on important considerations when using a query that deletes records, click [image] .

  1. Create a new query that contains the tables from which you want to delete records or set criteria.

    How?

  2. In query Design view, click the arrow next to Query Type [image] on the toolbar, and then click Delete Query.

  3. From the table with related records (on the "many" side of the one-to-many relationship), drag the asterisk (*) from the field list to the query design grid.

    From appears in the Delete cell under this field, as shown in the following illustration.

  4. From the primary table (on the "one" side of the one-to-many relationship), drag to the design grid the fields on which you want to set criteria.

    Where appears in the Delete cell under this field, as shown in the following illustration.

    Specifying criteria for deleting records from both sides of a one-to-many relationship

  5. In the Criteria cell for the fields that you have dragged to the grid, type the criteria.

    For information on specifying criteria, click [image] .

  6. To preview the records that will be deleted, click View [image] on the toolbar. To return to query Design view, click View [image] on the toolbar again. Make any changes you want in Design view.

  7. Click Run [image] on the toolbar to delete the records from the table on the "many" side.

  8. Select the field list for each table on the "many" side and press DELETE to remove it from the query.

  9. With just the primary table remaining in the query and the field on which you want to set criteria in the design grid, click Run [image] again. Microsoft Access deletes the specified records from the "one" table.

Note To stop a query after you start it, press CTRL+BREAK.


 Delete records by using a query that includes only the "one" table in a one-to-many relationship

Delete records by using a query that includes only the "one" table in a one-to-many relationship

When you run a delete query on the "one" table in a one-to-many relationship, and you've enabled cascading deletes for this relationship, Microsoft Access also deletes related records from the "many" side. For information on important considerations when using a query that deletes records, click [image] .

  1. Create a new query that contains the "one" table from which you want to delete records.

    How?

  2. In query Design view, click the arrow next to Query Type [image] on the toolbar, and then click Delete Query.

  3. Drag the asterisk (*) from the field list for the table to the query design grid.

    From appears in the Delete cell under this field, as shown in the illustration that follows.

  4. To specify criteria for deleting records, drag to the design grid the fields on which you want to set criteria.

    Where appears in the Delete cell under this field, as shown in the following illustration.

    Specifying criteria for deleting records

  5. In the Criteria cell for the fields that you have dragged to the grid, type the criteria.

    For information on specifying criteria, click [image] .

  6. To preview the records that will be deleted, click View [image] on the toolbar. To return to query Design view, click View [image] on the toolbar again. Make any changes you want in Design view.

  7. Click Run [image] on the toolbar to delete the records.

Note To stop a query after you start it, press CTRL+BREAK.


Delete a switchboard

  1. Open the database.

  2. Do one of the following to open the Switchboard Manager dialog box:
    • If you created the switchboard by using the Database Wizard, click Change Switchboard Items in the opening switchboard.

    • If you created the switchboard by using the Switchboard Manager, click Add-ins on the Tools menu, and then click Switchboard Manager.
  3. Click the switchboard you want to delete in the Switchboard Pages box, and then click Delete.


Delete an Or tab in the Filter By Form window

  1. Click the Or tab you want to delete.

  2. On the Edit menu, click Delete Tab.


 Delete a text box or other control that is in a group on a form or report

Delete a text box or other control that is in a group on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Click any control in the group to select the group.

  3. Select the control you want to delete.

  4. Press the DELETE key.

Note The group still exists without this deleted control, unless only one control is left in the group. If there are only two controls in a group and you delete one control, the group is also deleted.


 Disable a text box or other control in Form view or make data in a control read-only

Disable a text box or other control in Form view or make data in a control read-only

  1. Open a form in Design view or a report in Design view.

  2. Make sure that the control is selected, and then click Properties [image] on the toolbar to open its property sheet.

  3. Do one or both of the following:
    • If you want to disable the control completely so that it's dimmed and can't receive the focus, set the Enabled property to No.

    • If you want to make data in the control readable, but not allow users to change the data, set the Locked property to Yes. If you set the Enabled property to No and the Locked property to Yes, then the control won't appear dimmed, but it won't be able to receive the focus.

Notes

  • You can use the Enabled property together with the AfterUpdate property to disable a control until a user enters text or makes a selection in another control. For example, you might want to disable a command button until data has been entered in a text box. You can use the AfterUpdate property of the text box to call an event procedure or a macro to enable the command button.

  • For more information on the Enabled and Locked properties and how you can use them together, click [image] .

  • If you just want to keep a control off the tab order, but you want to make it possible to select that control, set the TabStop property for that control to No.


 Automatically display all fields from a query's underlying table or query

Automatically display all fields from a query's underlying table or query

You can display all the fields without adding them to the design grid.

  1. Open a query in Design view.

  2. Select the query by clicking anywhere in query Design view outside the design grid and the field lists.

  3. Click Properties [image] on the toolbar to display the query's property sheet.

  4. Set the OutputAllFields property to Yes.

Notes

  • If you want to limit the records that the query returns by specifying criteria, or if you want to create a calculated field or specify a sort order in the design grid, you need to add the fields for these purposes to the design grid. Make sure you clear the Show check box for any of these fields; otherwise, they will display twice in the query's results.

  • You can change the default setting for the OutputAllFields property for all new queries. For more information, click [image] .


 Display a custom field description in a query's status bar

Display a custom field description in a query's status bar

You can customize the description that is displayed when you click in a field in a query's results.

  1. Open a query in Design view.

  2. Click the field in the design grid whose description you want to change, and then click Properties [image] on the toolbar to display the field's property sheet.

  3. In the Description property, type the description you want the status bar to display for that field in the query's results. The maximum length is 255 characters.

Users will see the new description in the status bar when they click in the field in query Datasheet view.


 Prevent duplicate records in a query based on fields in the underlying table

Prevent duplicate records in a query based on fields in the underlying table

  1. Open a query in Design view.

  2. Select the query by clicking anywhere in query Design view outside the design grid and the field lists.

  3. Click Properties [image] on the toolbar to display the query's property sheet.

  4. Set the UniqueRecords property to Yes.

Notes

  • The UniqueRecords property has an effect only when you use more than one table in the query and select fields from those tables.

  • When the UniqueRecords property is set to Yes, Microsoft Access automatically sets the UniqueValues property to No.

  • As an alternative to setting the UniqueRecords property, you can add to the design grid the field that distinguishes one record from another.


 Prevent duplicate records in a query based on fields in the design grid

Prevent duplicate records in a query based on fields in the design grid

  1. Open a query in Design view.

  2. Select the query by clicking anywhere in query Design view outside the design grid and the field lists.

  3. Click Properties [image] on the toolbar to display the query's property sheet.

  4. Set the UniqueValues property to Yes.

    If the query's results include more than one field, the combination of values from all fields must be unique for a given record to be included in the results.

  5. To view the query's results, click View [image] on the toolbar.

Note When the UniqueValues property is set to Yes, Microsoft Access automatically sets the UniqueRecords property to No.


 Show or hide system objects in the Database window by default

Show or hide system objects in the Database window by default

Microsoft Access automatically creates system objects when you create a new database.

  1. On the Tools menu, click Options.

  2. Click the View tab.

  3. Under Show, select or clear the System Objects check box.


 Reapply a filter to retrieve the most current set of records

Reapply a filter to retrieve the most current set of records

If you're working with filtered data in a multiuser (shared) database, you may want to reapply the filter occasionally to see which records have been added, deleted, or changed since you opened the form or datasheet and applied the filter.

  • With the filtered records displayed in a datasheet, subdatasheet, form, or subform, click Apply Filter/Sort on the Records menu.


 Display a message box by using a macro

Display a message box by using a macro

  1. Create a macro.

    How?

  2. In a blank action row, click MsgBox in the action list, and then set the action arguments.

  3. Click Save [image] to save the macro.

  4. Run the macro.

    How?

For more information about the MsgBox action, click [image] .


Display a message box by using Visual Basic

  1. Create a Visual Basic procedure.

    How?

  2. Add an assignment statement to the procedure that assigns the value returned by the MsgBox function to a variable. The function returns different values depending on the button a user clicks in the message box. Your procedure can then perform different operations based on the value returned.

    For example, the following assignment statement runs the MsgBox function, displaying a message, and assigns the value returned by the function to the variable RetValue:

    RetValue = MsgBox("Continue?", vbOKCancel)

  3. Run the procedure.

    How?

For information about the MsgBox function, click [image] .


 Display the Paste Errors table

Display the Paste Errors table

  1. In the Database window of a Microsoft Access database, click Tables [image] under Objects.

  2. Double-click Paste Errors.


 Display a picture or other object on a form or report as an icon

Display a picture or other object on a form or report as an icon

  1. Do one of the following:
    • If the object is unbound, click the object in form or report Design view.

    • If the object is bound, open the form in Form view (or open a datasheet), find the record that you want to change, and click the object.
  2. On the Edit menu, point to the appropriate Object command (for example, point to Worksheet Object for a Microsoft Excel object), and then click Convert.

  3. In the Convert dialog box, select the Display As Icon check box.

Note Displaying an object as an icon can save a significant amount of disk space because the OLE server (the application that was used to create the object) sends the object with rendering information that consists of only the icon, rather than the complete object.


 Display the value of a variable or expression in the Visual Basic Editor Code window when code is suspended

Display the value of a variable or expression in the Visual Basic Editor Code window when code is suspended

  1. On the Tools menu, click Options.

  2. Click the Editor tab.

  3. Under Code Settings, make sure Auto Data Tips is selected.

When Auto Data Tips is selected, you can check the value of a variable or an expression while code is suspended. Rest the mouse pointer on a variable or expression to display its current value.


 Display a Web page on a form

Display a Web page on a form

Before you can add the Microsoft Web Browser control to a form, you must have Microsoft Internet Explorer version 3.0 or later installed. Learn about installing Microsoft Internet Explorer.

  1. Open the form in Design view.

  2. In the toolbox, click the More Controls tool ActiveX control .

    A menu appears that lists all the registered ActiveX controls in your system.

  3. On the menu of ActiveX controls, click Microsoft Web Browser.

  4. On the form, click where you want to place the control.

  5. Move and size the control if necessary.


 Create a hyperlink by dragging an Internet shortcut

Create a hyperlink by dragging an Internet shortcut

  1. Open a form in Design view or a report in Design view.

  2. Navigate to an Internet shortcut (an icon on your desktop or an item in the History subfolder of your Windows folder).

  3. Select the Internet shortcut.

  4. Use the right mouse button to drag the selection to the form or report.

    Microsoft Access adds a label to the form or report. To test the link, right-click the label, point to Hyperlink on the shortcut menu, and then click Open.


 Edit a bound picture or other object on a form

Edit a bound picture or other object on a form

  1. Open the form in Form view (or open a datasheet).

  2. Go to the record that contains the object you want to edit.

  3. Double-click the object.

    Microsoft Access opens the application that was used to create the object (the OLE server application) if it's available. The application may open in a separate window or you may be able to edit the object in place.

    Note When you double-click a sound or video object, Microsoft Access plays the object. To open these types of objects for editing, click the object and then click the appropriate Object command on the Edit menu. For example, point to the Media Clip Object command, and then click the Open or Edit command on the submenu.

  4. Make the changes that you want, and then do one of the following:
    • If you're editing in place, click the form outside the bound object frame. If you mistakenly click Exit on the File menu, you'll quit Microsoft Access.

    • If you're editing the object in a separate window, click Exit on the File menu of the OLE server application. If you're prompted to update the document, click OK.

Notes

  • To edit an object in a bound object frame, the Enabled property for the bound object frame must be set to Yes and the Locked property must be set to No.

  • You can define the action taken when you double-click an object by setting the Verb and AutoActivate properties for the bound object frame. For example, you might want to open the object in a separate window instead of in place. For more information on the Verb property, click [image] . For more information on the AutoActivate property, click [image] .


 Edit an unbound picture or other object on a form or report

Edit an unbound picture or other object on a form or report

  1. Open the form in Design view or the report in Design view.

  2. Double-click the object.

  3. Microsoft Access opens the application that was used to create the object (the OLE server application) if it's available.

    Note When you double-click a sound or video object, Microsoft Access plays the object. To open these types of objects for editing, click the object, and then click the appropriate Object command on the Edit menu. For example, point to the Media Clip Object command, and then click the Open or Edit command on the submenu.

  4. Make the changes you want and then do one of the following:
    • If you're editing the object in place, click the form outside the unbound object frame. If you click Exit on the File menu, you'll quit Microsoft Access.

    • If you're editing the object in a separate window, click Exit on the File menu of the OLE server application. If you're prompted to update the document, click OK.

Notes

  • In most cases, you'll edit an unbound object from the Design view of a form or report. If you want to be able to edit the object from Form view also, set the Enabled property of the unbound object frame to Yes and the Locked property to No.

  • This procedure only applies to pictures in unbound object frames, not image controls. A picture in an image control has no connection with the source application used to create it.


 Insert an existing bound object on a form

Insert an existing bound object on a form

  1. If you haven't already done so, create a bound object frame on a form.

    How?

  2. Switch to Form view or Datasheet view.

  3. Move to the record in which you want to insert the object and click the OLE Object field in a Microsoft Access database (.mdb), or the image column in a Microsoft Access project (.adp).

  4. On the Insert menu, click Object.

  5. In the Insert Object dialog box, click Create From File, and then specify a path to the file. If you don't know the path, you can click Browse.

  6. Select the Display As Icon check box if you want the object to appear as an icon instead of as the object itself. Displaying an object as an icon can be helpful when an object contains supplementary information that doesn't have to be displayed. Displaying an object as an icon also uses significantly less disk space.

  7. Click OK.

    If you're in Form view, Microsoft Access displays the object. If you're in Datasheet view, Microsoft Access displays the name of the object, for example, "Bitmap Image."

  8. If you need to edit the object, double-click it.

Notes

  • If the application that you're copying from supports OLE drag-and-drop editing, then you can drag the file directly from Windows Explorer or the desktop instead of using the Object command.

  • You can adjust the size and proportions of the object after you paste it.

    How?

  • You can also insert a bound object in a table or in a query datasheet. Just select the field that you want to insert the object into (it must be an OLE Object field or an image column), and then follow steps 4 through 7. In order to see the object, you must create a bound object frame on a form or report.


 Insert an existing unbound object on a form or report

Insert an existing unbound object on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Click the Unbound Object Frame tool [image] in the toolbox.

  3. On the form or report, click where you want to insert the object.

  4. In the Insert Object dialog box, click Create From File, and then specify a path to the file. If you don't know the path, then you can click Browse.

  5. Select the Display As Icon check box if you want the object to appear as an icon instead of as the object itself. Displaying an object as an icon can be helpful when an object contains supplementary information that doesn't have to be displayed. Displaying an object as an icon also uses significantly less disk space.

  6. Click OK.

Microsoft Access creates an unbound object frame and displays the object in the frame. If you want to edit the object, double-click it.

Notes

  • If the application that you're copying from supports OLE drag-and-drop editing, then you can drag the file directly from Windows Explorer or the desktop instead of using the Unbound Object Frame tool.

  • You can adjust the size and proportions of the object after you paste it.

    How?

  • In many cases, you'll edit an unbound object from form or report Design view. If you want to be able to edit the object from Form view also, then set the Enabled property of the unbound object frame to Yes and the Locked property to No.


 Insert part of an existing bound object on a form

Insert part of an existing bound object on a form

You can use this procedure if the application that you're copying from has OLE support for copying part of an existing document.

  1. If you haven't already done so, create a bound object frame on a form.

    How?

  2. Switch to the application that you used to create the object, and select the information that you want to insert. For example, open Microsoft Excel and select a range of cells.

  3. On the Edit menu, click Copy.

  4. Switch back to Microsoft Access, switch to Form view or Datasheet view, move to the record that you want to paste the object into, and click the OLE Object field in a Microsoft Access database (.mdb), or the image column in a Microsoft Access project (.adp).

  5. Click Paste [image] on the toolbar.

    Note If you want to display the object as an icon, or if you want to specify what type of object to paste as, click Paste Special on the Edit menu. For information on Paste Special options, click [image] .

    If you're in Form view, then Microsoft Access displays the object. If you're in Datasheet view, then Microsoft Access displays the name of the object, for example "Microsoft Excel Worksheet."

  6. If you need to edit the object, then double-click it.

Notes

  • If the application that you're copying from supports OLE drag-and-drop editing, you can drag selected information from that application to the field in Form view.

  • You can adjust the size and proportions of the object after you paste it.

    How?

  • You can also insert a bound object in a table or query datasheet. Just select the field that you want to insert the object into (it must be an OLE Object field or an image column), and then click Paste [image] on the toolbar. To see the object, you must create a bound object frame on a form or report.


 Insert part of an existing unbound object on a form or report

Insert part of an existing unbound object on a form or report

You can use this procedure if the application that you're copying from has OLE support for copying part of an existing document.

  1. Open the file in the application that you used to create it, and select the information you want to insert. For example, open Microsoft Excel and select a range of cells.

  2. On the Edit menu, click Copy.

  3. Switch to Microsoft Access.

  4. In form Design view or report Design view, click Paste [image] on the toolbar.

Microsoft Access creates an unbound object frame, and displays the object in the frame. If you want to edit the object, then double-click it.

Note If you want to display the object as an icon or if you want to specify what type of object to paste as, then click Paste Special on the Edit menu. For information on Paste Special options, click [image] .

Notes

  • If the application that you're copying from supports OLE drag-and-drop editing, then you can drag selected information from that application to the Design view of a Microsoft Access form or report. When you do this, Microsoft Access creates an unbound object frame and inserts the selected information in the frame.

  • You can adjust the size and proportions of the object after you paste it.

    How?

  • In many cases, you'll edit an unbound object from form or report Design view. If you want to be able to edit the object from Form view also, then set the Enabled property of the unbound object frame to Yes and the Locked property to No.


 Enable a previous-version database in Microsoft Access 2000

Enable a previous-version database in Microsoft Access 2000

  1. Click Open Database [image] on the toolbar.

  2. Click the previous-version Access database you want to enable and click Open.

  3. In the Convert/Open Database dialog box, click Open Database.

Microsoft Access enables the previous-version database in Microsoft Access 2000, without making any permanent changes to the previous-version database. An enabled database can still be opened with its original version of Microsoft Access.

Note You can enable a secured database.


 Where to specify criteria to affect when calculations are performed

Where to specify criteria to affect when calculations are performed

In the query design grid, where you specify criteria determines when the calculation is performed.

Note Although the following examples only show queries that calculate totals, these guidelines apply to calculated fields as well.

  • To limit groupings before you perform calculations on groups of records, specify the criteria in the Group By fields.

    Set grouping criteria to affect when a calculation is performed

  • To return only selected results after the calculation is performed, specify criteria in the field that contains the calculation. This rule applies whether you're performing the calculation on each record, groups of records, or all records.

    Perform a calculation and then return the selected results

  • To limit the records before they are grouped and before the calculation is performed, add to the design grid the field whose records you want to limit, and then specify criteria in the field's Criteria cell. If you're calculating totals in the same query, set the Total cell for the field containing the criteria to Where. This rule applies whether you're calculating the total on all records or groups of records. (Microsoft Access automatically clears the Show check box.)

    The following example uses the ExtendedPrice field twice, once to limit the records and once to calculate the total. However, you can use a different field to limit records by dragging that field to the design grid and setting its Total cell to Where.

    Limit the record and calculate the total by using the same field

Note For examples of criteria expressions, click [image] .


Enter a hyperlink by pasting a hyperlink or hyperlink address in a data access page

  1. Navigate to a hyperlink or hyperlink address in one of the following ways:
    • Open a document that contains the hyperlink or the hyperlink address.

    • In a Web browser, such as Microsoft Internet Explorer, go to the page containing the hyperlink or hyperlink address.
  2. Do one of the following:
    • In the document, select the defined hyperlink or the hyperlink address and then click Copy on the Edit menu.

    • In the Web browser, select the address in the Address box or select a valid hyperlink address anywhere on a page, right-click the selection, and then click Copy or Copy Shortcut on the shortcut menu.
  3. Open a data access page in your Web browser.

  4. Place the insertion point in the text box that accepts hyperlinks on the page.

  5. On the Edit menu, click Paste.

    On a data access page, the text box in which you enter a hyperlink address doesn’t format the address as a hyperlink. Look for the address formatted as hyperlink elsewhere on the page.

Tip Click the Refresh button on the Internet Explorer toolbar to see the hyperlink address displayed as a formatted hyperlink.


 Enter a hyperlink that creates an e-mail message in Form view or Datasheet view

Enter a hyperlink that creates an e-mail message in Form view or Datasheet view

  1. Do one of the following:
    • In a Microsoft Access database (.mdb), open the table or query in Datasheet view.

    • In an Access database or Microsoft Access project (.adp), open the form in Datasheet or Form view.
  2. Place the insertion point in the hyperlink field in the datasheet or in the text box or combo box that accepts hyperlinks on the form.

  3. Click Insert Hyperlink [image] on the toolbar.

  4. In the Insert Hyperlink dialog box, click E-mail Address under Link to.

  5. In the Text to display box, type the text that you want displayed in the field or text box. If you leave the box blank, then Microsoft Access will use the e-mail address and subject as the display text.

  6. Click ScreenTip, and type the text that you want to appear when the pointer hovers over the hyperlink. If you leave the ScreenTip box blank, then Microsoft Access will display the e-mail address and subject as the ScreenTip.

  7. In the E-mail address box, type an e-mail address. Or select an address from the Recently used e-mail addresses list.

  8. In the Subject box, type the information that you want to appear in the Subject field of the e-mail message.

    Note Some Web browsers and e-mail programs might not recognize the subject line.

  9. Click OK.

    When you click the hyperlink, Microsoft Access opens your mail program and creates a new message, with the address and subject filled in.


 Enter a hyperlink to an existing file or Web page by using the Insert Hyperlink button

Enter a hyperlink to an existing file or Web page by using the Insert Hyperlink button

  1. Do one of the following:
    • In a Microsoft Access database (.mdb), open the table or query in Datasheet view.

    • In an Access database or Microsoft Access project (.adp), open the form in Datasheet or Form view.
  2. Place the insertion point in the hyperlink field in the datasheet or in the text box or combo box that accepts hyperlinks on the form.

  3. Click Insert Hyperlink [image] on the toolbar.

  4. In the Insert Hyperlink dialog box, click Existing file or Web page under Link to.

  5. In the Text to display box, type the display text for the hyperlink. If you leave the box blank, then Microsoft Access will use the hyperlink address as the display text.

  6. Click ScreenTip, and then type the text that you want to appear when the pointer hovers over the hyperlink. If you leave the ScreenTip box blank, then Microsoft Access will display the hyperlink address as the ScreenTip.

  7. Specify the file or Web page you want to link to in one of these ways:
    • In the Type the file or Web page name box, type a path or a URL.

    • Under Or select from list, click Recent files, Browsed pages, or Inserted links. Then click an item in the list.

    • Click File to search for a file on your hard drive or network.

    • Click Web page to search for a page on the Internet or an intranet.
  8. To go to a specific location in an HTML file or to an object in a Microsoft Access database (.mdb) or a Microsoft Access project (.adp), click Bookmark. Click the bookmark or object you want in the list, and then click OK.

  9. Click OK in the Insert Hyperlink dialog box.

    Microsoft Access adds the hyperlink to the field or control. You can click the hyperlink to open the target document, Web page, or object.


 Create a new data access page and create a hyperlink to the page at the same time

Create a new data access page and create a hyperlink to the page at the same time

  1. Do one of the following:
    • In a Microsoft Access database (.mdb), open the table or query in Datasheet view.

    • In an Access database or Microsoft Access project (.adp), open the form in Datasheet or Form view.
  2. Place the insertion point in the hyperlink field in the datasheet or in the text box or combo box that accepts hyperlinks on the form.

  3. Click Insert Hyperlink [image] on the toolbar.

  4. In the Insert Hyperlink dialog box, click Create new page under Link to.

  5. In the Text to display box, type the text that you want displayed in the field or text box. If you leave the box blank, then Microsoft Access will use the hyperlink address as the display text.

  6. Click ScreenTip and type the text that you want to appear when the pointer hovers over the hyperlink. If you leave the ScreenTip box blank, then Microsoft Access will display the hyperlink address as the ScreenTip.

  7. In the Name of new document box, type a name and the three-letter file name extension of the type of file that you want to create. If you omit the extension or enter .htm or .html, then Microsoft Access will create a new data access page.

  8. Microsoft Access creates the new document in the current folder. To specify a different location, click Change.

  9. Select an option under When to edit. You can edit the new document immediately or wait until later.

  10. Click OK.

    Microsoft Access adds the hyperlink to the field or control. You can click the hyperlink to open the target document.


 Enter a hyperlink to an object in the current database in Form view or Datasheet view

Enter a hyperlink to an object in the current database in Form view or Datasheet view

  1. Do one of the following:
    • In a Microsoft Access database (.mdb), open the table or query in Datasheet view.

    • In an Access database or Microsoft Access project (.adp), open the form in Datasheet or Form view.
  2. Place the insertion point in the hyperlink field in the datasheet or in the text box or combo box that accepts hyperlinks on the form.

  3. Click Insert Hyperlink [image] on the toolbar.

  4. In the Insert Hyperlink dialog box, click Object in this database under Link to.

  5. In the Text to display box, type the text that you want displayed in the field or text box. If you leave the box blank, then Microsoft Access will use the object type and object name as the display text.

  6. Click ScreenTip, and type the text that you want to appear when the pointer hovers over the hyperlink. If you leave the ScreenTip box blank, then Microsoft Access displays the object type and object name as the ScreenTip.

  7. Select the database object that you want to link to from the list.

  8. Click OK.

    Microsoft Access adds the hyperlink to the field or control. You can click the hyperlink to open the target object.


 Field data types available in Microsoft Access

Field data types available in Microsoft Access

The following table summarizes all the field data types available in Microsoft Access, their uses, and their storage sizes.

Data type | Use for | Size
Text | Text or combinations of text and numbers, such as addresses. Also numbers that do not require calculations, such as phone numbers, part numbers, or postal codes. For more information on defining a Text field, click [image] . | Up to 255 characters. Microsoft Access only stores the characters entered in a field; it does not store space characters for unused positions in a Text field. To control the maximum number of characters that can be entered, set the FieldSize property.
Memo | Lengthy text and numbers, such as notes or descriptions. For more information on defining a Memo field, click [image] . | Up to 64,000 characters.
Number | Numeric data to be used for mathematical calculations, except calculations involving money (use Currency type). Set the FieldSize property to define the specific Number type. For more information on defining a Number field, click [image] . | 1, 2, 4, or 8 bytes. 16 bytes for Replication ID (GUID) only. For more information on changing Number field sizes, click [image] .
Date/Time | Dates and times. For more information on defining a Date/Time field, click [image] . | 8 bytes.
Currency | Currency values. Use the Currency data type to prevent rounding off during calculations. Accurate to 15 digits to the left of the decimal point and 4 digits to the right. For more information on defining a Currency field, click [image] . | 8 bytes.
AutoNumber | Unique sequential (incrementing by 1) or random numbers automatically inserted when a record is added. For more information on defining an AutoNumber field, click [image] . | 4 bytes. 16 bytes for Replication ID (GUID) only.
Yes/No | Fields that will contain only one of two values, such as Yes/No, True/False, On/Off. For more information on defining a Yes/No field, click [image] . | 1 bit.
OLE Object | Objects (such as Microsoft Word documents, Microsoft Excel spreadsheets, pictures, sounds, or other binary data), created in other programs using the OLE protocol, that can be linked to or embedded in a Microsoft Access table. You must use a bound object frame in a form or report to display the OLE object. For more information on defining an OLE Object field, click [image] . | Up to 1 gigabyte (limited by disk space).
Hyperlink | Field that will store hyperlinks. A hyperlink can be a UNC path or a URL. For more information on defining a Hyperlink field, click [image] . | Up to 64,000 characters.
Lookup Wizard | Creates a field that allows you to choose a value from another table or from a list of values using a combo box. Choosing this option in the data type list starts a wizard to define this for you. For more information on defining a Lookup field, click [image] . | The same size as the primary key field that is also the Lookup field; typically 4 bytes.

Note Number, Date/Time, Currency, and Yes/No data types provide predefined display formats. Set the Format property to choose from the formats available for each data type. You can also create a custom display format for all data types except the OLE Object data type. For information on how to define a custom display format, click [image] .


In a form, create a list box or combo box that gets its rows from a function

You may want to use this procedure when the values in a list are constantly changing, or if the values aren't stored in a database. For example, you could write a function that fills a list box with a list of dates, each one a specific number of days after the current date.

  1. Create the function. For information on creating the function, click [image] .

  2. Create the list box or combo box and open its property sheet.

  3. In the RowSourceType property box, enter the name of the function. Don't put an equal sign before the function name.

  4. Leave the RowSource property box blank.


 Filter records by using the Advanced Filter/Sort window

Filter records by using the Advanced Filter/Sort window

  1. Open a table, query, or form in Datasheet view or open a form in Form view.

  2. Click in the datasheet, subdatasheet, form, or subform you want to filter.

  3. On the Records menu, point to Filter, and then click Advanced Filter/Sort.

  4. Add to the design grid the field or fields you'll need to specify the values or other criteria the filter will use to find records.

    How?

  5. To specify a sort order, click in the Sort cell for a field, click the arrow, and select a sort order.

    Microsoft Access first sorts the leftmost field in the design grid, then it sorts the next field to the right, and so on.

  6. In the Criteria cell for the fields you have included, enter the value you're looking for or enter an expression.

    For more information on entering criteria, click [image] .

  7. Apply the filter by clicking Apply Filter [image] on the toolbar.

Notes

  • When you save a table or form, Microsoft Access saves the filters. You can reapply the filters when you need them, the next time you open the table or form.

  • When you save a query, Microsoft Access saves the filters you created, but it does not add the filter criteria to the query design grid. You can reapply the filters after you run the query, the next time you open it.

  • If you created a filter on a subdatasheet or subform, this filter is also available when you open the table or form for the subdatasheet or subform independently.

  • For information on creating a form or report based on the filtered data, click [image] .

  • Instead of creating a filter from scratch, you can use an existing query as a filter. For more information, click [image] .


 Filter records by entering criteria in place in a form or datasheet

Filter records by entering criteria in place in a form or datasheet

  1. Open a table, query, or form in Datasheet view, or a form in Form view.

    To filter records in a subdatasheet, first click the expand indicator to display that subdatasheet.

  2. Do one of the following:
    • To specify the exact field value you want the filtered records to contain, right-click in the field in the datasheet, subdatasheet, form, or subform you're filtering, and then in the Filter For box on the shortcut menu, type the value. For example, to find all the records that have London in the City field, right-click in the City field, and then type London in the Filter For box.

    • To specify more complex criteria, type the complete expression using the appropriate combination of identifiers, operators, wildcard characters, and values to produce the result you want. For example, to find all the records where the Contact Title field includes the word "Marketing" anywhere in the title, right-click in the Contact Title field, and then type *Marketing* in the Filter For box. To display only the records for orders that were shipped more than 15 days after the specified required date, type [ShippedDate]-[RequiredDate]>15. (In this last example, you don't have to right-click a specific field to enter the expression. However, in a datasheet with subdatasheets, first click in the sheet you want to filter.)

      For examples of criteria expressions, click [image] . For more information on wildcard characters, click [image] .

  3. Do one of the following:
    • To apply the filter and close the shortcut menu, press ENTER.

    • To apply the filter and keep the shortcut menu displayed (so that you can specify additional criteria for the field), press TAB. Enter new criteria, and then press TAB again. Repeat until you have just the records you want.

Notes

  • When you save a table or form, Microsoft Access saves the filters you created. You can reapply the filters when you need them, the next time you open the table or form.

  • When you save a query, Microsoft Access saves the filters you created, but it does not add the filter criteria to the query design grid. You can reapply the filters after you run the query, the next time you open it.


 Filter records by selecting values in a form or datasheet

Filter records by selecting values in a form or datasheet

  1. In a field on a form, subform, datasheet, or subdatasheet, find one instance of the value you want records to contain in order to be included in the filter's results.

  2. Select the value, and then click Filter By Selection [image] on the toolbar. How you select the value determines what records the filter returns. For more information on selecting values, click [image] .

    Repeat step 2 until you have the set of records you want.

Notes

  • When you save a table or form, Microsoft Access saves the filters you created. You can reapply the filters when you need them, the next time you open the table or form.

  • When you save a query, Microsoft Access saves the filters you created, but it does not add the filter criteria to the query design grid. You can reapply the filters after you run the query, the next time you open it.

  • If you created a filter on a subdatasheet or subform, this filter is also available when you open the table or form for the subdatasheet or subform independently.

  • You can also filter for records that do not have a certain value. After selecting a value, right-click it, and then click Filter Excluding Selection.

  • For information on creating a form or report based on the filtered data, click [image] .


 Filter records by entering values in a blank view of your form or datasheet

Filter records by entering values in a blank view of your form or datasheet

  1. Open a table, query, or form in Datasheet view or open a form in Form view.

    To filter records in a subdatasheet, display the subdatasheet by clicking its expand indicator.

  2. Click Filter By Form [image] on the toolbar to switch to the Filter By Form window.

    You can specify criteria for the form, subform, main datasheet, or any subdatasheet that's displayed. Each subdatasheet or subform has its own Look For and Or tabs.

  3. Click the field in which you want to specify the criteria that records must meet to be included in the filtered set of records.

  4. Enter your criteria by selecting the value you're searching for from the list in the field (if the list includes field values), or by typing the value into the field.
    • To find records in which a check box, toggle button, or option button is or is not selected, click the check box or button until it's the way you want. To return it to a neutral position so that it won't be used as criteria for filtering records, continue clicking the check box or button until it's grayed.

    • To find records in which a particular field is empty or not empty, type Is Null or Is Not Null into the field. (You can select these options from the list in fields with a Memo, OLE Object, or Hyperlink data type, and in calculated fields in queries.)

    • To find records using a criteria expression, type the expression into the appropriate field or enter one using the Expression Builder. For examples of expressions, click [image] .

      If you specify values in more than one field, the filter returns records only if they contain the same values you specified in each of those fields.

  5. To specify alternative values that records can have to be included in the filter's results, click the Or tab for the datasheet, subdatasheet, form, or subform you're filtering, and enter more criteria.

    The filter returns records if they have all the values specified on the Look For tab or all the values specified on the first Or tab or all the values specified on the second Or tab, and so on.

  6. Click Apply Filter [image] on the toolbar.

Notes

  • When you save a table or form, Microsoft Access saves the filters you created. You can reapply the filters when you need them, the next time you open the table or form.

  • If you created a filter on a subdatasheet or subform, this filter is also available when you open the table or form for the subdatasheet or subform independently.

  • When you save a query, Microsoft Access saves the filters you created, but it does not add the filter criteria to the query design grid. You can reapply the filters after you run the query, the next time you open it.

  • For information on creating a form or report based on the filtered data, click [image] .


 Find unmatched records between tables using a query wizard

Find unmatched records between tables using a query wizard

Using the Find Unmatched Query Wizard, you can find records in one table that don't have related records in another table. For example, you can find customers who don't have orders.

  1. In the Database window, click Queries [image] under Objects, and then click New on the Database window toolbar.

  2. In the New Query dialog box, click Find Unmatched Query Wizard.

  3. Click OK.

  4. Follow the directions in the wizard dialog boxes. In the last dialog box, you can choose to run the query or see the query's structure in Design view.

    If the resulting query isn't exactly what you want, you can rerun the wizard or change the query in Design view. For more information on changing a query in Design view, click [image] .


 Use a macro to force a page break in a report if a condition is met

Use a macro to force a page break in a report if a condition is met

  1. Open the report in Design view.

  2. In the toolbox, click Page Break [image] , and then click in the report section where you want a conditional page break.

  3. Click Properties [image] on the toolbar, and specify a name for the page break control in the Name box.

  4. Create a macro.

    How?

  5. In a blank action row, click SetValue in the action list.

  6. Set the Item argument to the identifier for the Visible property of the page break control. For example, if the name of the control is CondPgBreak, set the Item argument to [CondPgBreak].[Visible].

  7. Set the Expression argument to No.

  8. Click Save [image] to save the macro.

  9. In report Design view, set the OnFormat property of the report's page header section to the name of the macro.

    This hides the page break control when the report starts formatting each page, so the page doesn't break.

  10. Create a second macro that sets the Visible property of the page break control to Yes when a conditional expression is met.

Select an action to carry out when a condition that you specify is met

  11. Click Save to save the macro.

  12. Select the section where you placed the page break, and set the section's OnFormat property to the name of the second macro. In the preceding example, to make a page break occur if the Counter control in the detail section is 10, set the detail section's OnFormat property to the name of the second macro.

When the condition is met, the page breaks. After the page is broken, the macro attached to the page header hides the page break control until the condition is met again.


 Use Visual Basic to force a page break in a report if a condition is met

Use Visual Basic to force a page break in a report if a condition is met

  1. Open the report in Design view.

  2. In the toolbox, click Page Break [image] , and then click in the report section where you want a conditional page break.

  3. Open the report's PageHeader_Format event procedure.

    How?

  4. In the event procedure, add an assignment statement that sets the Visible property of the page break control to No. For example, if the name of the control is CondPgBreak, add the following assignment statement:
    Me![CondPgBreak].Visible = False

    This hides the page break control when the report starts formatting each page, so the page doesn't break.

  5. In the Format event procedure of the section where you placed the page break, add Visual Basic code that sets the Visible property to Yes when a condition is met. For example, suppose you want a page break to occur in the detail section of the report if the value of the Counter control is 10 so that the first 10 records will print on the first page. Add the following code to the Detail_Format event procedure:
    If Me![Counter] = 10 Then
    Me![CondPgBreak].Visible = True
End If

When the condition is met, the page breaks. After the page is broken, the event procedure attached to the page header hides the page break control until the condition is met again.


Get information about your Microsoft Outlook installation

  1. Start Microsoft Outlook.

  2. On the Help menu, click About Microsoft Outlook.

  3. Click Security Info.

Installation information appears at the top as Corporate or Workgroup, or Internet Mail Only.


 Group text boxes or other controls on a form or report

Group text boxes or other controls on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Select the controls you want to include in a group. How to select adjacent controls. How to select nonadjacent or overlapping controls.

  3. On the Format menu, click Group.

Note To create a group you must select more than one control.


 Group records by the first n characters in a text value on a data access page

Group records by the first n characters in a text value on a data access page

Learn about grouping records by the first n (or prefix) characters.

  1. Open the data access page in Design view.

  2. Create a grouped data access page.

  3. Make sure there are two controls bound to the field you want to use to group by prefix characters.

  4. Make sure the control you want to use to group by prefix characters is selected.

  5. Click Promote [image] on the toolbar.

    Microsoft Access adds a group header that contains an expand control, and a record navigation section that contains a record navigation control Access moves the control you grouped on to the group header.

  6. Click Sorting And Grouping [image] on the toolbar to display the Sorting And Grouping box.

  7. Click the group record source that you want to group by prefix characters.

  8. Set the following properties:
    • Set GroupOn to Prefix Characters.

    • Set GroupInterval to the number of characters you want to group on.
  9. Specify the default sort order for the other group levels on the page.

Note When you group on a control, Access creates an alias for the control by adding the prefix "GroupOf" to the control's name in the ControlSource property; for example, GroupOfProductName: ProductName. When you reference this control in an expression or in a property, you must use the alias.


 About grouping on autonumbered, currency, or numeric values in a report

About grouping on autonumbered, currency, or numeric values in a report

When you group records on a field that stores autonumbered, currency, or numeric values, you set the GroupOn property to one of the ranges listed in the following table. In a Microsoft Access database (.mdb), you store autonumbered values in an AutoNumber field, currency values in a Currency field, and numeric values in a Number field. In a Microsoft Access project (.adp), you store currency values in a money or small money column, and numeric values in a decimal, numeric, int, smallint, tinyint, float, or real column. If you set the GroupOn property to Interval, you can set the GroupInterval property to any number that's valid for the values in the field you're grouping on. If you set the GroupOn property to Each Value, the GroupInterval value is 1.

Set the GroupOn property to | To group records with
Each Value | The same value in the field or expression.
Interval | Values falling in the interval you specify.

Microsoft Access starts AutoNumber, Currency, and Number groups with 0. For example, if you set the GroupOn property to Interval, and set the GroupInterval property to 5, Microsoft Access groups the records like this: 0 to 4, 5 to 9, 10 to 14, and so on.

Report that groups currency values in intervals of 100

The following table lists the sorting and grouping specifications for this report. Sale Amount in the first row of the Field/Expression column in the Sorting And Grouping box groups the records in intervals of 100. Sale Amount in the second row sorts the records in ascending amounts within each $100 interval.

Field/ Expression | Sort Order | Group Header | Group Footer | Group On | Group Interval | Keep Together
Sale Amount | Ascending | No | Yes | Interval | 100 | Whole Group
Sale Amount | Ascending | No | No | Each Value | 1 | No

Note The Sales Totals by Amount report in the Northwind sample database groups records in intervals of 1,000. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Sales Totals by Amount report in Design view. For information on opening Northwind, click [image] .


 About grouping records on date or time values in a report

About grouping records on date or time values in a report

When you group records in a field that stores date or time values, you set the GroupOn property to one of the ranges listed in the following table. In a Microsoft Access database (.mdb), you store date or time values in field with a Date/Time data type. In a Microsoft Access project (.adp), you store them in a column with a datetime or smalldatetime data type. For all ranges except Each Value, you can set the GroupInterval property to any number that is valid for the values in the field or expression you're grouping on. If you set the GroupOn property to Each Value, the GroupInterval value is 1.

Set the GroupOn property to | To group records with
Each Value | The same value in the field or expression.
Year | Dates in the same calendar year.
Qtr | Dates in the same calendar quarter.
Month | Dates in the same month.
Week | Dates in the same week.
Day | Dates on the same day.
Hour | Times in the same hour.
Minute | Times in the same minute.

Report that groups date values by year and quarter

The following table lists the main sorting and grouping specifications for this report. Shipped Date in the first row of the Field/Expression column in the Sorting And Grouping box groups the records by year. Shipped Date in the second row groups the records for each year by quarter.

Field/ Expression | Sort Order | Group Header | Group Footer | Group On | Group Interval | Keep Together
Shipped Date | Ascending | Yes | Yes | Year | 1 | Whole Group
Shipped Date | Ascending | No | Yes | Qtr | 1 | No

Notes

  • To print the year or quarter instead of a specific date, use the DatePart function or use the Format function.

  • To count the number of orders shipped, use the Count function.

  • The Summary of Sales by Year report in the Northwind sample database prints quarterly sales for each year. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Summary of Sales by Year report in Design view. For information on opening Northwind, click [image] .

  • The Summary of Sales by Quarter report in the Northwind sample database shows sales from multiple years for each quarter. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Summary of Sales by Quarter report in Design view.


 About grouping records on text values in a report

About grouping records on text values in a report

When you group records on a field that stores text values, you can set the GroupOn property to the ranges listed in the following table. In a Microsoft Access database(.mdb), you store text values in field with a Text data type. In a Microsoft Access project (.adp), you store text values in a column with a char, varchar, nchar, or nvarchar data type. If you set the GroupOn property to Prefix Characters, you can set the GroupInterval property to any number that's valid for the value in the field you're grouping on. If you set the GroupOn property to Each Value, the GroupInterval value is 1.

Set the GroupOn property to | To group records
Each Value | That contain the same value in the field or expression.
Prefix Characters | That contain the same first n number of characters in the field or expression.

Report that groups records on the first letter of product names

The following table lists the sorting and grouping specifications for this report. Product Name in the first row of the Field/Expression column in the Sorting And Grouping box groups the records by the first letter of the product names. Product Name in the second row sorts the records alphabetically by product name under each letter.

Field/ Expression | Sort Order | Group Header | Group Footer | Group On | Group Interval | Keep Together
Product Name | Ascending | Yes | Yes | Prefix Characters | 1 | Whole Group
Product Name | Ascending | No | No | Each Value | 1 | No

Notes

  • To print the first letter of each group in the group header, you use the Left function. For more information, click [image] .

  • You can look at the Alphabetical List of Products report in the Northwind sample database. To view this report, open the Northwind database in the Samples subfolder of your Office folder, and then open the Alphabetical List of Products report in Design view. For information on opening Northwind, click [image] .


 Group records on intervals of autonumbered, currency, or numeric values on a data access page

Group records on intervals of autonumbered, currency, or numeric values on a data access page

Learn about grouping records on intervals of currency values.

  1. Open the data access page in Design view.

  2. Create a grouped data access page.

  3. Make sure there are two controls bound to the field you want to use to group by interval. You'll use one to group on and the other to display the actual value.

  4. Make sure the control you want to use to group on is selected.

  5. Click Promote [image] on the toolbar.

    Microsoft Access adds a group header that contains an expand control, and a record navigation section that contains a record navigation control. Access moves the control you grouped on to the group header.

  6. Click Sorting And Grouping [image] on the toolbar to display the Sorting And Grouping box.

  7. Click the group record source that you want to group on an interval.

  8. Set the GroupOn property to Interval.

  9. Set the GroupInterval property to any number that's valid for the values in the field you grouped on.

  10. Specify the default sort order for the other group levels on the page.

Note When you group on a control, Microsoft Access creates an alias for the control by adding the prefix "GroupOf" to the control's name in the ControlSource property; for example, GroupOfSaleAmount: SaleAmount. When you reference this control in an expression or in a property, you must use the alias.


 Group records on intervals of date or time values on a data access page

Group records on intervals of date or time values on a data access page

Learn about grouping records by month.

Create the grouped report and set the grouping interval

  1. Open the data access page in Design view.

  2. Create a grouped data access page.

  3. Make sure the control you want to use to group by date or time interval is selected.

  4. Click Promote [image] on the toolbar.

    Microsoft Access adds a group header that contains an expand control, and a record navigation section that contains a record navigation control. Access also moves the control you grouped on to the group header.

  5. Click Sorting And Grouping [image] on the toolbar to display the Sorting And Grouping box.

  6. Click the group record source that you want to group by date or time interval.

  7. In the GroupOn property, click a value in the list. You can group records on values that fall in the same calendar year, calendar quarter, month, week, day, hour, or minute.

  8. Set the GroupInterval property to any number that is valid for the values in the field you're grouping on. For example, if you set GroupOn to Month, valid values for GroupInterval are 1, 2, 3, 4, or 6.

  9. Specify the default sort order for the other group levels on the page.

Create a control that displays the field value as an interval

In some cases, you'll want to create a control that displays the value in the field you grouped on as an interval on the page in Page view or in Microsoft Internet Explorer.

  1. Add a bound HTML control for the expression by clicking Bound HTML Bound HTML control in the toolbox and then clicking in the group header where the control you grouped on an interval is located.

  2. Make sure the bound HTML control is selected, and then click Properties [image] on the toolbar to display the property sheet.

  3. Type the alias for the expression followed by a colon and the expression you want in the ControlSource property box. For example, if you grouped on ShippedDate, and set the GroupOn property to Month and the GroupInterval property to 1, type the following expression to display the values in the GroupOfShippedDate field as a three-letter month:

    Month: Format(GroupOfShippedDate, "mmm")

Note When you group on a control, Access creates an alias for the control by adding the prefix "GroupOf" to the control's name in the ControlSource property; for example, GroupOfShippedDate: ShippedDate. When you reference this control in an expression or in a property, you must use the alias.

Hide the control you grouped on

In some cases, you won't want the value in the control you grouped on to be visible on the page in Page view or in Microsoft Internet Explorer.

  1. Make sure the control you grouped by date or time interval is selected, and then click Properties [image] on the toolbar to display the property sheet.

  2. Set the control's Visibility property to Hidden.


Help topic not available

The Help topic cannot be displayed because Help or Visual Basic for Applications Help cannot be found, was not installed, or was removed.

To install Help and Visual Basic for Applications Help

  1. In Microsoft Windows Control Panel, double-click Add/Remove Programs.

  2. On the Install/Uninstall tab, click Microsoft Office 2000, and then click Add/Remove.

  3. Click Add or Remove Features, and then do one or both of the following:
    • Expand Microsoft Access for Windows in the list of features, and then click the icon next to Help to view the installation choices.

    • Expand Office Tools in the list of features, and then click the icon next to Visual Basic Help to view the installation choices.
  4. Click Run from My Computer or Run from Network, and then click Update Now.

Note If you chose the Custom Setup option when you installed Microsoft Access, and then deleted the Help files to save disk space, you must rerun the Setup program and reinstall Microsoft Access to restore the missing Help files.


 Show or hide a field in a query's results

Show or hide a field in a query's results

You can add to the query design grid a field that you use for setting criteria or a sort order, yet not show the data from that particular field in the query's results.

  • In query Design view, select the Show box in the design grid to show the field, or clear the Show box to hide the field.

Notes

  • If you want to create a form, report, or data access page based on the query, and the query's OutputAllFields property is set to No, you must show the fields for which you will create bound controls on the form, report, or data access page.

  • When you close a query, Microsoft Access moves hidden fields to the rightmost columns in the design grid.


 Show or hide warning messages by using a macro

Show or hide warning messages by using a macro

  1. Open an existing macro in the Macro window.

    How?

  2. In the place in the macro where you want to stop or resume the display of modal warning messages, add the SetWarnings action.

    How?

  3. To temporarily stop the display of warning messages, set the Warnings On argument to No. To resume displaying them, set the Warnings On argument to Yes.

  4. Click Save [image] to save the macro.

  5. Run the macro.

    How?

When the macro stops running, the display of warning messages automatically resumes.


 Show or hide warning messages by using Visual Basic

Show or hide warning messages by using Visual Basic

  1. Open a Function or Sub procedure in the Code window.

  2. In the place in the procedure where you want to stop or resume the display of modal warning messages, use the SetWarnings method to carry out the SetWarnings action.

    How?

  3. To temporarily stop the display of warning messages, set the warningson argument to False. To resume displaying them, set the warningson argument to True.

  4. Run the procedure.

    How?

When the code stops running, the display of warning messages automatically resumes.

For more information about the SetWarnings method, click [image] .


 I get a message when I attempt to enter data in Page view.

I get a message when I attempt to enter data in Page view.

When you try to move out of a field after changing data, Microsoft Access validates the data, making sure that the value you entered is allowed in that field. If the value isn't allowed, Microsoft Access alerts you. In order to move off the field, you must either change the data to an acceptable value or undo your changes.

A value might not be allowed in a field for the following reasons:

  • The value isn't compatible with the field's data type. If you enter a value that doesn't match the data type, Microsoft Access attempts to convert the entry to the correct data type. However, some data can't be converted to other data types. For example, you can't store a name in a field with the Number data type in a Microsoft Access database or the smallint data type in a Microsoft Access project.

  • The data breaks a rule set in the ValidationRule property for the field.

  • Data is required in the field, and you've tried to leave it blank.

  • The validation macro specified for the BeforeUpdate property canceled the update.

Microsoft Access also validates data when you move out of a record. Before it saves a record, Microsoft Access makes sure that your changes don't break any validation rules set in the ValidationRule property for the record. Additionally, if the table you are editing has a primary key or unique index, Microsoft Access makes sure that the record you are editing doesn't have the same value for the field or fields as another record in the table. If the record can't be saved, you must either make any necessary corrections or click Undo Record


 I'm getting the message "Too few parameters expected."

I'm getting the message "Too few parameters expected."

You may encounter this message if a parameter query exported to the IDC file type doesn't have data types specified in the Query Parameters dialog box.

To solve the problem, do the following:

  1. In the Database window, click Queries [image] under Objects.

  2. Click the name of the parameter query you want to modify, and click Design on the Database window toolbar.

  3. On the Query menu, click Parameters.

  4. In the Query Parameters dialog box, explicitly declare the data types of each parameter in your query and click OK when you are finished.

  5. Save and run the query.


 Insert a field in the design grid of a query or advanced filter

Insert a field in the design grid of a query or advanced filter

  1. Open a query in Design view, or open a form or datasheet and display the Advanced Filter/Sort window.

  2. Drag the field from the field list to the column in the design grid where you want to insert it.


 Perform a quick watch while debugging Visual Basic code

Perform a quick watch while debugging Visual Basic code

  1. Suspend execution of your Visual Basic code.

    How?

  2. Select the expression whose value you want to see.

  3. Click Quick Watch [image] on the Debug toolbar.

Microsoft Access displays the Quick Watch dialog box, where you can see the expression and the current value of the expression. Click Add in the dialog box to add the expression to the list of watch expressions in the Watch window of the Visual Basic Editor.


 Create a link on a form to an existing bound object

Create a link on a form to an existing bound object

  1. If you haven't already done so, create a bound object frame on a form.

    How?

  2. Switch to Form view or Datasheet view.

  3. Move to the record in which you want to link the object, and click the OLE Object field in a Microsoft Access database (.mdb), or the image column in a Microsoft Access project (.adp).

  4. On the Insert menu, click Object.

  5. In the Insert Object dialog box, click Create From File, and then specify a path to the file. If you don't know the path, you can click Browse.

  6. Select the Link check box.

  7. Select the Display As Icon check box if you want the object to appear as an icon instead of as the object itself. Displaying an object as an icon can be helpful when an object contains supplementary information that doesn't have to be displayed. Displaying an object as an icon also uses significantly less disk space.

  8. Click OK.

    If you're in Form view, Microsoft Access displays the object. If you're in Datasheet view, Microsoft Access displays the name of the object, for example, "Bitmap Image."

  9. If you need to edit the object, double-click it.

Notes

  • You can adjust the size and proportions of the object after you paste it.

    How?

  • You can also insert a bound object in a table or query datasheet. Just select the field that you want to insert the object into (it must be an OLE Object field or an image column), and then follow steps 4 through 8. To see the object, you must create a bound object frame on a form or report.

  • When you link an object, the link is automatic by default. Microsoft Access automatically updates the object when you move to the field. If you want to control when the link is updated, you can change the link from automatic to manual.

    How?


 Create a link on a form or report to an existing unbound object

Create a link on a form or report to an existing unbound object

  1. Open a form in Design view or a report in Design view.

  2. Click the Unbound Object Frame tool [image] in the toolbox.

  3. On the form or report, click where you want to place the object.

  4. In the Insert Object dialog box, click Create From File, and then specify a path to the file. If you don't know the path, you can click Browse.

  5. Select the Link check box.

  6. Select the Display As Icon check box if you want the object to appear as an icon instead of as the object itself. Displaying an object as an icon can be helpful when an object contains supplementary information that doesn't have to be displayed. Displaying an object as an icon also uses significantly less disk space.

  7. Click OK.

Microsoft Access creates an unbound object frame and displays the object in the frame. If you want to edit the object, then double-click it.

Notes

  • You can adjust the size and proportions of the object after you paste it.

    How?

  • In many cases, you'll edit an unbound object from form or report Design view. If you want to be able to edit the object from Form view also, then set the Enabled property of the unbound object frame to Yes and the Locked property to No.

  • When you link to an object, the link is automatic by default. This means that if the object is updated outside Microsoft Access, then the changes will automatically appear the next time you open the form or report. If you want to control when the link is updated, you can change the link from automatic to manual.

    How?


 Create a link on a form to part of an existing bound object

Create a link on a form to part of an existing bound object

You can use this procedure if the application that you're linking to has OLE support for linking to part of an existing document.

  1. If you haven't already done so, create a bound object frame on a form.

    How?

  2. Switch to the application that you used to create the object and select the information you want to link. For example, open Microsoft Excel and select a range of cells.

  3. On the Edit menu, click Copy.

  4. Leave the application open, and switch back to Microsoft Access. Switch to Form view or Datasheet view, move to the record you want to paste the object into, and click the OLE Object field in a Microsoft Access database (.mdb), or the image column in a Microsoft Access project (.adp).

  5. On the Edit menu, click Paste Special.

  6. In the Paste Special dialog box, click Paste Link, and then click the type of object to paste as in the As list. For more information on these options, click [image] .

  7. Select the Display As Icon check box if you want the object to appear as an icon instead of as the object itself. Displaying an object as an icon can be helpful when an object contains supplementary information that doesn't have to be displayed. Displaying an object as an icon also uses significantly less disk space.

  8. Click OK.

    If you're in Form view, then Microsoft Access displays the object. If you're in Datasheet view, then Microsoft Access displays the name of the object, for example "Microsoft Excel Worksheet."

  9. If you need to edit the object, double-click it.

Notes

  • You can adjust the size and proportions of the object after you paste it.

    How?

  • You can also insert a bound object in a table or query datasheet. Just select the field that you want to insert the object into (it must be an OLE Object field or an image column), and click Paste Special on the Edit menu. Then follow steps 6 through 8 above. To see the object, you must create a bound object frame on a form or report.

  • When you link an object, the link is automatic by default. Microsoft Access automatically updates the object when you move to the field. If you want to control when the link is updated, you can change the link from automatic to manual.

    How?


 Create a link on a form or report to part of an existing unbound object

Create a link on a form or report to part of an existing unbound object

You can use this procedure if the application that you're linking to has OLE support for linking to part of an existing document.

  1. Open the file in the application that you used to create it, and select the information you want to link to. For example, open Microsoft Excel and select a range of cells.

  2. On the Edit menu, click Copy.

  3. Leave the application open, and switch to Microsoft Access.

  4. In form or report Design view, click Paste Special on the Edit menu.

  5. In the Paste Special dialog box, click Paste Link, and then click the type of object to paste as in the As list. For more information on these options, click [image] .

  6. Select the Display As Icon check box if you want the object to appear as an icon instead of as the object itself. Displaying an object as an icon can be helpful when an object contains supplementary information that doesn't have to be displayed. Displaying an object as an icon also uses significantly less disk space.

  7. Click OK.

Microsoft Access creates an unbound object frame and displays the object in the frame. If you want to edit the object, double-click it.

Notes

  • You can adjust the size and proportions of the object after you paste it.

    How?

  • In a form, you can edit an unbound object in Design view. To edit the object in Form view also, open the form in Design view, and set the Enabled property of the unbound object frame to Yes and the Locked property to No.

  • When you link an object, the link is automatic by default. This means that if the object is updated outside Microsoft Access, then the changes will automatically appear the next time you open the form or report. If you want to control when the link is updated, you can change the link from automatic to manual.

    How?


 Make a bound HTML control the default control for a data access page

Make a bound HTML control the default control for a data access page

Using bound HTML controls on a data access page makes the page load faster in Page view or in Internet Explorer. However, you can't edit the values displayed in HTML controls.

  1. Open the data access page in Design view.

  2. On the Edit menu, click Select Page.

  3. Click Properties [image] on the toolbar. Microsoft Access displays the property sheet.

  4. Set the DefaultControlType property to Bound HTML.


Set Microsoft Access run-time options

  1. Create a Microsoft Access user profile

    How

  2. Under your Access user profile subkey, create a subkey called \Run-Time Options.

  3. Under the \Run-Time Options subkey, create subkeys to specify the following settings for your application.
    Windows registry setting | Feature
    AppTitleBar | Text displayed in the title bar of your application's main window.
    AppIcon | Icon displayed in your application's title bar and when your application is minimized.
    AppHelpFile | The default Help file used when a user first gets Help.
    AppStartupScreen | The splash screen, bitmap file displayed when your application starts.

Notes

  • Use the AppTitleBar and AppIcon settings to replace the Access title bar and icon with your application specific title and icon. The AppTitleBar and AppIcon settings correspond to the Application Title and Application Icon startup properties. For more information on setting startup properties, click [image] .

  • Use the AppHelpFile setting to specify an application-specific Help file.

  • Use the AppStartupScreen setting to display a splash screen that uniquely identifies and announces your application when it starts. A splash screen is different from a startup form and displays before any startup form you might have specified in the Startup dialog box.

  • Another way to create a splash screen is to use a bitmap with the same name as your application, give it a .bmp extension, and put it in the same folder as your application. Then, by using Windows Explorer, create a shortcut for your application that specifies the bitmap name on the command line, and then enter it in the Target box (Shortcut Properties dialog box, Shortcut tab). For example:

    "C:\Program Files\Microsoft Office\Office\MSAccess.exe C:\My Files\Taxes.mdb"

    Access looks for such a file when the application opens, and if it finds one, uses it as a splash screen. The run-time option, AppStartupScreen, takes precedence over a splash screen defined this way.


 Modify a filter by using Filter By Selection or Filter Excluding Selection

Modify a filter by using Filter By Selection or Filter Excluding Selection

You can modify the filter by adding more criteria or changing the existing criteria.

  1. To further limit a set of records that already has a filter applied, start with step 2. To change the criteria previously defined for a filter, first remove the filter if it is currently applied.

    How?

  2. In Form or Datasheet view, select a value in the form, subform, datasheet, or subdatasheet that you want to use as criteria, and then click either Filter By Selection [image] on the toolbar or right-click the value and click Filter Excluding Selection on the shortcut menu. Repeat this process until you have the records you want.

Note You can also switch to the Filter By Form window or Advanced Filter/Sort window to change the criteria, including specifying alternative criteria (one criteria or another).


 Modify a filter by using Filter For Input

Modify a filter by using Filter For Input

You can modify the filter by adding more criteria or changing the existing criteria.

  1. To further limit a set of records that already has a filter applied, start with step 2. To change the criteria previously defined for a filter, first remove the filter if it is currently applied.

    How?

  2. In Form or Datasheet view, do one of the following:
    • Right-click the field you want to specify criteria for in the main form, datasheet, subform, or subdatasheet, and then in the Filter For box on the shortcut menu, type the value you want to use as criteria.

    • Right-click any field in the main form, datasheet, subform, subdatasheet, and specify the expression you want to use as criteria in the Filter For box.
  3. Press TAB and repeat step 2 until you have the records you want.

    For more information about using Filter For Input, click [image] .

Note You can also switch to the Filter By Form window or Advanced Filter/Sort window to change the criteria.


 Move a field in the design grid in a query or advanced filter

Move a field in the design grid in a query or advanced filter

  1. Open a query in Design view, or open a form or datasheet and display the Advanced Filter/Sort window.

  2. Select the column you want to move.
    • To select one column, click its column selector.

    • To select more than one adjacent column, drag across their column selectors.

    Change the order of fields in a query by moving them

  3. Click the selector of any one of the selected columns again, and then drag the field or fields to their new location.

    The displaced field and all fields to its right move to the right.


 Resize a text box or other control in a group on a form or report

Resize a text box or other control in a group on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Click any control in the group to select the group.

  3. Click the control you want to resize.

  4. Drag the sizing handles of the control until it is the size you want.

    Sizing handles on a control

Notes

  • If you want to make small adjustments to the size of a control, you may find it easier to press SHIFT plus the appropriate arrow key.

  • When you resize a control in a group, the group rectangle is automatically resized to fit around all the controls.

  • You can resize all the controls in a group by dragging the sizing handles of the group rectangle.

  • If Snap To Grid is turned on, the group rectangle snaps to the grid when it’s resized. The controls in the group will not snap to the grid.


 Move a text box or other control in a group on a form or report

Move a text box or other control in a group on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Click any control in the group to select the group.

  3. Click the control you want to move.

  4. Do one of the following:
    • To move the control and its label, pass the pointer over the border (not the move handle) of the control until it turns into an open hand, and then drag the control and its label to a new position.

    Cursor changed to an open hand

    • To move the control or its label separately, place the pointer over the move handle in the upper-left corner of the control or label. When the pointer changes to an upward-pointing hand, drag the control or label.

    Cursor changed to an upward-pointing hand

Notes

  • If you want to move a control in small increments, you may find it easier to press CTRL plus the appropriate arrow key.

  • When you move a control in a group, the group rectangle is automatically resized to fit around all the controls.

  • If Snap To Grid is turned on, the group rectangle snaps to the grid when it’s moved. The controls in the group don't snap to the grid.


 Navigate between controls, records, and form pages by using a macro

Navigate between controls, records, and form pages by using a macro

  1. Create a macro.

    How?

  2. Do one of the following:

    To move the focus to a specific control or field in the current record, click GoToControl in the action list of a blank action row, and then set the Control Name argument to the name of the control to which you want to move.

    To make a specific record the current record, click GoToRecord in the action list of a blank action row, and then set the arguments.

    To move the focus in the active form to the first control on a specific form page, click GoToPage in the action list of a blank action row, and then set the arguments.

  3. Click Save [image] to save the macro.

  4. Run the macro.

    How?

For more information about the GoToControl action, click [image] .

For more information about the GoToRecord action, click [image] .

For more information about the GoToPage action, click [image] .


 Navigate between controls, records, and form pages by using Visual Basic

Navigate between controls, records, and form pages by using Visual Basic

  1. Open the event procedure for the appropriate event in the Code window.

    How?

    For example, to respond to a mouse click on a command button, open the button's Click event procedure.

  2. Do one of the following:

    To move the focus to a specific control or field in the current record, carry out the GoToControl method in the procedure, setting the Control Name argument to the name of the control to which you want to move.

    How?

    To make a specific record the current record or to create a new record, use the GoToRecord method to carry out the GoToRecord action in the procedure.

    To move the focus in the active form to the first control on a specific form page, use the GoToPage method to carry out the GoToPage action in the procedure.

  3. Run the procedure.

    How?

Tip You can also use Visual Basic for Applications to locate or move between records by using a Recordset object and the Seek method or any of the Move or Find methods.

For more information about the GoToControl action, click [image] .

For more information about the GoToRecord action, click [image] .

For more information about the GoToPage action, click [image] .

For more information about the Recordset object and its methods, click [image] .


 Use a macro to display related records when you move between records on a form

Use a macro to display related records when you move between records on a form

  1. Open the first form in Design view.

  2. Create a macro.

    How?

  3. In a blank action row, click OpenForm in the action list.

  4. Set the Form Name argument to the name of the second form, and then set the Where Condition argument to display the related records you want in the second form. For an example, click [image] .

  5. In form Design view, set the OnCurrent event property of the first form to the name of the macro.


 Use Visual Basic to display related records when you move between records on a form

Use Visual Basic to display related records when you move between records on a form

  1. Open the first form in Design view.

  2. Open the form's Form_Current event procedure.

    How?

  3. Add Visual Basic code to the event procedure to display records in the second form that have field values that match a related field on the first form.

For an example of using Visual Basic to display related records when you move between records on a form, click [image] .


 Open a query in Design view

Open a query in Design view

  1. In the Database window, click Queries [image] under Objects.

  2. Click the query you want to open, and then click Design on the Database window toolbar.

Notes

  • If a form, report, or data access page is based on a query, you can open the query to modify its design directly from the form, report, or data access page. For more information, click [image] .

  • If you previously saved a query while it was displayed in SQL view, that's the view Microsoft Access displays the next time you click Design on the Database window toolbar for that query.


 Overview of the Office Assistant

Overview of the Office Assistant

To use Microsoft Office objects from Microsoft Access, you must first set a reference to the Microsoft Office object library. Click References on the Tools menu while in module Design view and select the check box next to Microsoft Office 9.0 Object Library.

If you fail to set this reference, you'll get a compile-time error, "User-defined type not defined", when you try to use objects in the Microsoft Office object library.

Once you've set a reference to the Microsoft Office object library, you can view the Microsoft Office objects, properties, and methods in the Object Browser. The objects that you can use to program the Office Assistant include the Assistant, Balloon, BalloonCheckbox, and BalloonLabel objects, and the BalloonCheckboxes and BalloonLabels collections.

The following properties of the Assistant object aren't available in Microsoft Access, although they may be available in other Microsoft Office applications:

  • FeatureTips property

  • HighPriorityTips property

  • KeyboardShortcutTips property

  • MouseTips property

Note The Office Assistant isn't available in the run-time version of Microsoft Access.


 Overview of Command Bars

Overview of Command Bars

In order to program with command bars in Microsoft Access 2000, you must first set a reference to the Microsoft Office object library. Click References on the Tools menu while in module Design view, and select the check box next to Microsoft Office 9.0 Object Library.

Once you've set a reference to the Microsoft Office object library, you can view the Microsoft Office objects, properties, and methods in the Object Browser. The objects that you can use to program command bars include the CommandBar, CommandBarControl, CommandBarButton, CommandBarComboBox, and CommandBarPopup objects, and the CommandBars and CommandBarControls collections.


My report prints blank pages.

If you get a blank page only at the end of a report or printed form, make sure the Height property is set to zero for the report footer or form footer. For information on setting properties, click [image] .

If every other page is blank, make sure that the total width of the form or report plus the widths of the left and right margins don't exceed the paper size specified in the Page Setup dialog box (File menu). You can use the following formula as a guide:

form or report width + left margin + right margin <= paper size

You can adjust the form or report in one or both of the following ways:

  • Reduce the width of the form or report.

    How?

  • Reduce the margins or change the page orientation.

    How?


 Preview the layout of a report

Preview the layout of a report

Layout Preview is a fast way to check the layout of a report because Microsoft Access uses just enough data from the underlying table or query to show you what the report will look like. If you want to review the exact data that will appear in a report, use Print Preview. For more information, click [image] .

  • In report Design view, click the arrow next to the View button on the toolbar and then click Layout Preview.

Notes

  • If the report is based on a query that prompts you for parameters, you don't need to enter any values; just click OK. Microsoft Access ignores the parameters when you choose Layout Preview.

  • You can use the navigation buttons at the bottom of the Print Preview window to move between pages. You can move around the current page using the scroll bars, or, if you have a Microsoft IntelliMouse, using the wheel button.

  • For information on viewing the report at different magnifications, click [image] .

  • For information on viewing two or more pages at a time, click [image] .


 Preview records affected by a make-table, delete, append, or update query

Preview records affected by a make-table, delete, append, or update query

  • In query Design view, click View [image] on the toolbar to display the query in Datasheet view.
    For this query | The datasheet displays
    Update | The fields to be updated.
    Delete | The records to be deleted.
    Make-table | The fields to be included in the new table.
    Append | The records to be added to another table.


 Preview the data in a report

Preview the data in a report

To preview a report from Design view

  • In Design view, click Print Preview [image] on the toolbar.

To preview a report from the Database window

  1. In the Database window, click Reports [image] under Objects.

  2. Select the report you want to preview.

  3. On the Database window toolbar, click the Preview button.

Notes

  • You can use the navigation buttons at the bottom of the Print Preview window to move between pages. You can move around the current page using the scroll bars, or, if you have a Microsoft IntelliMouse, using the wheel button.

  • For information on viewing the report at different magnifications, click [image] .

  • For information on viewing two or more pages at a time, click [image] .


 Print a form from the Database window

Print a form from the Database window

  1. Click Forms [image] under Objects.

  2. Select the form you want to print.

  3. On the File menu, click Print.

  4. In the Print dialog box, select the printing options you want.

  5. Click OK.

Microsoft Access prints the form in the view specified in the form's DefaultView property.

Tip If you want to print a form without having to specify options in the Print dialog box, click Print [image] on the toolbar.


 Print a form from Design view, Form view, or Datasheet view

Print a form from Design view, Form view, or Datasheet view

  1. On the File menu, click Print.

  2. In the Print dialog box, select the printing options you want.

How Microsoft Access prints a form depends on the view from which you print it.

From | The form prints
Design view | In Form view.
Form view | In Form view.
Datasheet view | As a datasheet.

Tip If you want to print a form without having to specify options in the Print dialog box, click Print [image] on the toolbar.


 Quit Microsoft Access

Quit Microsoft Access

  • Click Exit on the File menu.

    Microsoft Access automatically saves changes to your data whenever you quit. However, if you have made changes to the design of any database objects since you last saved them, Microsoft Access asks whether you want to save these changes before quitting.

Caution If you exit Microsoft Access unexpectedly, your database may become damaged. Whenever possible, exit Microsoft Access as described in this topic.


 Reconnect a link to a background picture on a form or report

Reconnect a link to a background picture on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Double-click the form selector or the report selector to open the property sheet for the form or report.

  3. Specify the correct path for the picture in the Picture property.


 Reconnect a link to a picture in an image control on a form or report

Reconnect a link to a picture in an image control on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Make sure that the image control is selected, and then click Properties [image] on the toolbar.

  3. Specify the correct path for the picture in the Picture property.


 Reconnect or change a link to a picture in a bound or unbound object frame on a form or report

Reconnect or change a link to a picture in a bound or unbound object frame on a form or report

  1. Do one of the following:
    • If the object is unbound, click the object in form or report Design view.

    • If the object is bound, open the form in Form view (or open a datasheet), find the record you want to change, and click the object.
  2. On the Edit menu, click OLE/DDE Links.

  3. In the Links box, click the link you want to reconnect or change.

  4. Click Change Source.

  5. In the Change Source dialog box, select the new file name. You may need to switch to a different drive and/or folder to find the appropriate file.

  6. Click Open to complete the link and close the Change Source dialog box, and then click Close in the Links dialog box.

Note When you make any changes to a link for a bound object frame, you're changing the link only for the current record. To make a change in a different record, move to that record and repeat the process.


Set the tab order of text boxes or other controls on a data access page

What do you want to do?

Change the tab order

Remove a text box or other control from the tab order


 Remove a text box or other control from the tab order on a form

Remove a text box or other control from the tab order on a form

  1. Open a form in Design view.

  2. Make sure the control is selected, and then click Properties [image] on the toolbar to display the control's property sheet.

  3. In the TabStop property box, click No.

Note As long as a control's Enabled property is set to Yes, you can click the control to select it even if its TabStop property is set to No.


 Remove the default theme for new data access pages

Remove the default theme for new data access pages

  1. Open any data access page in Design view.

  2. On the Format menu, click Theme.

  3. In the Choose a theme list, click (No Theme).

  4. Click Set Default.

  5. Click Yes.


 Remove a field from the design grid in a query or advanced filter

Remove a field from the design grid in a query or advanced filter

  1. Open a query in Design view, or open a form or datasheet and display the Advanced Filter/Sort window.

  2. Select the field by clicking its column selector, and then press the DEL key.

Note When you remove a field from the design grid, you're only removing it from the query or filter's design. You're not deleting the field and its data from the underlying table, nor, in the case of a filter, are you removing it from the filtered results.


 Remove a table or query from a query

Remove a table or query from a query

  1. Open a query in Design view.

  2. In the upper part of query Design view, select the table or query you want to remove by clicking anywhere in its field list, and then press the DEL key.

    Fields that you have dragged from the field list to the design grid are also removed from the query. The table or query is not deleted from the database, however.


 Remove a text box or other control from a group on a form or report

Remove a text box or other control from a group on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Click any control in the group to select the group.

  3. On the Format menu, click Ungroup.

  4. Click the form background to cancel selection of the controls that were in the group..

  5. Select the controls you now want in the group. How to select adjacent controls. How to select nonadjacent or overlapping controls.

  6. On the Format menu, click Group.


 Remove a theme from an existing data access page

Remove a theme from an existing data access page

  1. Open the data access page you want to remove the theme from in Design view.

  2. On the Format menu, click Theme.

  3. In the Choose a theme list, click (No Theme).


 Delete or rename a group

Delete or rename a group

  1. If you haven't already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  2. Click the Groups bar to display the groups, and then right-click the group you want to delete or rename.

  3. Do one of the following:

    To delete the group, click Delete Group on the shortcut menu.

    To rename the group, click Rename Group on the shortcut menu, and then type a new name for the group in the New Group Name box.


 Rename a field in a query

Rename a field in a query

  1. Open a query in Design view.

  2. Place the insertion point to the left of the first letter of the field name in the design grid.

  3. Type the new name followed by a colon.

    Change a field heading that displays in a query

Note If you're replacing the field name Expr1 (or Expr2, and so on) that Microsoft Access automatically assigned, replace only the name, not the expression that follows the colon.


 Rename or delete a database object shortcut in a group

Rename or delete a database object shortcut in a group

  1. If you haven't already done so, switch to the Database window. You can press F11 to switch to the Database window from any other window.

  2. Click the Groups bar, and then click the group that contains the database object shortcut you want to delete or rename.

  3. Right-click the shortcut.

  4. Do one of the following:

    To delete the shortcut, click Delete [image] on the shortcut menu.

    To rename the shortcut, click Rename on the shortcut menu, and then type a new name for the shortcut.

Notes
  • Deleting a database object shortcut from a group only deletes the shortcut to that object; it does not delete the object itself. For example, if you delete a form shortcut from your group, and then click Forms [image] under Objects in the Database window, that form still appears in the list of all forms.

  • Renaming a database object shortcut in a group changes only the name of the shortcut; it does not change the name of the object itself.


 Rename a table or query that's added to a query

Rename a table or query that's added to a query

You can rename multiple copies of the same table or query in a query.

  1. Open a query in Design view.

  2. Click anywhere in the second copy of the field list for the table or query, and then click Properties [image] on the toolbar to display the property sheet.

  3. In the Alias property box, type a new name for the table or query.

Note Renaming copies of a table or query in a query doesn't rename the underlying table or query.


 Run a macro directly

Run a macro directly

To run a macro directly, do one of the following:

  • To run a macro from the Macro window, click Run [image] on the toolbar.

  • To run a macro from the Database window, click Macros [image] and then double-click a macro name.

  • To run a macro from anywhere else in Microsoft Access, on the Tools menu, point to Macro, and click Run Macro. Then click a macro in the Macro Name box.

Note You normally run a macro directly only to test it. You can then attach the macro to a form, report, or control so that it runs in response to an event, or you can create a custom menu command that runs the macro.


 Run a macro that is in a macro group

Run a macro that is in a macro group

To run a macro that is in a macro group, do one of the following:

  • Specify the macro as an event property setting on a form or report or as the Macro Name argument of the RunMacro action. Refer to the macro using this syntax:

    macrogroupname.macroname

    For example, this event property setting runs a macro called Categories in a macro group called Form Switchboard Buttons:

    Forms Switchboard Buttons.Categories

  • On the Tools menu, point to Macro, click Run Macro, and then select the macro from the Macro Name list. When macro names appear in lists, Microsoft Access includes an entry for each macro in each macro group.

  • Run a macro that is in a macro group from a Visual Basic procedure by using the RunMacro method of the DoCmd object, with the syntax shown previously to refer to the macro.


 Run a make-table, append, delete, or update query

Run a make-table, append, delete, or update query

  1. Open the query in Design view.

  2. To preview the records that will be affected, click View [image] on the toolbar and check the records. For information on what you're previewing, click [image] . To return to query Design view, click View [image] on the toolbar again. Make any changes you want in Design view.

  3. Click Run [image] on the toolbar to run the query.

Note To stop a query after you start it, press CTRL+BREAK.

For information on viewing the results of a make-table, append, or delete query, click [image] .

For information on viewing the results of an update query, click [image] .


 Save a copy of a PivotTable form's data

Save a copy of a PivotTable form's data

If you know that you'll need to edit a PivotTable form later on when you won't have access to the data, save a copy of the data with the PivotTable form. Note that saving the data can significantly increase the size of the form, so make sure that you have enough disk space available.

  1. Open the PivotTable form in Form view.

  2. Click the Edit PivotTable Object button.

  3. On the Data menu in Microsoft Excel, click Refresh Data.

  4. On the Data menu, click PivotTable and PivotChart Report to restart the PivotTable Wizard.

  5. Click Options.

  6. Under Data Source Options, make sure Save Data With Table Layout is selected.

  7. Click OK.

  8. Click Finish.

  9. Continue working with the PivotTable form, or close it and return to the form in Microsoft Access by clicking Close & Return To Pivot Form on the Microsoft Excel File menu.

Note The changes you make to data saved with a PivotTable form apply only to that PivotTable form; they don't affect data in the underlying table.


 Save a copy of a database object as another object type

Save a copy of a database object as another object type

  1. If the database object that you want to save as another object type is a table or a view, close the object.

  2. If the database object is open and is selected in the Database window, click Save As on the File menu.

    If the object isn’t open, click Objects in the Database window, and then click the type of object that you want. Select the object, and then click Save As on the File menu.

  3. In the Save As dialog box, type in the Save Object Name To box a unique name that follows Microsoft Access object-naming rules, and then click the object type that you want. If you are in a Microsoft Access database that is a Design Master, and if you want the new object to be replicated to other databases, select the Make Replicable check box.

Notes

  • You can save a table, a view, or a query as a form, or a report. The resulting object is identical to an object that would be created by using AutoForm or AutoReport.

  • You can save a form as a report, and you can save a macro as a Visual Basic module. However, a report, a data access page, or a module cannot be saved as another object type.

  • The Save As command is not available if a stored procedure or database diagram is selected in the Database window of an Access project.

  • Learn more about saving changes to a shared Access database.


 Save a database object by using a macro

Save a database object by using a macro

  1. Create a macro.

    How?

  2. In a blank action row, click Save in the action list, and then set the Object Type argument to the type of the object you want to save and the Object Name argument to the name of the object.

  3. Click Save [image] to save the macro.

  4. Run the macro.

    How?

    For example, to save a form by clicking a command button on the form, set the button's OnClick property to the name of the macro.

For more information about the Save action, click [image] .


 Save a database object by using an event procedure

Save a database object by using an event procedure

  1. Open the event procedure for the appropriate event in the Code window.

    How?

    For example, to save a form by clicking a command button on a form, open the button's Click event procedure.

  2. Use the Save method to carry out the Save action in the procedure, setting the objecttype argument to the type of the object you want to save and the objectname argument to the name of the object.

    How?

  3. Run the procedure.

    How?

For more information about the Save action, click [image] .


 Save the SQL statement for a form or report as a query

Save the SQL statement for a form or report as a query

By saving as a query the SQL statement displayed in the RecordSource property of a form or report, you can run the query independently, or base new forms and reports on the query.

  1. Open a form in form Design view or a report in report Design view.

  2. Double-click the form selector or the report selector to open the property sheet for the form or report.

  3. Next to the RecordSource property box, click the Build button [image] to display query Design view.

  4. Click Save [image] on the toolbar.

  5. In the Save As dialog box, enter a name that follows Microsoft Access object-naming rules, and then click OK.

    Microsoft Access adds the query to Queries [image] under Objects in the Database window.


 Use the Save As command to copy a database object

Use the Save As command to copy a database object

  1. If the database object that you want to save is a table, a module, or a view, close the object.

  2. If the database object is open and is selected in the Database window, click Save As on the File menu.

    If the object isn't open, in the Database window, click the object type under Objects; click the object, and then click Save As on the File menu.

  3. In the Save As dialog box, type a unique name that follows Microsoft Access object-naming rules, and then click OK. If you are in a Microsoft Access database that is a Design Master, and if you want the new object to be replicated to other databases, then select the Make Replicable check box.

    For information on exporting objects and data, click [image] .

Notes

  • When you use this procedure to create a copy of a data access page, Microsoft Access prompts you to provide a name for the new HTML file.

  • Learn more about saving changes to a shared Access database


 Adjust the size of a picture displayed in an image control or object frame on a form or report

Adjust the size of a picture displayed in an image control or object frame on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Make sure that the image control, bound object frame, or unbound object frame is selected.

  3. Click Properties [image] on the toolbar to display the property sheet.

  4. In the SizeMode property box, click one of the following settings:
    • Clip Displays the picture at actual size. If the picture is larger than the area within the control, the image is cut off.

    • Stretch Sizes the picture to fit the area within the control. This setting may distort the image.

    • Zoom Displays the picture in its entirety after sizing it to fill either the height or width of the area within the control. This setting won't distort the image.


Select fields to add to the design grid in a query or advanced filte

Select fields to add to the design grid in a query or advanced filter

To select | Do this
A field | Click the field name.
A block of fields | Click the first field in the block, hold down SHIFT, and click the last field.
Noncontiguous fields | Hold down CTRL as you click the fields.
All fields | Double-click the title bar of the field list or click the asterisk (*). (For more information on using the asterisk, click [image] .)

Notes

  • Once you've selected fields in the field list, you must drag them to the design grid.

  • When you drag more than one field at a time, Microsoft Access places each field in a separate column. If you drag the asterisk to the grid, Microsoft Access places the table or query name in one column and attaches a period and asterisk to the name (for example, Categories.*). After either operation, the datasheet looks the same.

  • Instead of dragging, you can also add fields by double-clicking the name in the field list or selecting a field directly from the list box in the Field row on the grid.


 Change the number of times scrolling text repeats on a data access page

Change the number of times scrolling text repeats on a data access page

  1. Open a data access page in Design view.

  2. Select the scrolling text control, and then click Properties [image] on the toolbar to display the control’s property sheet.

  3. Do one of the following:
    • To make the text scroll continuously, in the Loop property box type –1.

    • To make the text scroll a specific number of times and then disappear, in the Loop property box type an integer. For example, if you set the Loop property to 5, the text will scroll five times.


 Change the motion of scrolling text on a data access page

Change the motion of scrolling text on a data access page

  1. Open a data access page in Design view.

  2. Select the scrolling text control, and then click Properties [image] on the toolbar to display the control’s property sheet.

  3. Do one of the following:
    • To make the text scroll continuously in the control like a stock ticker, in the Behavior property box click Scroll.

    • To make the text slide from the starting point to the opposite edge of the control and then remain on the screen, in the Behavior property box click Slide.

    • To make the text go back and forth from the starting point to the opposite edge of the control, and have it remain on the screen at all times, in the Behavior property box, click Alternate.


 Select a single text box or other control in a group

Select a single text box or other control in a group

  1. Open a form in Design view or a report in Design view.

  2. Click any control in the group to select the group.

  3. Click the control you want to select.

Notes

  • When you select a single control in a group, all the properties for that control are available on the property sheet.

  • When you click any control within a group, thus selecting the whole group, the property sheet displays only those properties common to all the controls within the group.


 Send commands to an SQL database using a pass-through query

Send commands to an SQL database using a pass-through query

Microsoft Access pass-through queries send commands directly to an ODBC database server (such as Microsoft FoxPro). With pass-through queries, you work directly with the tables on the server instead of linking to them.

  1. In the Database window, click Queries [image] under Objects, and then click New on the Database window toolbar.

  2. In the New Query dialog box, click Design View, and then click OK.

  3. Without adding tables or queries, click Close in the Show Table dialog box.

  4. On the Query menu, point to SQL Specific, and then click Pass-Through.

  5. On the toolbar, click Properties [image] to display the query property sheet.

  6. In the query property sheet, set the ODBCConnectStr property to specify information on the database to which you want to connect. You can type the connection information, or click Build [image] , and then enter information about the server you're connecting to.

    For details on the syntax for your query, see the documentation for the SQL database server to which you're sending the query.

  7. If the query isn't the type that returns records, set the ReturnsRecords property to No.

  8. In the SQL Pass-Through Query window, type your pass-through query.

  9. To run the query, click Run [image] on the toolbar. (For a pass-through query that returns records, you can click View [image] on the toolbar, instead.)

    If necessary, Microsoft Access prompts you for information about your Microsoft SQL server database.

    Caution If you convert a pass-through query to another type of query, such as a select query, you'll lose the SQL statement that you entered.

Notes

  • Pass-through queries are useful for running stored procedures on an ODBC server.

  • If you don't specify a connection string in the ODBCConnectStr property, or if you delete an existing string, Microsoft Access uses the default string "ODBC;". With this setting, Microsoft Access prompts you for connection information each time you run the query.

  • Some pass-through queries can return messages in addition to data. If you set the query's LogMessages property to Yes, Microsoft Access creates a table that contains any returned messages. The table name is the user name concatenated with a hyphen ( - ) and a sequential number starting at 00. For example, the default user name is ADMIN so the tables returned would be named "ADMIN - 00," "ADMIN - 01," and so on.

    If you create a pass-through query that returns multiple result sets, you can create a separate table from each result. For more information, click [image] .


 Specify arguments when you use a procedure, statement, or method in Visual Basic code

Specify arguments when you use a procedure, statement, or method in Visual Basic code

  • Specify the arguments immediately after the name of the procedure, statement, or method. For a Function procedure or a method that returns a value, enclose the arguments in parentheses. If you specify more than one argument, separate the arguments with a comma.

For example, the following Close method of the DoCmd object closes the Add Products form. It accepts two arguments, acForm and "Add Products":

DoCmd.Close acForm, "Add Products"

Because the Close method doesn't return a value, the arguments aren't enclosed in parentheses.

Tip You can use the Object Browser to paste method or property syntax, including arguments, into your Visual Basic code. The Object Browser pastes named arguments that you can specify in any order. You can use these named arguments, or you can replace the named arguments with standard arguments. For more information on using the Object Browser, click [image] . For more information on using named arguments, click [image] .


 Change the ENTER key, arrow keys, TAB key, and insertion point default behavior

Change the ENTER key, arrow keys, TAB key, and insertion point default behavior

Set these options to change the behavior of the specified keys for moving within or between fields.

  1. On the Tools menu, click Options.

  2. Click the Keyboard tab.

  3. Under Move After Enter, Arrow Key Behavior, and Behavior Entering Field, select the options you want, and then select or clear the Cursor Stops At First/Last Field check box.

Notes

  • For Microsoft Access to use the Behavior Entering Field option you select, Arrow Key Behavior must be set to Next Field.

  • These settings do not apply to data access pages.


 Specify the default language sort order for a database

Specify the default language sort order for a database

Set this option to specify the alphabetical sort order that Microsoft Access uses when you create a new database.

  1. On the Tools menu, click Options.

  2. Click the General tab.

  3. In the New Database Sort Order box, click the language that you want to use.

Notes

  • To reset the sort order for an existing database to the language that you selected on the General tab, compact that database.

  • Some languages that were listed separately in the New Database Sort Order list in previous versions of Microsoft Access are now included in the General sort order setting.

  • If your database contains linked tables from a database that uses a different language sort order, Microsoft Access uses the sort order of your database, not the database where the table is stored.

  • If you're synchronizing between replicas in a Microsoft Access database and a Microsoft SQL Server database, you might encounter synchronization conflicts if the databases don't have the same language sort orders.


 Change the default folder for new Microsoft Access databases or projects

Change the default folder for new Microsoft Access databases, projects, or pages

  1. On the Tools menu, click Options.

  2. Click the General tab.

  3. In the Default Database Folder box, type the path name of any valid folder where you want to store new Microsoft Access database files, Microsoft Access project files, or data access pages and any associated files, and then click OK.

    Note For data access pages, this option only applies when you have an Access database or Access project open at the time you create and save the page. Otherwise, your page is saved to the default folder for your system.


 Set margins and other page setup options for a data access page

Set margins and other page setup options for a data access page

  1. Open the data access page in Design view.

  2. On the File menu, click Page Setup.

  3. In the Page Setup dialog box, set options for paper size, headers and footers, page orientation, and margins.


 Set page setup options for a table, query, form, or report

Set page setup options for a table, query, form, or report

  1. Open the database object in one of the following views:
    • Open a table or query in Datasheet view or Print Preview.

    • Open a form or report in any view (or from the Database window).

    Note Page setup options aren't available for macros or modules.

  2. On the File menu, click Page Setup.

  3. Click the following tabs for the options you want to set:
    • Margins. To set margins and whether to print data only (for forms and reports) or to print headings (for tables or queries).

    • Page. To set orientation, paper size, and printer.

    • Columns. To set number, size, and layout of columns (for forms and reports).
  4. Click OK.

    Microsoft Access stores the settings for page setup options with a form or report, so you set these options only once for each form or report. For tables, queries, and modules, you must set page setup options every time you print.


 Set Data Access Page Properties in Visual Basic

Set Data Access Page Properties in Visual Basic

DataAccessPage objects are Microsoft Access objects. You can set properties for these objects from within a Sub, Function, or event procedure.

To set a property of a data access page

Refer to the individual data access page within the DataAccessPages collection, followed by the name of the property and its value. For example, to set the Visible property of the Customers data access page to True (–1), use the following line of code:

DataAccessPages!Customers.Visible = True

Notes

  • For each property you want to set, you can look up the property in the Help index to find information about:
    • Whether you can set the property from Visual Basic.

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


 Set Form, Report, and Control Properties in Visual Basic

Set Form, Report, and Control Properties in Visual Basic

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

To set a property of a form or report

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

Forms!Customers.Visible = True

You can also set a property of a form or report from within the object's module by using the object's Me property. Code that uses the Me property executes faster than code that uses a fully qualified object name. For example, to set the RecordSource property of the Customers form to an SQL statement that returns all records with a CompanyName field entry beginning with "A" from within the Customers form module, use the following line of code:

Me!RecordSource = "SELECT * FROM Customers " _
    & "WHERE CompanyName Like 'A*'"

To set a property of a control

Refer to the control in the Controls collection of the Form or Report object on which it resides. You can refer to the Controls collection either implicitly or explicitly, but the code executes faster if you use an implicit reference. The following examples set the Visible property of a text box called CustomerID on the Customers form:

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

The fastest way to set a property of a control is from within an object's module by using the object's Me property. For example, you can use the following code to toggle the Visible property of a text box called CustomerID on the Customers form:

With Me!CustomerID
    .Visible = Not .Visible
End With

To set a property of a form or report section

Refer to the form or report within the Forms or Reports collection, followed by the Section property and the integer or constant that identifies the section. The following examples set the Visible property of the page header section of the Customers form to False (0):

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

Notes

  • For each property you want to set, you can look up the property in the Help index to find information about:
    • Whether you can set the property from Visual Basic.

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

    • Which values you should use to set the property. You often use different settings when you set a property in Visual Basic instead of in the property sheet. For example, if the property settings are selections from a list, you must use the value or numeric equivalent for each selection.
  • To set default properties for controls from Visual Basic, use the DefaultControl method.


 Set Options from Visual Basic

Set Options from Visual Basic

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

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

Notes

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.

Some options are available only within a Microsoft Access database (.mdb) or Access project (.adp). The exceptions are noted with a (MDB only) or (ADP only) notation.

View Tab

Option text | String argument
Show |
Status bar | Show Status Bar
Startup dialog box | Show Startup Dialog Box
New object shortcuts | Show New Object Shortcuts
Hidden objects | Show Hidden Objects
System objects | Show System Objects
Use taskbar for each document | Use Taskbar For Each Document
Show in macro design |
Names column | Show Macro Names Column
Conditions column | Show Conditions Column
Click options in database window | Database Explorer Click Behavior
Use substitute font | Enable Font Switching
Substitute font name | Substitute Font Name

General Tab

Option text | String argument
Print margins |
Left Margin | Left Margin
Right Margin | Right Margin
Top Margin | Top Margin
Bottom Margin | Bottom Margin
Default database folder | Default Database Directory
Provide feedback with sound | Provide Feedback With Sound
Recently used file list | Enable MRU File List
# of recently used file list | Size of MRU File List
New database sort order (MDB only) | New Database Sort Order
Compact current database | Auto Compact
Compact when database will shrink by this percentage or more | Auto Compact Percentage
Name AutoCorrect (MDB only) |
Track name AutoCorrect info | Track Name AutoCorrect Info
Perform name AutoCorrect | Perform Name AutoCorrect
Log name AutoCorrect changes | Log Name AutoCorrect Changes

WebOptions Button (General tab)

Options listed in italic are listed for backward compatibility. With the exception of the Show Hyperlink Addresses In Status Bar option, all other options are hidden but can be set with the SetOption method. For more information about Web options, see DefaultWebOptions.

Option text | String argument
Hyperlink color | Hyperlink Color
Followed Hyperlink color | Followed Hyperlink color
Underline hyperlinks | Underline Hyperlinks
Show Hyperlink Addresses In Status Bar | Note Not valid for Microsoft Access 2000. Address shown in tooltips.
HTML Template | HTML Template
Data Source Name | Data Source Name
User Name | User Name
Password | Password
Server URL | Active Server Pages URL
Session Timeout | Active Server Pages Session Timeout

Edit/Find Tab

Option text | String argument
Default find/replace behavior | Default Find/Replace Behavior
Confirm |
Record changes | Confirm Record Changes
Document deletions | Confirm Document Deletions
Action queries (MDB only) | Confirm Action Queries
Show list of values in (MDB only) |
Local indexed fields | Show Values In Indexed
Local nonindexed fields | Show Values In Non-Indexed
ODBC fields | Show Values In Remote
Don't display lists where more than this number of records read | Show Values Limit
Show list of values in (ADP only) |
Records in local snapshot | Show Values In Snapshot
Records at server | Show Values In Server
Don't display lists where more than this number of records read | Show Values Limit

Keyboard Tab

Option text | String argument
Move after enter | Move After Enter
Behavior entering field | Behavior Entering Field
Arrow Key Behavior | Arrow Key Behavior
Cursor Stops At First/Last Field | Cursor Stops at First/Last Field

Datasheet Tab

Option text | String argument
Default Colors |
Font | Default Font Color
Background | Default Background Color
Gridlines | Default Gridlines Color
Default gridlines showing |
Horizontal | Default Gridlines Horizontal
Vertical | Default Gridlines Vertical
Default column width | Default Column Width
Default Font |
Font | Default Font Name
Weight | Default Font Weight
Size | Default Font Size
Italic | Default Font Italic
Underline | Default Font Underline
Default cell effect | Default Cell Effect
Show animations | Show Animations

Forms/Reports Tab

Option text | String argument
Selection Behavior | Selection Behavior
Form template | Form Template
Report template | Report Template
Always use event procedures | Always Use Event Procedures

Advanced Tab (MDB Only)

Option text | String argument
Ignore DDE Requests | Ignore DDE Requests
Enable DDE Refresh | Enable DDE Refresh
Default Open Mode | Default Open Mode for Databases
Command-Line Arguments | Command-Line Arguments
OLE/DDE Timeout (Sec) | OLE/DDE Timeout (Sec)
Number Of Update Retries | Number of Update Retries
ODBC Refresh Interval (Sec) | ODBC Refresh Interval (Sec)
Refresh Interval (Sec) | Refresh Interval (Sec)
Update Retry Interval (Msec) | Update Retry Interval (Msec)
Default Record Locking | Default Record Locking
Use Record Level Locking | Use Record Level Locking

Advanced Tab (ADP Only)

Option text | String argument
Ignore DDE Requests | Ignore DDE Requests
Enable DDE Refresh | Enable DDE Refresh
Default Max Records | Row Limit
Save login and password | Save Login And Password
Command-Line Arguments | Command-Line Arguments
OLE/DDE Timeout (Sec) | OLE/DDE Timeout (Sec)

Tables/Queries Tab (MDB Only)

Option text | String argument
Default field sizes |
Text | Default Text Field Size
Number | Default Number Field Size
Default Field Type | Default Field Type
AutoIndex On Import/Create | AutoIndex On Import/Create
Show table names | Show Table Names
Output all fields | Output All Fields
Enable AutoJoin | Enable AutoJoin
Run Permissions | Run Permissions

Note If you are developing a database application, add-in, library database, or referenced database, make sure that the Error Trapping option is set to 2 (Break On Unhandled Errors) when you have finished debugging your code.

The value that you pass to the SetOption method as the setting argument depends on which type of option you are setting. The following table establishes some guidelines for setting options.

If the option is | Then the setting argument is
A text box | A string
A check box | A Boolean value — True (–1) or False (0)
An option button in an option group, or an option in a combo box or a list box | An integer corresponding to the option's position in the option group or list (starting with zero [0])


 Set Properties of ActiveX Data Objects in Visual Basic

Set Properties of ActiveX Data Objects in Visual Basic

ActiveX Data Objects (ADO) enable you to manipulate the structure of your database and the data it contains from Visual Basic. Many ADO objects correspond to objects that you see in your database — for example, a Table object corresponds to a Microsoft Access table. A Field object corresponds to a field in a table.

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

Setting ADO Properties for ADO Objects

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

Dim tbl As New ADOX.Table
Dim cnn As ADODB.Connection
Set cnn = CurrentProject.Connection
tbl.Name = "Contacts"

Setting Microsoft Access Properties for ADO Objects

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

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

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

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

If the property setting is | Then the Type property setting should be
A string | adLongVarWChar or adVarWChar
True/False | adBoolean
An integer | adInteger

The following table lists some Microsoft Access–defined properties that apply to ADO objects.

ADO object | Microsoft Access–defined properties
Connection | AppTitle, AppIcon, StartupShowDBWindow, StartupShowStatusBar, AllowShortcutMenus, AllowFullMenus, AllowBuiltInToolbars, AllowToolbarChanges, AllowBreakIntoCode, AllowSpecialKeys, Replicable, ReplicationConflictFunction
Table | DatasheetBackColor, DatasheetCellsEffect, DatasheetFontHeight, DatasheetFontItalic, DatasheetFontName, DatasheetFontUnderline, DatasheetFontWeight, DatasheetForeColor, DatasheetGridlinesBehavior, DatasheetGridlinesColor, Description, FrozenColumns, RowHeight, ShowGrid
QueryDef | DatasheetBackColor, DatasheetCellsEffect, DatasheetFontHeight, DatasheetFontItalic, DatasheetFontName, DatasheetFontUnderline, DatasheetFontWeight, DatasheetForeColor, DatasheetGridlinesBehavior, DatasheetGridlinesColor, Description, FailOnError, FrozenColumns, LogMessages, MaxRecords, RecordLocks, RowHeight, ShowGrid, UseTransaction
Field | Caption, ColumnHidden, ColumnOrder, ColumnWidth, DecimalPlaces, Description, Format, InputMask


 Set Properties of Data Access Objects in Visual Basic

Set Properties of Data Access Objects in Visual Basic

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

Most of the properties you can set for DAO objects are DAO properties. These properties are defined by the Microsoft Jet database engine and are set the same way in any application that includes the Jet database engine. Some properties that you can set for DAOobjects are defined by Microsoft Access, and aren't automatically recognized by the Jet database engine. How you set properties for DAO objects depends on whether a property is defined by the Jet database engine or by Microsoft Access.

Setting DAO Properties for DAO Objects

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

Dim dbs As Database, tdf As TableDef
Set dbs = CurrentDb
Set tdf = dbs.CreateTableDef
tdf.Name = "Contacts"

Setting Microsoft Access Properties for DAO Objects

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

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

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

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

If the property setting is | Then the Type property setting should be
A string | dbText
True/False | dbBoolean
An integer | dbInteger

The following table lists some Microsoft Access–defined properties that apply to DAO objects.

DAO object | Microsoft Access–defined properties
Database | AppTitle, AppIcon, StartupShowDBWindow, StartupShowStatusBar, AllowShortcutMenus, AllowFullMenus, AllowBuiltInToolbars, AllowToolbarChanges, AllowBreakIntoCode, AllowSpecialKeys, Replicable, ReplicationConflictFunction
SummaryInfo Container | Title, Subject, Author, Manager, Company, Category, Keywords, Comments, Hyperlink Base (See the Summary tab of the DatabaseName Properties dialog box, available by clicking Database Properties on the File menu.)
UserDefined Container | (See the Summary tab of the DatabaseName Properties dialog box, available by clicking Database Properties on the File menu.)
TableDef | DatasheetBackColor, DatasheetCellsEffect, DatasheetFontHeight, DatasheetFontItalic, DatasheetFontName, DatasheetFontUnderline, DatasheetFontWeight, DatasheetForeColor, DatasheetGridlinesBehavior, DatasheetGridlinesColor, Description, FrozenColumns, RowHeight, ShowGrid
QueryDef | DatasheetBackColor, DatasheetCellsEffect, DatasheetFontHeight, DatasheetFontItalic, DatasheetFontName, DatasheetFontUnderline, DatasheetFontWeight, DatasheetForeColor, DatasheetGridlinesBehavior, DatasheetGridlinesColor, Description, FailOnError, FrozenColumns, LogMessages, MaxRecords, RecordLocks, RowHeight, ShowGrid, UseTransaction
Field | Caption, ColumnHidden, ColumnOrder, ColumnWidth, DecimalPlaces, Description, Format, InputMask


 Set Startup Properties from Visual Basic

Set Startup Properties from Visual Basic

In a Microsoft Access database (.mdb), startup properties are properties of a Database object. A Database object is a DAO object supplied by the Microsoft Jet database engine, but startup properties are defined by Microsoft Access, so they aren't automatically recognized by the Jet database engine. If a startup property hasn't been set previously, you must create it and add it to the Properties collection of the Database object.

In a Microsoft Access project (.adp), startup properties are properties of a CurrentProject object and like the Database object in an Access database (.mdb), startup properties aren't automatically recognized by the Jet database engine. If a startup property hasn't been set previously, you must create it and add it to the AccessObjectProperties collection of the CurrentProject object.

When you set startup properties from Visual Basic, you should include error-handling code to verify that the property exists in the Properties or AccessObjectProperties collection. For more information about setting properties defined by Microsoft Access, see Set Properties of Data Access Objects in Visual Basic or Set Properties of ActiveX Data Objects in Visual Basic.

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

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


 Set the value of a control based on the value of another control by using a macro

Set the value of a control based on the value of another control by using a macro

  1. Create a macro.

    How?

  2. In a blank action row, click SetValue in the action list.

  3. Set the Item argument to the identifier for the control whose value you want to set, and then set the Expression argument to the identifier for the control whose value you want to assign to the first control.

    Assign the value of one control to another

  4. Click Save [image] to save the macro.

  5. Run the macro.

    How?

Note Depending on the context, you might need to use qualified identifiers for the controls. For more information about using identifiers in expressions, click [image] .


 Set the value of a control based on the value of another control by using Visual Basic

Set the value of a control based on the value of another control by using Visual Basic

  1. Create a Visual Basic procedure.

    How?

  2. Add an assignment statement to the procedure by typing the identifier for the control whose value you want to set, an equal sign (=), and the identifier for the control whose value you want to assign to the first control.

    To refer to the value of a control on the current form, type the Me keyword followed by the ! operator and the name of the control. For example, the following statement assigns the value of the City control on the current form to the ShipCity control on the current form:

    Me![ShipCity] = Me![City]

    To refer to the value of a control on a different form, type the control's full identifier. For example, the following identifier refers to the ShipCity control on the ShipForm form:

    Forms![ShipForm]![ShipCity]

  3. Run the procedure.

    How?

For more information about referring to the value of a control, click [image] .


 Set the value of a property in response to an event by using a macro

Set the value of a property in response to an event by using a macro

  1. Create a macro.

    How?

  2. In a blank action row, click SetValue in the action list.

  3. Set the Item argument to the identifier for the property whose value you want to set, and then set the Expression argument to the value you want to assign to the property.

    Set a value based on an event

  4. Click Save [image] to save the macro.

  5. Go to the form or report, open the property sheet for the object whose event will run the macro, and set the event property to the name of the macro.

For an example of setting the value of a property in response to an event, click [image] .


 Set the value of a property in response to an event by using Visual Basic

Set the value of a property in response to an event by using Visual Basic

  1. Create an event procedure for the event.

    How?

  2. Add an assignment statement to the procedure by typing the identifier for the property whose value you want to set, an equal sign (=), and the value you want to assign.

    To refer to the property of a control on the current form, type the Me keyword followed by the ! operator, the name of the control, the . (dot) operator, and the name of the property. For example, the following statement assigns the value False to the Visible property of the DateDue control on the current form:

    Me![DateDue].Visible = False

    To refer to the property of a control on a different form, type the control's full identifier. For example, the following identifier refers to the Visible property of the DateDue control on the ShipForm form:

    Forms![ShipForm]![DateDue].Visible

For more information about referring to a property, click [image] .

For an example of setting the value of a property in response to an event, click [image] .


 Set a watch expression in Visual Basic code

Set a watch expression in Visual Basic code

When you suspend execution of Visual Basic code, you can observe the values of watch expressions in the Watch window of the Visual Basic Editor. You can also perform an instant watch to see the value of an expression that hasn't been specified as a watch expression.

What do you want to do?

Add a watch expression to the Watch window of the Visual Basic Editor

Perform an instant watch


 Adding and Displaying Shortcut Menus

Adding and Displaying Shortcut Menus

Microsoft Access 2000 provides a user interface for adding and modifying shortcut menus. To add a custom shortcut menu, add a toolbar in the Customize dialog box, available by pointing to Toolbars on the View menu and clicking Customize, and then use the Toolbar Properties dialog box to change the Type of the toolbar to Popup. To delete a shortcut menu, you must change its type to Menu Bar or Toolbar, and then delete it. You can add, modify, and delete any shortcut menus in Visual Basic.

Built-in and custom shortcut menus are displayed in the Shortcut Menus toolbar, available by selecting the Shortcut Menus check box in the Customize dialog box. You can add and remove command buttons and menu items to and from shortcut menus by using the Shortcut Menus toolbar. Note, however, that to refer to a shortcut menu in Visual Basic, use the syntax CommandBars("shortcutmenuname"). The code CommandBars("Shortcut Menus") is meaningless.

You can use an event procedure to display a shortcut menu in response to a right mouse click. The following example displays the custom shortcut menu "CustomerFormShortcut" when the user right-clicks in a blank area or record selector on a form.

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, _
        X As Single, Y As Single)
    Dim cmdBar As CommandBar
    Dim intRight As Integer

    Set cmdBar = CommandBars("CustomerFormShortcut")
    intRight = (Button and acRightButton) > 0
        If intRight Then
            cmdBar.ShowPopup 200, 200
        End If
End Sub


 Show or hide the records for a group on a data access page

Show or hide the records for a group on a data access page

  • Click the expand indicator next to the group heading.


 Adjust the size and proportions of a background picture on a form or report

Adjust the size and proportions of a background picture on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Double-click the form selector or report selector to open the property sheet.

  3. In the PictureSizeMode property box, click one of the following settings:
    • Clip Displays the picture at actual size. If the picture is larger than the form or report, the image is cut off.

    • Stretch Sizes the picture to fit within the form or report. This setting may distort the image.

    • Zoom Displays the picture in its entirety after sizing it to fill either the height or width of the form or report. This setting won't distort the image.

    Note If you set the PictureTiling property to Yes, set the PictureSizeMode property to Clip.


 Sort records in Form or Datasheet view

Sort records in Form or Datasheet view

For a list of issues to consider when sorting records, click [image] .

  1. In Form view or Datasheet view, click the field you want to use for sorting records. To sort records in a subform, click the field you want to sort. To sort records in a subdatasheet, display the subdatasheet by clicking its expand indicator, and then click the field.

  2. Do one of the following:
    • To sort in ascending order, click Sort Ascending [image] .

    • To sort in descending order, click Sort Descending [image] .

Notes

  • In Datasheet view, when you sort the subdatasheet for one record, Microsoft Access sorts all the subdatasheets at that level.

  • In a form, you can sort on only one field at a time; in a datasheet or subdatasheet, you can select two or more adjacent columns at the same time, and then sort them. Microsoft Access sorts records starting with the leftmost selected column. When you save the form or datasheet, Microsoft Access saves the sort order.


 Sort records by using the design grid of a query or advanced filter

Sort records by using the design grid of a query or advanced filter

Before you specify a sort order, there are certain things you should consider. For more information, click [image] .

  1. Open a query in Design view or display the Advanced Filter/Sort window for a table, query, or form.

  2. To sort on more than one field, first arrange the fields in the design grid in the order you want the sorts performed. Microsoft Access sorts on the leftmost field first, then on the next field to the right, and so on. For example, to sort on the LastName field first and then on the FirstName field, the LastName field must be to the left of the FirstName field in the grid.

  3. In the Sort cell for each of the fields you want to sort on, click an option.

  4. To see the results of the query, click View [image] on the toolbar.


 Specify a command-line argument that can be used in Visual Basic code

Specify a command-line argument that can be used in Visual Basic code

When you start Microsoft Access from the command line, you can use the /cmd command-line option to specify a command-line argument that can be used in Visual Basic code.

For more information on the /cmd command-line option, click [image] .


 Specify the data type of a parameter in a parameter query

Specify the data type of a parameter in a parameter query

  1. In query Design view after creating a parameter query, click Parameters on the Query menu.

  2. In the first Parameter cell, type the first prompt you entered in the query design grid.

  3. In the Data Type cell to the right, click the data type you want.

  4. Repeat steps 2 and 3 for each parameter you want to specify a data type for.


 Specify a default value that is automatically entered in a combo box on a form

Specify a default value that is automatically entered in a combo box on a form

  1. Open a form in Design view.

  2. Make sure that the combo box is selected and then click Properties [image] on the toolbar.

  3. In the DefaultValue property box, type [comboboxname].ItemData(n) where n is the row that you want to use as the default. The ItemData property is zero-based, so type ItemData(0) if you want to make the first row in the list the default. For example, to specify the first row of the SupplierCombo combo box as the default for the combo box, type [SupplierCombo].ItemData(0) in the DefaultValue property box.

Note If you want to specify a default value for a lookup combo box in Microsoft Access database (.mdb) table Design view, enter a default value in the DefaultValue property for the foreign key. For example, if you have a SupplierID foreign key in a Products table, click the SupplierID field, and then enter a valid supplier ID number in the DefaultValue property box in the lower portion of the window. The next time you add this Supplier ID field to a form, Access automatically sets the default value for the field.


 Define a default value in table Design view

Define a default value in table Design view

  1. Open a table in Design view.

  2. In the upper portion of the window, click the field you want to define a default value for.

  3. In the lower portion of the window on the General tab, click the DefaultValue property box, and then type the default value (such as New York) or an expression (such as Date()).

    To view examples of default values, click [image] .

Notes

  • Setting the DefaultValue property for a field has no effect on existing data. However, you can replace a field's current value with the default value by pressing CTRL+ALT+SPACEBAR.

  • If you define a default value for a Yes/No field in a database that will be used internationally, enter an equal sign before the value, and Microsoft Access will display the default value in the local language. For example, enter =Yes to have Microsoft Access display "Ja" in Germany. You must set the DisplayControl property for the field to Text Box or Combo Box to see the value.


 Specify how long before a query displays an ODBC time-out error

Specify how long before a query displays an ODBC time-out error

A query that uses an ODBC database as its underlying source of data might encounter delays due to network traffic or heavy use of the ODBC server.

  1. Open a query in Design view.

  2. Select the query by clicking anywhere in query Design view outside the design grid and the field lists.

  3. Click Properties [image] on the toolbar to display the query's property sheet.

  4. Set the ODBCTimeout property to the number of seconds that the query waits before displaying a time-out error. The default is 60 seconds.

Note If you set the property to zero, no time-out error occurs.


 Specify a record-locking strategy for a query in a multiuser environment

Specify a record-locking strategy for a query in a multiuser environment

You can lock all records in the underlying table or only the record that you're editing. That way, other users can't change the record in the underlying table while you are editing it in the query's results.

  1. Open a query in Design view. In a multiuser environment, confirm that all users have closed the query, the underlying table or query, and other objects based on the query.

  2. Select the query by clicking anywhere in query Design view outside the design grid and the field lists.

  3. Click Properties [image] on the toolbar to display the query's property sheet.

  4. Click the RecordLocks property setting you want to use.

    For information on specifying a default setting for this property that all your queries will use, click [image] .

For more information about choosing a record-locking strategy, click [image] .


Document summary information of a Microsoft Access database or Microsoft Access project

  1. With the database open, click Database Properties on the File menu.

  2. Click the Summary tab, and then specify as much of the requested information as you want to.

    To get Help on an option, click the question mark [image] and then click the option.

  3. Click OK.

Note For each item you complete on the Summary tab, the associated properties are automatically set. For more information, click [image] .


 Specify a border and title bar for a pop-up form or custom dialog box

Specify a border and title bar for a pop-up form or custom dialog box

  1. Open the form in Design view.

  2. Double-click the form selector to open the form's property sheet.

  3. In the BorderStyle property box, click one of the settings. For information on the settings, click [image] . For information on creating pop-up forms and custom dialog boxes, click [image] .


 Specify whether a data access page opens for data entry

Specify whether a data access page opens for data entry

  1. Open the data access page in Design view.

  2. On the Edit menu, click Select Page.

  3. Click Properties [image] on the toolbar. Microsoft Access displays the page properties in the property sheet.

  4. Set the DataEntry property to True.

When you open the data access page in Page view or in Internet Explorer, the page will display a new blank record.


 Specify whether a form can be sized

Specify whether a form can be sized

In most cases, you don't want to prevent a form from being resized. Use this procedure for pop-up forms or custom dialog boxes.

  1. Open the form in Design view.

  2. Double-click the form selector to open the form's property sheet.

  3. In the BorderStyle property box, click None, Thin, or Dialog. To read more about these settings, click [image] .

Note For information on creating pop-up forms and custom dialog boxes, click [image] .


Choose which e-mail account to use to send a message

Note This procedure applies only if you installed Microsoft Outlook in Internet Only mode. Learn about how to get Outlook installation information.

  1. Display the message header by sending a database object as an attachment or sending a data access page as the body of an e-mail message.

  2. Click Options.

  3. In the Send message using box, click the account you want to use, and then click Close.


 Start the Expression Builder in a property sheet or the Macro window

Start the Expression Builder in a property sheet or the Macro window

  1. Click the property or argument box that will contain the expression.

  2. Click the Build button [image] next to the property or argument box.

    If a property has more than one builder associated with it, Microsoft Access displays the Choose Builder dialog box. Click Expression Builder and click OK.

Note If the property box or argument box where you start the Expression Builder already contains a value, that value is automatically copied into the expression box.


 Start the Expression Builder in the query design grid or a macro condition

Start the Expression Builder in the query design grid or a macro condition

You can start the Expression Builder in a Field or Criteria cell in query Design view or in the Condition column of the Macro window.

  1. Right-click where you want to insert the expression.

  2. On the shortcut menu, click Build.

Note If the cell or Condition column where you start the Expression Builder already contains a value, that value is automatically copied into the expression box.


 Start Microsoft Access with command-line options from the Windows Start menu

Start Microsoft Access with command-line options from the Windows Start menu

  1. Click the Windows Start button, point to Settings, and then click Taskbar.

  2. Click the Start Menu Programs tab, and then click Advanced.

  3. Double-click the Programs folder.

  4. Double-click the Microsoft Office folder (or the name of the Programs subfolder where Microsoft Access is installed). If Microsoft Access is not installed in a Start menu subfolder, you can skip this step.

  5. Right-click the Microsoft Access program shortcut icon, click Properties, and then click the Shortcut tab.

  6. Click to the right of the Microsoft Access startup command in the Target box, and then type the desired command-line options.

    For example, the following command line starts Microsoft Access and opens the Northwind sample database for exclusive access.

"C:\Program Files\Microsoft Office\Office\MSAccess.exe" "C:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb" /excl

To display the list of command-line options, click [image] .


 Start Microsoft Access with command-line options using a shortcut

Start Microsoft Access with command-line options using a shortcut

  1. Open the folder where Microsoft Access is installed (typically the folder will be named Office in the Microsoft Office subfolder of the Program Files folder on your C drive).

  2. Right-click the Microsoft Access program icon, and then click Create Shortcut.

  3. Right-click the shortcut icon just created, click Properties, and then click the Shortcut tab.

  4. Click to the right of the Microsoft Access startup command in the Target box, and then type the desired command-line options.

    For example, the following command line starts Microsoft Access, opens the Northwind sample database for exclusive access.

"C:\Program Files\Microsoft Office\Office\MSAccess.exe" "C:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb" /excl

To display the list of command-line options, click [image] .

Note After you create a shortcut you can put it on your desktop or in a folder, or add it to the Start menu. Search Windows Help for "shortcuts" for more information.

You can also create a shortcut to open any Microsoft Access database object directly from Windows.

For more information, click [image] .


 Step through Visual Basic code

Step through Visual Basic code

Stepping through your Visual Basic code can help you identify where an error is occurring. You can see whether each line of code produces the results you expect.

  1. Suspend execution of the code.

    How?

    Microsoft Access displays the line of code where execution is suspended.

  2. Do one of the following:
    • To step through each line of code and into the code in a procedure called by another procedure, click Step Into [image] on the Debug toolbar.

    • To step through each line of code but run as a unit any procedure that is called, click Step Over [image] on the Debug toolbar.

    • To run the code that precedes the current line of code, and then break so you can step through each line of code, click Run To Cursor on the Debug menu.

    • To run the rest of the current procedure, and then return to the next line of code in the preceding procedure in the call tree, click Step Out [image] on the toolbar.

Note You can use Step Into [image] without suspending code execution. In the Visual Basic Editor Code window, place your cursor in the procedure you want to step through, and click Step Into [image] on the toolbar.

You can alternate between these types of stepping. The type of stepping you do depends on which portions of code you want to analyze.


 Use a breakpoint to suspend running of Visual Basic code

Use a breakpoint to suspend running of Visual Basic code

When you suspend execution of Visual Basic code, the code is still running but is paused between running statements. While running of your code is suspended, you can do debugging tasks such as check current variable values and run each line of code one at a time. To make Microsoft Visual Basic pause running your code, you can set a breakpoint.

  1. In the Visual Basic Editor Code window, move the insertion point to a line of code that isn't already a breakpoint, or declaration.

  2. Click Toggle Breakpoint [image] on the Debug toolbar.

To clear a breakpoint, move the insertion point to the line of code on which the breakpoint has been set, and then click Toggle Breakpoint [image] on the Debug toolbar. To resume running the code, click Run Sub/UserForm on the Run menu.

Note You can also cause code execution to be suspended by adding a Stop statement to a procedure or by pressing CTRL+BREAK while the code is running.


 Switch between views of a query

Switch between views of a query

A query has three views: Design view, Datasheet view, and SQL view.

  1. Click the arrow next to the View [image] on the toolbar.

  2. In the drop-down list, click the view that you want.


 Trace Visual Basic procedure calls while debugging Visual Basic code

Trace Visual Basic procedure calls while debugging Visual Basic code

When you suspend execution of Visual Basic code while debugging the code, you can use the Calls dialog box to view a list of procedures that have been started but not completed.

  1. Suspend execution of your Visual Basic code.

    How?

  2. Click Call Stack [image] on the Debug toolbar.

Microsoft Access displays the most recently called procedure at the top of the list, followed by the next most recent procedure call, and so on. To display the statement that calls the next procedure in the list, click Show.


 Turn confirmation messages on or off

Turn confirmation messages on or off

You can turn confirmation messages on or off for record changes, document deletions, or, in Microsoft Access databases, action queries.

  1. On the Tools menu, click Options.

  2. Click the Edit/Find tab.

  3. Under Confirm, select or clear the appropriate check boxes.

Note These settings don't apply to data access pages.


 Update a manual link to a picture or other object on a form or report

Update a manual link to a picture or other object on a form or report

This type of link is different from a hyperlink that is used on a form or report to jump to another document, object, or page. For more information on hyperlinks, click [image] .

  1. Do one of the following:
    • If the object is unbound, click the object in form or report Design view.

    • If the object is bound, open the form in Form view (or open a datasheet), find the record you want to change, and click the object.
  2. On the Edit menu, click OLE/DDE Links.

  3. In the Links box, click the link you want to update. To select multiple links, hold down the CTRL key while you click each link.

  4. Click Update Now.

Note This procedure only applies to pictures in unbound object frames and bound object frames. Background pictures and pictures in image controls are always updated automatically.


 Update a table based on values in another table by using a query

Update a table based on values in another table by using a query

  1. Create an update query that contains the table you want to update and the table whose values you want to copy. For information about how to create an update query, click [image] .

  2. If the tables aren't already joined, join them on the fields that have related information. For information on creating joins, click [image] .

    For example, if you want to copy data from the ProductName field in the Products table to a field in another table, join the two tables on the primary key, which might be called ProductID.

  3. In the Update To cell for the fields you want to update, type an expression with the following syntax:

    [tablename].[fieldname]

    where tablename and fieldname are the names of the table and field that contain the data you're copying. For example, if you are copying data from the ProductName field in the Products table, you would type [Products].[ProductName] in the Update To cell.


 Ungroup text boxes or other controls on a form or report

Ungroup text boxes or other controls on a form or report

  1. Open a form in Design view or a report in Design view.

  2. Click any control in the group to select the group.

  3. On the Format menu, click Ungroup.

Notes

  • You can only ungroup controls when a single group is selected.

  • When you ungroup controls, the group rectangle is deleted and all controls are automatically selected.


 Group records on an expression on a data access page

Group records on an expression on a data access page

  1. Open the data access page in Design view.

  2. Create a grouped data access page.

  3. If the expression will reference field names, either add the fields to the page as bound HTML controls, or add the fields as bound text boxes.

    Tip The page will load faster in Page view and in Microsoft Internet Explorer if you use bound HTML controls.

  4. Add a bound HTML control for the expression by clicking Bound HTML Bound HTML control on the toolbox and then clicking in the section where you want the control.

  5. Make sure the control is selected, and then click Properties [image] on the toolbar to display the property sheet.

  6. Type an alias for the expression followed by a colon and the expression you want in the ControlSource property box. In this example, FullName is the alias for the expression:

    FullName: FirstName & " " & LastName

  7. With the bound HTML control still selected, click Promote [image] on the toolbar.

    Microsoft Access adds a group header that contains an expand control, and a record navigation section that contains a record navigation control. Access moves the control you grouped on to the group header.

Notes

  • Any field you reference in an expression must be added to the data definition of the page; The field is automatically added to the data definition when you create a control bound to that field. If you don't want to display the values in those controls in Page view or in Microsoft Internet Explorer, you can either hide the controls or delete the controls. Even if you delete a control bound to a field used in an expression on the page, it won't be deleted from the page's data definition.

  • When you group on a control, Access creates an alias for the control by adding the prefix "GroupOf" to the control's name in the ControlSource property; for example, GroupOfFullName: FullName. When you reference this control in an expression or in a property, you must use the alias.


 Use a front-end/back-end application with several versions of Microsoft Access

Use a front-end/back-end application with several versions of Microsoft Access

If your Microsoft Access database is already a front-end/back-end application, you only need to convert the front end to Microsoft Access 2000.

  1. Leave the back-end database alone.

  2. Convert the front-end database to Microsoft Access 2000.

  3. Run the Linked Table Manager (Tools menu, Database Utilities command) to link the new Microsoft Access 2000 front-end database to the tables in the previous-version back-end database. You can then enhance the Microsoft Access 2000 front-end database to support new features, for users that have upgraded to Microsoft Access 2000.


 Create a hyperlink to an existing file or Web page by using the Insert Hyperlink button

Create a hyperlink to an existing file or Web page by using the Insert Hyperlink button

  1. Open a form in Design view, a report in Design view, or a data access page in Design view.

  2. On the Insert menu, click Hyperlink.

  3. In the Insert Hyperlink dialog box, click Existing file or Web page under Link to.

  4. In the Text to display box, type the display text for the hyperlink. If you leave it blank, Microsoft Access uses the hyperlink address and/or subaddress as the display text.

  5. Click ScreenTip, and type the text you want to appear when the mouse pointer hovers over the hyperlink. If you leave the ScreenTip text box blank, then Microsoft Access will display the hyperlink address and/or subaddress as the ScreenTip.

  6. Specify the file or Web page that you want to link to in one of these ways:
    • In the Type the file or Web page name box, type a path or a URL.

    • Under Or select from list, click Recent files, Browsed pages, or Inserted links. Then click an item in the list.

    • Click File to search for a file on your local machine, a network, or any accessible ftp or http server.

    • Click Web page to search for a page on the Internet or an intranet. When you switch from Microsoft Internet Explorer or other Web browsers to Microsoft Access, Access puts the title and the URL of the currently open Web page in the Text to display and Type the file or Web page name boxes.
  7. To go to a specific location in an HTML file or to an object in a Microsoft Access database (.mdb) or a Microsoft Access project (.adp), click Bookmark. Click the bookmark or object you want in the list, and then click OK.

  8. Click OK in the Insert Hyperlink box.

    On a data access page, Microsoft Access adds the hyperlink in a hyperlink control. In a form or report, it adds the hyperlink in a label. To test the link on a data access page, switch to Page view and click the hyperlink. To test the link on a form or report, right-click the label, point to Hyperlink on the shortcut menu, and then click Open.


 Create the ODBC connection string for an SQL pass-through query

Create the ODBC connection string for an SQL pass-through query

  1. Open a pass-through query.

  2. Click Properties [image] on the toolbar to display the query property sheet.

  3. In the query property sheet, click Build [image] to the right of the ODBCConnectStr property box, and then enter information about the server you are connecting to.

  4. When you are prompted to save the password in the connection string, select Yes if you want the password and logon stored in the connection string information.

Note The default ODBC connection string is "ODBC;". After the builder creates the ODBC connection string, it enters the new string into the ODBCConnectStr property in the query property sheet.


 Use a one-file Access database with several versions of Microsoft Access

Use a one-file Access database with several versions of Microsoft Access

To use a Microsoft Access database that is one file in several versions of Microsoft Access, convert it to a front-end/back-end application. The data remains in the oldest version of Access, and you use a front end that has been converted to Access 2000.

  1. Convert the Access database to Microsoft Access 2000, specifying a new name.

  2. Use the Database Splitter Wizard to split the converted database into a front-end/back-end application.

  3. Delete the back-end database that the Database Splitter Wizard created. You want your data to remain in the original database, so you are going to be using the original database as the back-end database. The back-end database should be in the oldest version of Microsoft Access that is being used.

  4. Run the Linked Table Manager (Tools menu, Database Utilities command) to link the new Microsoft Access 2000 front-end database to the tables in the previous-version database. You can then enhance the Microsoft Access 2000 front-end database to support new features, for users that have upgraded to Microsoft Access 2000. Users of previous versions can continue to use the previous-version database. For example, if the back-end tables are in Microsoft Access version 2.0 format, you can use up to four versions of Microsoft Access: Microsoft Access version 2.0 (using the original database), Microsoft Access 95 and 97 (using an enabled version of the original database or a converted front-end database), and Microsoft Access 2000 (using a converted front-end database).


 Use the Registry Editor

Use the Registry Editor

Caution Many Microsoft Access registry settings are added automatically when you install Microsoft Access. Changing the installed settings can produce unexpected results, which may make it necessary to reinstall Microsoft Access. It is strongly recommended that you not change settings in the Windows registry. However, if you must change registry settings or options, use the Windows Registry Editor, and change only those settings or options that are explicitly documented. The revised settings take effect the next time you start Microsoft Access. It is recommended that you back up all of the registry, or at least the part you will be editing. For information, look up "backing up the registry" in the index of the Registry Editor Help (available on the menu bar of the Registry Editor).

  1. To run the Registry Editor, click the Windows Start button, click Run, type regedit, and then click OK.

  2. Navigate to the appropriate registry subkey. The two main subkeys that contain settings that affect Microsoft Access are:
    • \HKEY_LOCAL_MACHINE\SOFTWARE
      \Microsoft\Office\9.0\Access

    • \HKEY_LOCAL_MACHINE\SOFTWARE
      \Microsoft\Jet\4.0

    If there is a plus (+) to the left of the subkey, that registry subkey contains additional subkeys. To edit a registry subkey's value(s), double-click the subkey in the left pane of the Registry Editor window to open it, and then double-click the value you want to edit in the right pane of the Registry Editor window. In some cases, you may need to add new subkeys or values. For information on how to add new subkeys and values, use the Registry Editor Help.

Important The subkeys displayed below the \Microsoft\Office\9.0\Access subkey apply only to Microsoft Access 2000. The subkeys that are displayed below the \Microsoft\Jet\4.0 subkey apply to the Microsoft Jet database engine that Microsoft Access uses for data access. Changes to these settings affect Microsoft Access 2000 and will affect other programs that use the Microsoft Jet database engine, such as Microsoft Excel 2000, Microsoft Visual Basic 6.0 or later, and possibly others. To make changes to Microsoft Jet database engine settings that affect only Microsoft Access, change the settings in the \HKEY_LOCAL_MACHINE\SOFTWARE
\Microsoft\Office\9.0\Access\Jet\4.0 subkey.


 Use a wizard to create a PivotTable form

Use a wizard to create a PivotTable form

  1. In the Database window, click Forms [image] under Objects.

  2. Click the New button on the Database window toolbar.

  3. In the New Form dialog box, click PivotTable Wizard, and then click OK.

  4. Follow the instructions in the wizard.

    For more information on PivotTable forms and how they work, click [image] .

Notes

  • The Sales Analysis form in the Northwind sample database has an example of a PivotTable form. To view this PivotTable form, open the Northwind database in your Office folder's Samples subfolder, and then open the Sales Analysis form in Design view.

  • The source data that the PivotTable form uses isn't automatically saved with the PivotTable form. Instead, you must update the PivotTable form with the most current data each time you want to use it, which means you'll need access to the location where the data is stored. If you know that you'll need to edit the PivotTable form later on when you won't have access to the data, save a copy of the data with the PivotTable form. For more information, click [image] .

  • When you're editing the PivotTable form, you are using Microsoft Excel and can get Microsoft Excel Help on PivotTable reports. When you're in Form view, you can get Microsoft Access Help on PivotTable forms.


 Using the Microsoft Office Assistant in Microsoft Access

Using the Microsoft Office Assistant in Microsoft Access

To use Microsoft Office objects, including the Office Assistant, from Microsoft Access, you must first set a reference to the Microsoft Office object library. Click References on the Tools menu while in module Design view and select the check box next to Microsoft Office 9.0 Object Library.

If you fail to set this reference, you'll get a compile-time error, "User-defined type not defined", when you try to use objects in the Microsoft Office object library.

Note The Office Assistant isn't available in the run-time version of Microsoft Access.


 Using Command Bars

Using Command Bars

In Microsoft Access 2000, you use the Customize dialog box, available by pointing to Toolbars on the View menu and clicking Customize, to make design-time changes to command bars. You can use this dialog box to add and modify menu bars, toolbars, and shortcut menus, and to add any of the built-in menu items or toolbar buttons to one of these types of command bars. However, you can only add custom command buttons or menu items to a command bar by using this dialog box. To add custom edit boxes, drop-down list boxes, or combo boxes to a command bar, you must use Visual Basic.


 Using the Microsoft Office Command Bars Object Model in Microsoft Access

Using the Microsoft Office Command Bars Object Model in Microsoft Access

In order to program with command bars in Microsoft Access 2000, you must first set a reference to the Microsoft Office object library. Click References on the Tools menu while in module Design view, and select the check box next to Microsoft Office 9.0 Object Library.


 Validate data by using a macro

Validate data by using a macro

  1. Create a macro.

    How?

  2. In the Macro window, make sure Conditions [image] on the toolbar is pressed in.

  3. In the Condition column of a blank action row, enter a validation condition.

  4. In the Action column, click the action in the action list that you want to carry out if the validation condition is true.

  5. For any additional actions you want to carry out if the validation condition is true, enter an ellipsis (...) in the Condition column followed by the action in the Action column. For example, it's usually a good idea to carry out a CancelEvent action for each validation condition after any other actions have been carried out.

  6. Click Save [image] to save the macro.

  7. Open the form in Design view.

  8. For the event that you want to trigger the validation, set the event property to the name of the macro. For example, to trigger the validation when a control is updated with changed data, set the BeforeUpdate event property of the control to the name of the macro.

    Tip To validate data before a record as a whole is updated, attach the validation macro to the form's BeforeUpdate event rather than to the control's BeforeUpdate event.

For an example of validating data by using a macro, click [image] .

For information about the events used for data validation, click [image] .

For information about the order of validation for controls and fields, click [image] .


 Validate data by using an event procedure

Validate data by using an event procedure

  1. Open the form in Design view.

  2. Create the event procedure for the event that you want to trigger the validation.

    How?

    For example, to trigger the validation rule when a control is updated with changed data, create an event procedure for the control's BeforeUpdate event.

  3. Add Visual Basic for Applications code to the event procedure, specifying the validation condition and the operations to perform when those conditions are met.

Tips

  • It's usually a good idea to cancel the event that triggers the validation after the operations have been performed. You can cancel many events by setting the event procedure's Cancel argument to True.

  • To validate data before the record as a whole is updated, add code to the BeforeUpdate event procedure for the form, rather than the control.

For an example of validating data by using an event procedure, click [image] .

For information about the events used for data validation, click [image] .

For information about the order of validation for controls and fields, click [image] .


View the attributes of a database file

  1. With the database open, click Database Properties on the File menu.

  2. Click the General tab.


 View a list of database objects in the current Access database or Access project

View a list of database objects in the current Access database or Access project

  1. With the Microsoft Access database or Microsoft Access project open, click Database Properties on the File menu.

  2. Click the Contents tab.


 View the results of a make-table, append, or delete query

View the results of a make-table, append, or delete query

  1. Click Database Window [image] on the toolbar.

  2. In the Database window, click Tables [image] under Objects.

  3. Click the table you created or changed, and then click Open on the Database window toolbar.


 View the results of a select or crosstab query

View the results of a select or crosstab query

Microsoft Access displays the results of a select or crosstab query in a datasheet. You can display the datasheet from query Design view or by clicking Open on the Database window toolbar.

From | Do this
Query Design view | Click View [image] on the toolbar.
Database window | Click Queries [image] under Objects, and then double-click the query name, or select the query and then click Open on the Database window toolbar.

To stop the query, press CTRL+BREAK. (This procedure may not work for very large queries, however.)


 View the results of an update query

View the results of an update query

  1. In query Design view, click the arrow next to Query Type [image] on the toolbar, and then click Select Query.

  2. Click View [image] on the toolbar.


Why can't I customize the toolbar?

If you are unable to customize a toolbar, make sure that the Allow Customizing check box in the Toolbar Properties dialog box is selected. How to allow customizing of a toolbar.

If the Toolbars command on the View menu is disabled, you might need to change the settings in the Startup dialog box or temporarily bypass its settings.

To change the settings

On the Tools menu, click Startup, and select the Allow Toolbar/Menu Changes check box. Close the database, and then reopen it.

To temporarily bypass the settings in the Startup dialog box

You can temporarily bypass all the settings specified in the Startup dialog box instead of resetting the options. Hold down the Bypass key (the SHIFT key) while you open the database.


Why can't I show or hide a toolbar, menu bar, or shortcut menu?

If you are unable to show or hide a toolbar, menu bar, or shortcut menu, make sure that the Allow Showing/Hiding check box in the Toolbar Properties dialog box is selected. How to allow showing or hiding of a toolbar, menu bar, or shortcut menu.


Why is my toolbar cut off?

Some buttons may not appear on the toolbar because there is not enough room to display them. Click More Buttons [image] at the end of the toolbar to see a list of additional buttons.

There may not be enough room to display all of the buttons because the toolbar is on the same row as another toolbar. To see more buttons, you can resize the toolbar or move the toolbar to its own row or to another location.


 Create an event procedure

Create an event procedure

Microsoft Access makes it easy to run code in response to an action performed by the user. When you set an event property for a form, report, or control to [Event Procedure], Microsoft Access creates the event procedure template for you. All you have to do is add the code you want to run in response to a particular event on the form, report, or control. For example, you can have code run when a user clicks a command button or changes data.

  1. Open a form or report in form or report Design view.

  2. Display the property sheet for the form, report, or a section or control on the form or report.

  3. Click the Event tab.

  4. Click the event property for the event that you want to trigger the procedure. For example, to display the event procedure for the Change event, click the OnChange property.

  5. Click Build [image] next to the property box to display the Choose Builder dialog box.

  6. Double-click Code Builder to display the event procedure Sub and End Sub statements in the form module or report module. These statements define, or declare, the event procedure.

    Microsoft Access automatically declares event procedures for each object and event in a form or report module by using the Private keyword to indicate that the procedure can be accessed only by other procedures in that module.

  7. Add the code to the event procedure that you want to run when the event occurs. For example, to produce a sound through the computer's speaker when data in the CompanyName text box changes, add a Beep statement to the CompanyName_Change event procedure, as follows:
    Private Sub CompanyName_Change()

    Beep

End Sub

    The event procedure runs each time the Change event occurs for the object.


 Create a custom Sub procedure

Create a custom Sub procedure

  1. Open a new module.
    • To open a new standard module, in the Database window, click Modules [image] under Objects, and then click New on the Database window toolbar. To open an existing standard module, click Modules [image] under Objects, select the module you want to open, and then click Design.

    • To open a form module or report module, open the form or report in Design view, and then click Code [image] on the toolbar.

    • To open a new class module that isn't associated with a form or report, in the Database window click Class Module on the Insert menu. To open an existing class module, in the Database window, click Modules [image], select the module you want to open, and then click Design on the Database window toolbar.
  2. Declare the procedure by typing the Sub statement.

  3. Type a procedure name, immediately followed by any arguments in parentheses. For example, the following declaration for the ShowEvent Sub procedure specifies (EventName As String) as an argument:
    Sub ShowEvent(EventName As String)

  4. Add the Visual Basic code that performs the operation that you want the procedure to perform.

For more information on the Sub statement, click [image] . For more information on writing Sub procedures, click [image] .


 Create a custom function

Create a custom function

  1. Open a new module.
    • To open a new standard module, in the Database window, click Modules [image] under Objects, and then click the New button on the Database window toolbar. To open an existing standard module, click Modules [image] under Objects, select the module you want to open, and then click Design.

    • To open a form module or report module, open the form or report in Design view, and then click Code [image] on the toolbar.

    • To open a new class module that isn't associated with a form or report, in the Database window click Class Module on the Insert menu. To open an existing class module, in the Database window, click Modules [image] under Objects, select the module you want to open, and then click the Design button on the Database window toolbar.
  2. Declare the function by typing the Function statement.

  3. Type a function name immediately followed by any function arguments in parentheses. For example, the following declaration for the IsLoaded function specifies strFormName as an argument:
    Function IsLoaded(strFormName As String) As Boolean

  4. Add the Visual Basic code that performs the operation or calculation that you want the function to perform.

For more information on the Function statement, click [image] .


 SQL Aggregate Functions

SQL Aggregate Functions

The SQL aggregate functions are similar to the domain aggregate functions, but they are used in different contexts. In Microsoft Access, you can use the SQL aggregate functions in an SQL statement that you create in SQL view of the Query window, or in an SQL statement within Visual Basic code. Conversely, domain aggregate functions can be called directly from Visual Basic code.

You can use both SQL aggregate and domain aggregate functions in query expressions in the query design grid. SQL aggregate functions are most useful in totals queries and crosstab queries.

You can also use both types of aggregate functions in a calculated control on a form or report.


Data Events

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

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


Error and Timing Events

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

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


Filter Events

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

Event Event property It occurs
ApplyFilter OnApplyFilter (forms) When you click Apply Filter on the Records menu, or click the Apply Filter or Apply Server Filter button on the command bar. This applies the most recently created filter (created using the Filter by Form feature, Server Filter by Form feature or the Advanced Filter/Sort window).

When you click Filter By Selection or Server Filter By Form after pointing to Filter on the Records menu, or click the Filter By Selection button on the command bar. This applies a filter based on the current selection in the form.

When you click Remove Filter/Sort on the Records menu, or click the Remove Filter button on the command bar. This removes any filter (or sort) currently applied to the form.

When you close the Advanced Filter/Sort window or the Filter by Form window.
Filter OnFilter (forms) When you click Filter By Form or Server Filter By Form after pointing to Filter on the Records menu, or click the Filter By Form or Server Filter By Form button on the command bar. This opens the Filter by Form window, where you can quickly create a filter based on the fields in the form.

When you click Advanced Filter/Sort after pointing to Filter on the Records menu. This opens the Advanced Filter/Sort window, where you can create complex filters for the form.


Focus Events

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

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


Keyboard Events

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

Event Event property It occurs
KeyDown OnKeyDown (forms, controls) When you press any key on the keyboard while a control or form has the focus. A form can have the focus only if all visible controls on the form are disabled, or there are no controls on the form.

The KeyDown event also occurs if you send a keystroke to a form or control using the SendKeys action in a macro or the SendKeys statement in Visual Basic.

A form also receives all KeyDown events (even those for controls) before they occur for the controls if you set the form's KeyPreview property to Yes.

If you hold down a key, the KeyDown event occurs repeatedly.
KeyPress OnKeyPress (forms, controls) When you press and release a key or key combination that produces a standard ANSI character while a control or form has the focus. A form can have the focus only if all visible controls on the form are disabled, or there are no controls on the form.

For example, you can use the KeyPress event to respond to keystrokes entered in a text box or combo box. For keystrokes not recognized by KeyPress, such as function keys or navigation keys, use the KeyDown and KeyUp events.

The KeyPress event also occurs if you send a keystroke that produces a standard ANSI character to a form or control using the SendKeys action in a macro or the SendKeys statement in Visual Basic.

A form also receives all KeyPress events (even those for controls) before they occur for the controls if you set the form's KeyPreview property to Yes.

If you hold down a key, the KeyPress event occurs repeatedly.
KeyUp OnKeyUp (forms, controls) When you release a pressed key while a control or form has the focus. The object with the focus receives all the keystrokes. A form can have the focus only if all visible controls on the form are disabled, or there are no controls on the form.

The KeyUp event also occurs if you send a keystroke to a form or control using the SendKeys action in a macro or the SendKeys statement in Visual Basic.

A form also receives all KeyUp events (even those for controls) before they occur for the controls if you set the form's KeyPreview property to Yes.

If you hold down a key, the KeyUp event occurs after all the KeyDown and KeyPress events have occurred.


 Mouse Events

Mouse Events

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

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


Print Events

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

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


Window Events

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

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


Keys for sending e-mail messages

Press | To
ALT+F+D+A | Send the active database object as an e-mail message Learn about sending a database object's output as an attachment to an e-mail message or a data access page as the body of an e-mail message.
CTRL+SHIFT+B | Open the Address Book
ALT+K | Check the names in the To, Cc, and Bcc boxes against the Address Book
TAB | Select the next box in the e-mail header or the body of the message when the last box in the e-mail header is active
SHIFT+TAB | Select the previous field or button in the e-mail header


 Keys for working with Help

Keys for working with Help

If Help is not open, press F1. If you use the Office Assistant to find Help topics, you can use keys to select Help topics.

This topic provides reference information about:

Working in the Help window

Moving around in the navigation pane

Moving around in the topic pane

Work in the Help window

Press | To
F6 | Move between the navigation pane and topic pane
ALT+O | Display the Options menu to access any Help toolbar command
ALT+SPACEBAR | Display the program Control menu
ALT+F4 | Close the active Help window

Return to top

Move around in the navigation pane

Press | To
CTRL+TAB | Switch to the next tab
CTRL+SHIFT+TAB | Switch to the previous tab
ALT+C | Switch to the Contents tab
ALT+A | Switch to the Answer Wizard tab
ALT+I | Switch to the Index tab
ENTER | Open or close a selected book, or open a selected Help topic
DOWN ARROW | Select the next book or Help topic
UP ARROW | Select the previous book or Help topic

Return to top

Move around in the topic pane

Press | To
ALT+LEFT ARROW | Go back to a Help topic you viewed previously
ALT+RIGHT ARROW | Go forward to a Help topic you viewed previously
TAB | Go to the first or next hyperlink
SHIFT+TAB | Go to the last or previous hyperlink
ENTER | Activate a selected hyperlink
ESC | Close a pop-up window
UP ARROW | Scroll toward the beginning of a Help topic
DOWN ARROW | Scroll toward the end of a Help topic
PAGE UP | Scroll toward the beginning of a Help topic in larger increments
PAGE DOWN | Scroll toward the end of a Help topic in larger increments
HOME | Move to the beginning of a Help topic
END | Move to the end of a Help topic
CTRL+P | Print the active Help topic
CTRL+A | Select the entire Help topic
CTRL+C | Copy the selected items to the Clipboard

Return to top


Use shortcut keys in data access page Design view

Press | Editing controls
SHIFT+ENTER | To add a control to a section How to place a text box or another control on a data access page by using the keyboard.
CTRL+C | To copy the selected control to the Clipboard
CTRL+X | To cut the selected control and copy it to the Clipboard
CTRL+V | To paste the contents of the Clipboard in the upper-left corner of the selected section
CTRL+RIGHT ARROW | To move the selected control to the right by a pixel (irrespective of the page’s grid)
CTRL+LEFT ARROW | To move the selected control to the left by a pixel (irrespective of the page’s grid)
CTRL+UP ARROW | To move the selected control up by a pixel (irrespective of the page’s grid)
CTRL+DOWN ARROW | To move the selected control down by a pixel (irrespective of the page’s grid)

Press | Adding tables and fields
ALT+A and ENTER | From the field list to add tables and fields to the page


 Use shortcut keys to navigate in subdatasheets

Use shortcut keys to navigate in subdatasheets

Press | Going to a specific record
F5 | From the subdatasheet to move to the record number box; then type the record number and press ENTER

Press | Expanding and collapsing subdatasheet
CTRL+SHIFT+DOWN ARROW | From the datasheet to expand the record’s subdatasheet
CTRL+SHIFT+UP ARROW | To collapse the subdatasheet

Press | Navigating between the datasheet and subdatasheet
TAB | To enter the subdatasheet from the last field of the previous record in the datasheet
SHIFT+TAB | To enter the subdatasheet from the first field of the following record in the datasheet
CTRL+TAB | To exit the subdatasheet and move to the first field of the next record in the datasheet
CTRL+SHIFT+TAB | To exit the subdatasheet and move to the last field of the previous record in the datasheet
TAB | From the last field in the subdatasheet to enter the next field in the datasheet
DOWN ARROW | From the datasheet to bypass the subdatasheet and move to the next record in the datasheet
UP ARROW | From the datasheet to bypass the subdatasheet and move to the previous record in the datasheet

Note You can navigate between fields and records in a subdatasheet with the same shortcut keys used in Datasheet view.

Learn more about using the keyboard to rearrange columns.

Learn more about selecting fields and records in Datasheet view.


Databases: What they are and how they work 1

A database is a collection of information that's related to a particular subject or purpose, such as tracking customer orders or maintaining a music collection. If your database isn't stored on a computer, or only parts of it are, you may be tracking information from a variety of sources that you're having to coordinate and organize yourself.

Storing data on paper, not on a computer


Databases: What they are and how they work 2

Using Microsoft Access, you can manage all your information from a single database file. Within the file, divide your data into separate storage containers called tables; view, add, and update table data by using online forms; find and retrieve just the data you want by using queries; and analyze or print data in a specific layout by using reports. Allow users to view, update, or analyze the database's data from the Internet or an intranet by creating data access pages.

A form, report, query, and data access page displaying data from the same table


Databases: What they are and how they work 3

To store your data, create one table for each type of information that you track. To bring the data from multiple tables together in a query, form, report, or data access page, define relationships between the tables.

Two tables, each with a Customer ID field that relates them


Databases: What they are and how they work 4

To find and retrieve just the data that meets conditions that you specify, including data from multiple tables, create a query. A query can also update or delete multiple records at the same time, and perform predefined or custom calculations on your data.

A query with fields from two tables


Databases: What they are and how they work 5

To easily view, enter, and change data directly in a table, create a form. When you open a form, Microsoft Access retrieves the data from one or more tables, and displays it on the screen with the layout you choose in the Form Wizard, or a layout that you create from scratch.

A form displaying one record of information and a Print Invoice button


Databases: What they are and how they work 6

To analyze your data or present it a certain way in print, create a report. For example, you might print one report that groups data and calculates totals, and another report with different data formatted for printing mailing labels.

Reports that total, display charts, or generate mailing labels


Databases: What they are and how they work 7

To make data available on the Internet or an intranet for interactive reporting, data entry, or data analysis, use a data access page. Microsoft Access retrieves the data from one or more tables and displays it on the screen with the layout you choose in the Page Wizard, or a layout that you create from scratch. Users can interact with the data by using features on the data access page.

Grouped data access page with expand buttons and record navigation toolbars


Databases: What they are and how they work 8

The Database window

More information

Tables: What they are and how they work

Queries: What they are and how they work

Forms: What they are and how they work

Reports: What they are and how they work

Data access pages: What they are and how they work


 Display a combo box from a table as a text box in a query

Display a combo box from a table as a text box in a query

Changing how the field displays in the query doesn't affect how the field displays in the underlying table.

  1. Open the query in Design view.

  2. In the query design grid, right-click anywhere in the column of the field you want to change, and then click Properties on the shortcut menu.

  3. Click the Lookup tab.

  4. In the DisplayControl property box, click Text Box.


Example of a crosstab query

1 2


Example of a crosstab query 1

Crosstab queries calculate a sum, average, count, or other type of total for data that is grouped by two types of information — one down the left side of the datasheet and another across the top.

Comparison of a crosstab and a select query


Example of a crosstab query 2

You create a crosstab query with a wizard or from scratch in the query design grid. In the design grid, you specify which field's values will become column headings, which field's values will become row headings, and which field's values to sum, average, count, or otherwise calculate.

Example of how to fill in the query design grid for a crosstab query

More information

Create a crosstab query by using a wizard

Create a crosstab query without using a wizard


Example of grouped records in a report 1

Comparison of reports with grouped and ungrouped records


Example of grouped records in a report 2

Setting group header and footer properties in the Sorting and Grouping box


Example of grouped records in a report 3

A header on a group level is paired with a footer on the same level

More information

Sort records in a report

Group records in a report

Change sorting or grouping order in a report

Delete a sorting or grouping field or expression in a report


Forms: What they are and how they work 1

You can use forms for a variety of purposes.

Data entry form, switchboard form, and dialog box


Forms: What they are and how they work 2

Most of the information in a form comes from an underlying record source. Other information in the form is stored in the form's design.

Types of information displayed on a form: text, data, calculations, and graphics


Forms: What they are and how they work 3

You create the link between a form and its record source by using graphical objects called controls. The most common type of control used to display and enter data is a text box.

The relationship between a form and its underlying record source

More information

Create a form

Create a pop-up form or custom dialog box

Create and manage a switchboard form


About the Table Analyzer Wizard's query 1

The Table Analyzer Wizard divides one table that contains duplicate information into separate tables in which each type of information is stored only once. This makes the database more efficient and easier to update, and reduces its size. After the wizard divides the data, you can still view and work with the data in one place by having the wizard create a query.

Two tables created from one table and the query that brings their data back together


About the Table Analyzer Wizard's query 2

You can use the query to update data from more than one table at the same time. The query also offers other timesaving features to increase the accuracy of your data.

Automatic updates in a query, and in forms, reports, and data access pages based on the query


About the Table Analyzer Wizard's query 3

From the new tables, the query inherits Lookup fields, which let you change field values by picking values from a list instead of having to correctly type a value.

Lookup lists in a query


About the Table Analyzer Wizard's query 4

Forms and reports that were previously based on the original table will automatically be based on the query now, because the wizard assigns the original table's name to the query and renames the table. For a data access page that is based on the original table, you have to manually change its RecordSource property setting from the table name to the query name.

Form with a lookup list inherited from the query


Join types and how they affect query results 1

A join line between tables or queries in a query shows Microsoft Access how the data is related. The type of join indicates which records the query selects or performs an action on.

Join line and how it affects query results


Join types and how they affect query results 2

Microsoft Access automatically creates join lines between tables whose relationship (association between common fields) was previously defined. If relationships weren't previously defined, you can create the join line yourself by dragging a field from one table to the equivalent field in the other table.

Join line between field lists in a query


Join types and how they affect query results 3

The default join type selects only those records from the joined tables or queries that have the same values in the joined fields. When the values are the same, the query combines the two matching records and displays them as one record in the query's results.

Query results from an inner join


Join types and how they affect query results 4

Join Properties dialog box for changing join types


Join types and how they affect query results 5

Query results from an outer join

More information

Change the type of join between tables and queries in a query

Join multiple tables and queries in a query

Ways to bring together data from multiple tables or queries in a query


Queries: What they are and how they work 1

You use queries to view, change, and analyze data in different ways. You can also use them as the source of records for forms, reports, and data access pages.

Multiple-table query, crosstab query, and query that performs calculations


Queries: What they are and how they work 2

The most common type of query is a select query. A select query retrieves data from one or more tables by using criteria you specify and then displays it in the order you want.

How queries retrieve and display data from tables


Queries: What they are and how they work 3

How a query looks in Design view and Datasheet view

More information

Create a query


Reports: What they are and how they work 1

A report is an effective way to present your data in a printed format. Because you have control over the size and appearance of everything on a report, you can display the information the way you want to see it.

Mailing labels, report with grouped records, and report with chart


 Reports: What they are and how they work 2

Most of the information in a report comes from an underlying table, query, or SQL statement, which is the source of the report's data. Other information in the report is stored in the report's design.

The types of information displayed on a report: text, data, and expressions


Reports: What they are and how they work 3

The relationship between a report and its underlying record source

More information

Create a report

Create mailing and other types of labels

Create a chart


Sections of a form 1

You can increase the effectiveness of a form by adding one or more sections. All forms have a detail section, but a form can also include form header, page header, page footer, and form footer sections.

Sections of a form in Design view


Sections of a form 2

This illustration shows the Add Products form from the previous screen in Form view and when it's printed.

Sections of a form in Form view and when printed


Sections of a form 3

Sections of a subform in Form view and Design view

More information

Add or remove a form header and footer or a page header and footer

Change the size of a header, footer, or other section on a form


Sections of a report 1

The information in a report can be divided into sections. Each section has a specific purpose and prints in a predictable order on the page and in the report.

Sections of a report on a printed report


Sections of a report 2

In Design view, sections are represented as bands, and each section that the report contains is represented once. In the printed report, some sections may be repeated many times. You determine where information appears in every section by placing controls, such as labels and text boxes.

Sections of a report in Design view


Sections of a report 3

By grouping records that share a common value, you can calculate subtotals and make a report easier to read. In this report, orders shipped on the same date are grouped together.

Group header and footer sections in Design view and on a printed report

More information

Add or remove a report header and footer or a page header and footer

Change the size of a header, footer, or other section on a report

Group records in a report


Tables: What they are and how they work 1

A table is a collection of data about a specific topic, such as products or suppliers. Using a separate table for each topic means that you store that data only once, which makes your database more efficient, and reduces data-entry errors.

Suppliers and Products tables


Tables: What they are and how they work 2

Tables organize data into columns (called fields) and rows (called records).

Records and fields in tables


Tables: What they are and how they work 3

A common field relates two tables so that Microsoft Access can bring together the data from the two tables for viewing, editing, or printing.

Common field that relates two tables


Tables: What they are and how they work 4

In table Design view, you can create an entire table from scratch, or add, delete, or customize the fields in an existing table.

Areas in table Design view for working with fields, data types, and primary keys


Tables: What they are and how they work 5

In table Datasheet view, you can add, edit, view, or otherwise work with the data in a table. You can also display records from tables that are related to the current table by displaying subdatasheets within the main datasheet. With some restrictions, you can work with the data in subdatasheets in many of the same ways that you work with data in the main datasheet.

Tools for working with data in Datasheet view

More information

Create a table

Ways to customize a table

Ways to work with data in a table's datasheet


Ways to customize a form 1

You can use the following techniques to customize a form that you created with a wizard or to create a form entirely on your own.

Tasks you can complete in form Design view


Ways to customize a query 1

You customize a query in query Design view. From there, you can make a variety of changes.

Ways to modify a query in Design view


Ways to customize a query 2

Add a table or query if the data you need isn't in the query; then add the fields that you want to work with to the design grid.

Adding tables or queries and fields to the query design grid


Ways to customize a query 3

Add the values in a field or do other computations with the data by specifying the type of calculation to perform.

To perform a predefined calculation on the values in a field, click Totals on the toolbar to display the Total row in the design grid.

Defining calculations and groupings in the query design grid


Ways to customize a query 4

Limit the records that you see in the query's results or the records that are included in a calculation by specifying criteria.

Specifying criteria in the query design grid


Ways to customize a query 5

Sort the query's results by specifying a sort order in the design grid.

Specifying a sort order in the query design grid

More information

Create a query


Ways to customize a report 1

You can use the following techniques to customize a report that you created with a wizard or to create a report entirely on your own.

Tasks you can complete in report Design view


Ways to customize a table 1

In table Design view, you can customize a table in many different ways.

Different ways to customize a table in Design view


Ways to customize a table 2

In table Design view, you can add or delete fields, or customize fields by setting properties.

Opening a table in Design view


Ways to customize a table 3

If you want to track additional data in a table, add more fields. If an existing field name isn't descriptive enough, you can rename the field.

Adding and renaming fields


Ways to customize a table 4

Setting a field's data type defines what kind of values that you can enter into a field. For example, you can't enter text into a Currency field. By choosing an appropriate data type, you can ensure that data is entered in the correct form for sorting, performing calculations, and other operations.

Setting data types


Ways to customize a table 5

Field properties are a set of characteristics that provide additional control over how a field works. For example, depending on your Regional Settings in Windows Control Panel, setting the Format property to Currency for a field with a Number or Currency data type automatically adds commas, a dollar sign, and two decimal places ($1,234.50).

Setting field properties


Ways to customize a table 6

You use a unique tag, called a primary key, to identify each record in your table. Just as a license plate number identifies a car, the primary key uniquely identifies a record.

Setting a primary key

More information

Add a field to a table in Design view

Change a field name in a table

Set field properties to customize how data is stored, handled, or displayed

What kind of primary key should I use


Ways to specify multiple criteria in a query

Query design grid with alternative criteria for one field

More information

Examples of criteria expressions for queries or filters

Where to specify criteria to affect when calculations are performed


Ways to specify multiple criteria in a query 2

Query design grid with two criteria that must both be met for one field

More information

Examples of criteria expressions for queries or filters

Where to specify criteria to affect when calculations are performed


Ways to specify multiple criteria in a query 3

Query design grid with alternative criteria for two fields

More information

Examples of criteria expressions for queries or filters

Where to specify criteria to affect when calculations are performed


Ways to specify multiple criteria in a query 4

Query design grid with criteria that must be met for two fields

More information

Examples of criteria expressions for queries or filters

Where to specify criteria to affect when calculations are performed


Ways to specify multiple criteria in a query 5

Query design grid showing And and Or criteria for three fields

More information

Examples of criteria expressions for queries or filters

Where to specify criteria to affect when calculations are performed


Ways to work with data in a form 1

In Form view, you have all the tools you need to work with your data.

Tasks you can complete in Form view


Ways to work with data in a form 2

Tools to change views and to print, preview, cut, copy, paste, and check spelling of data


Ways to work with data in a form 3

Tools to sort, filter, find, and replace data


Ways to work with data in a form 4

Tools to add and delete records

More information

Create a filter in a table, query, or form

Edit the data in a field

Find specific occurrences of a value in a field

Replace specific occurrences of a value in a field

Sort records in a table, query, or form


Ways to work with data in a query's datasheet 1

There are many ways to work with data in a query's datasheet.

Ways to work with a query datasheet


Ways to work with data in a query's datasheet 2

Tools for cutting, copying, pasting, checking spelling, printing, and previewing data


Ways to work with data in a query's datasheet 3

Tools for sorting, filtering, and finding data


Ways to work with data in a query's datasheet 4

Tools for adding and deleting records


Ways to work with data in a query's datasheet 5

Moving, hiding, freezing, and resizing columns


Ways to work with data in a query's datasheet 6

Navigating between records


Ways to work with data in a query's datasheet 7

While you're viewing the query's results, you can display data that is related to the records in the datasheet by inserting a subdatasheet for the related data. Although there are some restrictions, you can work with data in a subdatasheet in many of the same ways you work with data in the main datasheet; for example, you can filter and sort data.

More information

Copy or move data

Create a filter in a table, query, or form

Edit the data in a field

Find specific occurrences of a value in a field

Replace specific occurrences of a value in a field

Sort records in a table, query, or form


Ways to work with data in a table's datasheet 1

In table Datasheet view, there are many ways to work with data.

Ways to work with data in a datasheet


Ways to work with data in a table's datasheet 2

Tools for cutting, copying, pasting, checking spelling , and printing data


Ways to work with data in a table's datasheet 3

Tools for sorting, filtering, finding, and replacing data


Ways to work with data in a table's datasheet 4

Tools for adding and deleting records


Ways to work with data in a table's datasheet 5

Inserting, naming, and deleting columns


Ways to work with data in a table's datasheet 6

Moving, hiding, freezing, and resizing columns


Ways to work with data in a table's datasheet 7

Displaying subdatasheets in the main datasheet

More information

Copy or move data

Create a filter in a table, query, or form

Edit the data in a field

Find specific occurrences of a value in a field

Replace specific occurrences of a value in a field

Sort records in a table, query, or form


Add or manipulate fields

What do you want to do?

Add a field

Copy a field

Move a field

Rename a field

Repair errors caused by renaming a field

Delete a field


Change the appearance of Datasheet view

What do you want to do?

Change font, or font style, size, and color in Datasheet view

Change the gridline style and background color in Datasheet view

Set defaults for the appearance of Datasheet view

Resize a column in Datasheet view

Move columns in Datasheet view

Freeze and unfreeze columns in Datasheet view

Hide columns in Datasheet view

Show hidden columns in Datasheet view

Resize rows in Datasheet view


Create, modify, or enter data into tables

What do you want to do?

See an overview of what tables are and how they work

Create a table

Open a table

Add new data in Datasheet or Form view

Customize a table


Define or view relationships

What do you want to do?

Display the Relationships window

Define relationships

Define a many-to-many relationship between tables

View existing relationships

Manage relationships by using the keyboard

Print the Relationships window


Export objects

What do you want to do?

Export data to another database or file format

Load the output of a datasheet, form, or report into Microsoft Excel

Save an object's output as a Microsoft Excel or rich text format


Import data

What do you want to do?

Import or link data

Troubleshoot text or spreadsheet import errors


Link data

What do you want to do?

Import or link data

Delete the link to a linked table

Troubleshoot problems with linked tables

View, refresh, or change the filename and path for linked tables


Work with data in Datasheet view

What do you want to do?

Add new data in Datasheet or Form view

Select fields and records in Datasheet view

Copy or move data

Troubleshoot problems when pasting data

Change the appearance of Datasheet view

Display the most current data in Datasheet or Form view

Move between fields in long records with the Go To Field box in Datasheet view

Use shortcut keys to edit text or data

Delete a record in Datasheet or Form view

Undo changes when adding or editing records

Insert the value that is in the same field in the previous record


Work in Form view

What do you want to do?

Add new data in Datasheet or Form view

Copy or move data

Troubleshoot problems when pasting data

Display the most current data in Datasheet or Form view

Delete a record in Datasheet or Form view

Undo changes when adding or editing records


Compiler Constants

  • Microsoft Access is a 32-bit development environment. The compiler constant Win32 will always evaluate to True (-1), while the constant Win16 will always evaluate to False (0).


Create, modify, or enter data into forms

What do you want to do?

See an overview of what forms are and how they work

Create a form

Open a form

Add new data in Datasheet or Form view

Customize a form


 Constants, fixed-length strings, arrays, and Declare statements not allowed as Public members of class module

Constants, fixed-length strings, arrays, and Declare statements not allowed as Public members of class module

  • In Microsoft Access, class modules exist both alone and in association with forms and reports. You can't declare a public constant, fixed-length string, or Declare statement in a form module or a report module. You must preface the declaration with the Private keyword.


 Invalid use of New keyword

Invalid use of New keyword

In Microsoft Access, form modules and report modules are class modules. You can use the New keyword to create a new instance of a class module and assign it to an object variable.

For example, to create a new instance of a form class module called Form_Orders, use the New keyword as shown in the following code:

Dim frmOrdersObject As New Form_Orders


 Member already exists in this form

Member already exists in this form

In Microsoft Access, you can't use an identifier in a form module and report module if that identifier has the same name as a method or property of the form or report. For example, since a form has a RecordSource property, a procedure such as the following in the form's module would cause an error:

Sub RecordSource()        ' Generates an error.
    .                            ' Some code.
    .
    .
End Sub


ApplyFilter 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'"


Close Method (Microsoft Access) Example

Close 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


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


DeleteObject Method Example

The following example deletes the specified table:

DoCmd.DeleteObject acTable, "Former Employees Table"


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


Echo Method (DoCmd Object) 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."


FindRecord Method Example

The following example finds the first occurrence in the records of the name Smith in the current field. It doesn't find occurrences of smith or Smithson.

DoCmd.FindRecord "Smith",, True,, True


GoToControl Method Example

The following example uses the GoToControl method to move the focus to the EmployeeID field:

DoCmd.GoToControl "EmployeeID"


GoToPage Method (DoCmd Object) 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


GoToRecord 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


Hourglass 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


MoveSize Method Example

The following example moves the active window and changes its height, but leaves its width unchanged:

DoCmd.MoveSize 1440, 2400, , 2000


OpenDataAccessPage Method Example

The following example opens the Employees data access page in Design view.

DoCmd.OpenDataAccessPage "Employees", acDataPageDesign


OpenForm 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 Method Example

The following example opens the Utility Functions module to the IsLoaded( ) Function procedure:

DoCmd.OpenModule "Utility Functions","IsLoaded"


OpenQuery 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 Method Example

The following example prints Sales Report while using the existing query Report Filter:

DoCmd.OpenReport "Sales Report", acViewNormal, "Report Filter"


OpenStoredProcedure Method Example

The following example opens the Employees stored procedure in Design view.

DoCmd.OpenStoredProcedure "Employees", 1


OpenTable Method Example

The following example opens the Employees table in Print Preview:

DoCmd.OpenTable "Employees", acViewPreview


OpenView Method Example

The following example opens the Employees view.

DoCmd.OpenView "Employees"


OutputTo 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


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


Quit Method (DoCmd Object) 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


Rename Method Example

The following example renames the Employees table with the specified name:

DoCmd.Rename "Old Employees Table", acTable, "Employees"


RepaintObject Method Example

The following example repaints the table Customers:

DoCmd.RepaintObject acTable, "Customers"


Requery Method (DoCmd Object) Example

The following example uses the Requery method to update the EmployeeList control:

DoCmd.Requery "EmployeeList"


RunMacro Method Example

The following example runs the macro Print Sales that will print the sales report twice:

DoCmd.RunMacro "Print Sales", 2


RunSQL Method Example

The following example updates the Employees table, changing each sales manager's title to Regional Sales Manager:

DoCmd.RunSQL "UPDATE Employees " & _
    "SET Employees.Title = 'Regional Sales Manager' " & _
    "WHERE Employees.Title = 'Sales Manager';"


Save Method 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"


SelectObject Method Example

The following example selects the form Customers in the Database window:

DoCmd.SelectObject acForm, "Customers", True


SendObject 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


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


SetWarnings Method Example

The following example turns the display of system messages off:

DoCmd.SetWarnings False


ShowToolbar Method Example

The following example displays the custom toolbar named CustomToolbar in all Microsoft Access windows that become active:

DoCmd.ShowToolbar "CustomToolbar", acToolbarYes


TransferDatabase 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 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 Method 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"


 Add Method (CommandBarControls Collection)

Add Method (CommandBarControls Collection)

You can set the Id argument of this method to an Integer value that corresponds to a built-in command button or menu item. This will cause the new control to have the appearance and functionality of the existing command button or menu item.

However, if you set the Id argument to the Integer value of a Microsoft Office command button or menu item that has been modified by Microsoft Access (for example, Microsoft Access uses a different label, different shortcut text, or uses text instead of an icon), you won't see the Microsoft Access modifications to the command button or menu item. If you want to make sure a control you're adding to a command bar looks and functions exactly like the Microsoft Access version of the control, use the Copy method to copy the control to the command bar.


AddFromFile, AddFromString Methods 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_AddTextToModule
End 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 directory, My Documents. 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 If
End 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


AddNew Method Example

The following example creates a new record in an Employees table and saves the changes:

Sub AddNewRecord()

    Dim cnn As ADODB.Connection
    Dim rst As New ADODB.Recordset

    Set cnn = CurrentProject.Connection
    rst.Open "Employees", cnn, adOpenKeyset, adLockOptimistic, adCmdTableDirect

    With rst
        .AddNew                         ' Add new record.
        !LastName = "Gregory"         ' Add data.
        !FirstName = "Justin"
        !BirthDate = #1/27/1970#
        .Update                         ' Save changes.
    End With

End Sub


AddNew Method Example (MDB)

The following example creates a new record in an Employees table and saves the changes:

Sub AddNewRecord(ByVal rst As Recordset, _
    strLast As String, strFirst As String)

    With rst
        .AddNew                            ' Add new record.
        !LastName = strLast            ' Add data.
        !FirstName = strFirst
        .Update                            ' Save changes.
    End With
End Sub


Add, Remove Methods (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_AddPage
End 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_RemovePage
End Function


 Add Method

Add Method

Items added to a user-defined collection are automatically indexed. You can refer to an individual item by this index. For example, if you have a collection colThings that contains four objects, you can refer to the third item in the collection with the expression colThings(3).

Note When you add items to a Collection object, they are automatically indexed beginning with the number 1. Therefore, when you enumerate a Collection object, keep in mind that the index begins at 1. This may be different from built-in collections, which usually are indexed beginning with 0.

When you add an object to a user-defined collection, you can also specify a custom key for that object in addition to the automatic index. In subsequent references to the object, you can refer to the custom key. For example, you can add an object objMine with the following key.

colThings.Add Item := objMine, key := ("A")

Subsequently you can refer to this particular object in the collection either as colThings(A), or by its numeric index.


AddToFavorites 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.AddToFavorites
End Sub


Append Method Example

The following example appends a new Column to the Columns collection of a Table object:

Sub NewField()

    Dim cat As New ADOX.Catalog, tbl As ADOX.Table

    ' Return reference to current database.
    Set cat.ActiveConnection = CurrentProject.Connection
    Set tbl = cat.Tables(“Employees”)
    ' Create new field in Employees table.
    tbl.Columns.Append "SocialSecurity#", adVarWChar, 11
    ' Append field and refresh collection.
    cat.Tables.Refresh
End Sub


AppendChunk, GetChunk Methods Example

The following example appends data to the Notes field for each record in an Employees table. The data type of the Notes field is Memo. The procedure returns the contents of the field by using the GetChunk method, adds to the data, and appends the altered data back to the Notes field by using the AppendChunk method.

Sub AddToMemo()
Dim cnn As ADODB.Connection, rst As New ADODB.Recordset
Dim fldFirstName As ADODB.Field
Dim fldLastName As ADODB.Field
Dim fldNotes As ADODB.Field
Dim lngSize As Long, strChunk As String

Set cnn = CurrentProject.Connection
rst.Open "Employees", cnn, adOpenKeyset, adLockOptimistic
With rst
Set fldNotes = !Notes
Set fldFirstName = !FirstName
Set fldLastName = !LastName
Do Until .EOF
If IsNull(fldNotes.Value) Then
strChunk = fldFirstName & " " & fldLastName & " is an excellent employee."
!Notes = strChunk
.MoveNext
Else
lngSize = Len(fldNotes)
strChunk = fldNotes.GetChunk(lngSize)
strChunk = strChunk & " " & fldFirstName & " " & fldLastName & " is and excellent Employee."
!Notes = " "
!Notes.AppendChunk strChunk
.MoveNext
End If
Loop
End With
rst.Close
cnn.Close
End Sub


AppendChunk, GetChunk Methods Example (MDB)

The following example appends data to the Notes field for each record in an Employees table. The data type of the Notes field is Memo. The procedure returns the contents of the field by using the GetChunk method, adds to the data, and appends the altered data back to the Notes field by using the AppendChunk method.

Sub AddToMemo()
    Dim dbs As Database, rst As Recordset
    Dim fldNotes As Field, fldFirstName As Field
    Dim fldLastName As Field
    Dim lngSize As Long, strChunk As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create table-type Recordset object.
    Set rst = dbs.OpenRecordset("Employees")
    ' Return references to Field objects.
    Set fldNotes = rst!Notes
    Set fldFirstName = rst!FirstName
    Set fldLastName = rst!LastName

    ' Loop through all records in recordset.
    Do Until rst.EOF
        ' Check if data exists in Notes field.
        If IsNull(fldNotes.Value) Then
            ' If no data, use AppendChunk method only.
            strChunk = fldFirstName _
                & " " & fldLastName & " is an excellent employee."
            With rst
                .Edit
                !Notes = strChunk
                .Update
                .MoveNext
            End With
        Else
            lngSize = Len(fldNotes)
            ' Use GetChunk to retrieve existing data.
            strChunk = fldNotes.GetChunk(0, lngSize)
            ' Alter data.
            strChunk = strChunk & "  " & fldFirstName _
                & " " & fldLastName & " is an excellent employee."
            With rst
                .Edit                             ' Enable editing.
                !Notes = ""                     ' Initialize field.
                ' Append altered data.
                !Notes.AppendChunk strChunk
                .Update                         ' Save changes.
                ' Move to next record.
                .MoveNext
            End With
        End If
    Loop
    rst.Close
    Set dbs = Nothing
End Sub


Append Method Example (MDB)

The following example defines a new Field object and appends it to the Fields collection of a TableDef object:

Sub NewField()
    Dim dbs As Database, tdf As TableDef, fld As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Employees
    ' Create new field in Employees table.
    Set fld = tdf.CreateField("SocialSecurity#", dbText, 11)
    ' Append field and refresh collection.
    tdf.Fields.Append fld
    tdf.Fields.Refresh
    Set dbs = Nothing
End Sub


BeginTrans, CommitTrans, Rollback Methods Example

The following example changes the category type of the current record in the categories form and then confirms the change with the user before using the CommitTrans method to save the change.

This example requires that the Categories form be opened

Sub cmdSave_OnClick()
    Dim rs as ADODB.Recordset
    Dim Response As Integer

    Set rs = Forms("Categories").Recordset
    With rs
        rs.ActiveConnection.BeginTrans
        !CategoryName = "Drinks"
        .Update
        Response = Msgbox "Are you sure you want to change the current value to." & !CategoryName & "?", vbYesNo
        If Response = vbNo Then
            rs.ActiveConnection.RollbackTrans
        Else
            rs.ActiveConnection.CommitTrans
        End If
    End With
End Sub

This example changes the job title of all sales representatives in an Employees table. After the BeginTrans method starts a transaction that isolates all the changes made to the Employees table, the CommitTrans method saves the changes. Notice that you can use the Rollback method to undo changes that you saved by using the Update method. The example also shows how to maintain a flag to properly manage errors that might occur during a transaction.

One or more table pages remain locked while the user decides whether or not to accept the changes. Consequently, this technique isn't recommended but is shown only as an example.

Sub ChangeTitle()
    Dim cnn As ADODB.Connection, rst As New ADODB.Recordset
    Dim strName As String, strMessage As String, strPrompt As String
    Dim fInTrans As Boolean

    On Error GoTo ChangeTitleErr

    fInTrans = False
    strPrompt = "Change title to Account Executive?"

    ' Return reference to current database.
    Set cnn = CurrentProject.Connection
    ' Create table-type Recordset object.
    rst.Open "Employees", cnn, adOpenKeyset, adLockOptimistic, adCmdTableDirect
    ' Start of transaction.
    cnn.BeginTrans
    fInTrans = True
    With rst
    .MoveFirst
    Do Until rst.EOF
        If !Title = "Sales Representative" Then
            strName = !LastName & ", " & !FirstName
            strMessage = "Employee: " & strName & vbCrLf & vbCrLf
            If MsgBox(strMessage & strPrompt, vbQuestion + _
                    vbYesNo, "Change Job Title") = vbYes Then
                !Title = "Account Executive"
            End If
        End If
        ' Move to next record.
        .MoveNext
    Loop
    End With
    If MsgBox("Save all changes?", vbQuestion + vbYesNo, _
            " Save Changes") = vbYes Then
        cnn.CommitTrans         ' Commit changes.
    Else
        cnn.RollbackTrans                ' Undo changes.
    End If
ChangeTitleExit:
    rst.Close
    Exit Sub
ChangeTitleErr:
    MsgBox Err.Number & " " & Err.Description
    If fInTrans Then
        cnn.RollbackTrans
    End If
    Resume ChangeTitleExit
End Sub


BeginTrans, CommitTrans, Rollback Methods Example (MDB)

The following example changes the job title of all sales representatives in an Employees table. After the BeginTrans method starts a transaction that isolates all the changes made to the Employees table, the CommitTrans method saves the changes. Notice that you can use the Rollback method to undo changes that you saved by using the Update method. The example also shows how to maintain a flag to properly manage errors that might occur during a transaction.

One or more table pages remain locked while the user decides whether or not to accept the changes. Consequently, this technique isn't recommended but is shown only as an example.

Sub ChangeTitle()
    Dim wsp As Workspace, dbs As Database, rst As Recordset
    Dim strName As String, strMessage As String, _
        strPrompt As String
    Dim fInTrans As Boolean

    On Error GoTo ChangeTitleErr

    fInTrans = False
    strPrompt = "Change title to Account Executive?"
    ' Return reference to default Workspace object.
    Set wsp = DBEngine.Workspaces(0)
    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create table-type Recordset object.
    Set rst = dbs.OpenRecordset("Employees", dbOpenTable)
    ' Start of transaction.
    wsp.BeginTrans
    fInTrans = True
    rst.MoveFirst
    Do Until rst.EOF
        If rst!Title = "Sales Representative" Then
            strName = rst!LastName & ", " & rst!FirstName
            strMessage = "Employee: " & strName & vbCrLf & vbCrLf
            If MsgBox(strMessage & strPrompt, vbQuestion + _
                    vbYesNo, "Change Job Title") = vbYes Then
                ' Enable editing.
                rst.Edit
                rst!Title = "Account Executive"
                ' Save changes.
                rst.Update
            End If
        End If
        ' Move to next record.
        rst.MoveNext
    Loop
    If MsgBox("Save all changes?", vbQuestion + vbYesNo, _
            " Save Changes") = vbYes Then
        wsp.CommitTrans            ' Commit changes.
    Else
        wsp.Rollback                ' Undo changes.
    End If
ChangeTitleExit:
    rst.Close
    Set dbs = Nothing
    Set wsp = Nothing
    Exit Sub
ChangeTitleErr:
    MsgBox "Error!"
    If fInTrans Then
        wsp.Rollback
    End If
    Resume ChangeTitleExit
End Sub


BuildCriteria Method Example

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 = True
End Sub


CancelUpdate, Update Methods Example

The following example creates a new record in an Employees table, enters values, and prompts the user to save the changes. If the user chooses not to save the changes, the Update method is canceled.

Sub NewRecord()
    Dim cnn As ADODB.Connection, rst As New ADODB.Recordset

    ' Return reference to current connection
    Set cnn = CurrentProject.Connection
    rst.Open "Employees", cnn, adOpenKeyset, adLockOptimistic
    With rst
        ' Add new record to end of Recordset object.
        .AddNew
        !LastName = "Christopher"       ' Add data.
        !FirstName = "Kevin"
        !BirthDate = #2/24/1970#        ' Need a valid BirthDate

        ' Prompt user to save changes.
        If MsgBox("Save these changes?", vbYesNo) = vbNo Then
            ' If user chooses No, cancel changes.
            .CancelUpdate
        Else
            ' If user chooses Yes, save changes.
            .Update
        End If
    End With
    rst.Close
    Set cnn = Nothing
End Sub


CancelUpdate, Update Methods Example (MDB)

The following example creates a new record in an Employees table, enters values, and prompts the user to save the changes. If the user chooses not to save the changes, the Update method is canceled.

Sub NewRecord()
    Dim dbs As Database, rst As Recordset

    ' Return reference to current database.
    Set dbs = CurrentDb
    Set rst = dbs.OpenRecordset("Employees")
    With rst
        ' Add new record to end of Recordset object.
        .AddNew
        !LastName = "Christopher"        ' Add data.
        !FirstName = "Kevin"
    End With
    ' Prompt user to save changes.
    If MsgBox("Save these changes?", vbYesNo) = vbNo Then
        ' If user chooses No, cancel changes.
        rst.CancelUpdate
    Else
        ' If user chooses Yes, save changes.
        rst.Update
    End If
    rst.Close
    Set dbs = Nothing
End Sub


Circle Method Example

The following example uses the Circle method to draw a circle, and then create a pie slice within the circle and color it red.

To try this example in Microsoft Access, create a new report. 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.
    Me.FillStyle = 0                     ' Fill pie slice.
    ' Draw pie slice within circle.
    Me.Circle(sngHCtr, sngVCtr), sngRadius, , sngStart, sngEnd
End Sub


Clone Method Example

The following example creates a Recordset object by using a SQL statement on an Employees table and then uses the Clone method to create a clone of the Recordset object so that bookmarks can be shared between the two objects. This technique is especially useful when you have to compare the results of a query from more than one point at the same time.

The function reads and stores in a variable the value of the Bookmark property for the current record, in this case the second record in the original Recordset object. The Bookmark property of the duplicate Recordset object is set to this string, making the second record the current record in this Recordset object as well. The current values of the LastName field for both recordsets are identical, as you can see once they are printed in the Debug window.

Sub CreateClone()
    Dim cnn As ADODB.Connection
    Dim rstEmployees As New ADODB.Recordset, rstDuplicate As ADODB.Recordset
    Dim fldName As ADODB.Field, varBook As Variant

    ' Return reference to current database.
    Set cnn = CurrentProject.Connection
    ' Open dynaset-type Recordset object.
        rstEmployees.Open "SELECT * FROM Employees ORDER BY LastName", _ cnn, adOpenKeyset, adLockOptimistic
    ' Clone Recordset object.
    Set rstDuplicate = rstEmployees.Clone
    Set fldName = rstEmployees.Fields!LastName
    ' Set current record.
    rstEmployees.MoveFirst
    ' Move to second record.
    rstEmployees.MoveNext
    ' Get Bookmark property value and print current field value.
    If rstEmployees.Properties("Bookmarkable") Then
        varBook = rstEmployees.Bookmark
        Debug.Print fldName.Value
        ' Set Bookmark property of clone to obtained value.
            rstDuplicate.Bookmark = varBook
        Debug.Print fldName.Value
    End If

    rstEmployees.Close
    rstDuplicate.Close
    Set cnn = Nothing
End Sub


Clone Method Example (MDB)

The following example creates a Recordset object by using an SQL statement on an Employees table and then uses the Clone method to create a clone of the Recordset object so that bookmarks can be shared between the two objects. This technique is especially useful when you have to compare the results of a query from more than one point at the same time.

The function reads and stores in a string variable the value of the Bookmark property for the current record, in this case the second record in the original Recordset object. The Bookmark property of the duplicate Recordset object is set to this string, making the second record the current record in this Recordset object as well. The current values of the LastName field for both recordsets are identical, as you can see once they are printed in the Debug window.

Sub CreateClone()
    Dim dbs As Database
    Dim rstEmployees As Recordset, rstDuplicate As Recordset
    Dim fldName As Field, varBook As Variant

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Open dynaset-type Recordset object.
    Set rstEmployees = dbs.OpenRecordset("SELECT * " _
        & "FROM Employees ORDER BY LastName")
    ' Clone Recordset object.
    Set rstDuplicate = rstEmployees.Clone
    Set fldName = rstEmployees.Fields!LastName
    ' Set current record.
    rstEmployees.MoveFirst
    ' Move to second record.
    rstEmployees.MoveNext
    ' Get Bookmark property value and print current field value.
    If rstEmployees.Bookmarkable Then
        varBook = rstEmployees.Bookmark
        Debug.Print fldName.value
    Else
        ' If Recordset object doesn't support bookmarks,
        ' exit procedure.
        ExitCreateClone
    End If
    ' Set Bookmark property of clone to obtained value.
    rstDuplicate.Bookmark = varBook
    Debug.Print fldName.value

ExitCreateClone:
    rstEmployees.Close
    rstDuplicate.Close
    Set dbs = Nothing
End Sub


Close Method Example

The following example creates a Connection object that points to the current connection and opens a table-type Recordset object based on a Customers table in the database. The procedure uses the Close method on the Recordset object variable to free the memory resources it has been using. It uses the Set statement with the Nothing keyword to free resources used by the Connection object variable.

You can also use the Close method of the Connection object to close it and free memory. The Close method of the Connection object doesn't actually close the database that's open in Microsoft Access; it only frees the resources used by the Connection object variable.

Using an object's Close method and setting the object variable to Nothing are equivalent ways to free memory.

Sub UseClose()
    Dim cnn As ADODB.Connection, rst As New ADODB.Recordset

    ' Return reference to current database.
    Set cnn = CurrentProject.Connection
    ' Create table-type recordset.
    rst.Open “Customers",cnn

    ' Code that does something

    ' Close recordset to free memory.
    rst.Close
    ' Free memory used by object variable.
    Set cnn = Nothing
End Sub


 CloseConnection Method

CloseConnection Method

You can use the CloseConnection method to close the current connection between the CurrentProject or CodeProject object in a Microsoft Access project (.adp) or Access database (.mdb) and the database specified in the project's base connection string.

Syntax

object.CloseConnection

The CloseConnection method has the following argument.

Argument | Description
object | A string expression that evaluates to the CurrentProject or CodeProject object.

Remarks

The CloseConnection method closes the current connection of the Access project, database, or data source control, frees the ADO Connection object, and sets the Connection property to Null. The BaseConnectionString property is left unchanged. Users are prevented from calling datasoucecontrol.Connection.Close and must use this method instead.

The CloseConnection method is useful when you have opened a Microsoft Access database from another application through Automation.


CloseCurrentDatabase Method 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 a COM 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.9")
    ' 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 = Nothing
End Sub


 Close Method

Close Method

If a Visual Basic procedure contains an object variable that represents the database currently open in Microsoft Access, using the Close method on that object causes the variable to go out of scope. The Close method will not affect the database that is open in the Microsoft Access Database window.


Open Method (Connection)

In Microsoft Access, use CurrentProject.Connection to return a reference to the current database and assign it to a Connection variable, as shown in the following example.

Dim cnnCurrent As ADODB.Connection
Set cnnCurrent = CurrentProject.Connection

Use the Open method of a Connection variable to open a database other than the current database from Visual Basic.


CodeDb Method Example

The following example uses the CodeDb method 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 method 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.Close
End Function


 CompactDatabase Method (MDB)

CompactDatabase Method (MDB)

To compact a database from the Microsoft Access window, point to Database Utilities on the Tools menu, and click Compact Database.

Note: The CompactDatabase method won't completely convert an Access database (.mdb) from one version to another. Only the data format is converted. Microsoft Access–defined objects, such as forms and reports, aren't converted. To convert a database created in a previous version, point to Database Utilities on the Tools menu and click Convert Database.


CopyQueryDef Method Example (MDB)

The following example uses the CopyQueryDef method to return a copy of a QueryDef object representing an Invoices query, and prints the SQL property of that QueryDef object.

Sub GetQueryDefCopy()
    Dim dbs As Database, rst As Recordset
    Dim qdfOriginal As QueryDef, qdfCopy As QueryDef

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Invoices query.
    Set qdfOriginal = dbs.QueryDefs!Invoices
    ' Open dynaset-type Recordset object.
    Set rst = qdfOriginal.OpenRecordset
    ' Get copy of original QueryDef object.
    Set qdfCopy = rst.CopyQueryDef
    ' Print value of SQL property for copy.
    Debug.Print qdfCopy.SQL
    rst.Close
    Set dbs = Nothing
End Sub


CreateControl, CreateReportControl Methods Example

The following example first creates a new form based on an Orders table. It then uses the CreateControl method to create a text box control and an attached label control on the form.

Sub NewControls()
    Dim frm As Form
    Dim ctlLabel As Control, ctlText As Control
    Dim intDataX As Integer, intDataY As Integer
    Dim intLabelX As Integer, intLabelY As Integer

    ' Create new form with Orders table as its record source.
    Set frm = CreateForm
    frm.RecordSource = "Orders"
    ' Set positioning values for new controls.
    intLabelX = 100
    intLabelY = 100
    intDataX = 1000
    intDataY = 100
    ' Create unbound default-size text box in detail section.
    Set ctlText = CreateControl(frm.Name, acTextBox, , "", "", _
        intDataX, intDataY)
    ' Create child label control for text box.
    Set ctlLabel = CreateControl(frm.Name, acLabel, , _
         ctlText.Name, "NewLabel", intLabelX, intLabelY)
    ' Restore form.
    DoCmd.Restore
End Sub


CreateDataAccessPage Method Example

The following code fragment illustrates how you could create a new data access page, work with the HTML in the page, and then create a link to the page and permanently save it to disk. The procedure also illustrates one way to use an error trap to handle files that already exist:

Function CreateDAP(strFileName As String) As Boolean
    Dim dapNewPage As DataAccessPage

    Const DAP_EXISTS As Long = 2023

    On Error GoTo CreateDAP_Err
    ' Create the new page.
    Set dapNewPage = Application.CreateDataAccessPage(strFileName, _
        True)
    ' Use the Document property to return the Internet Explorer 5.0
    ' document object, and then use the Internet Explorer objects to
    ' work with the HTML in the page.

    With dapNewPage.Document
        .All("HeadingText").innerText = "This page was created " _
            & "programmatically!"
        .All("HeadingText").Style.display = ""
        .All("BeforeBodyText").innerText = "When you work " _
            & "with the HTML in a data access page, you " _
            & "must use the document property of the Page " _
            & "to get to the HTML. "
            .All("BeforeBodyText").Style.display = ""
    End With

    ' Close the page and save all changes.
    DoCmd.Close acDataAccessPage, dapNewPage.Name, acSaveYes
    CreateDAP = True
CreateDAP_End:
    Exit Function
CreateDAP_Err:
    If Err = DAP_EXISTS Then
        ' The file specified in strFileName already exists,
        ' so replace it with this new page.
        If MsgBox("'" & strFileName & " already exists. Do you " _
            & "want to replace it with a new, blank page?", vbYesNo, _
            "Replace existing page?") = vbYes Then
            Set dapNewPage = Application.CreateDataAccessPage(strFileName, False)
            Resume Next
        Else
            CreateDAP = False
            Resume CreateDAP_End
        End If
    Else
        CreateDAP = False
        Resume CreateDAP_End
    End If
End Function

The following example fragment illustrates how the CreateDataAccessPage method can be used to create multiple links to a single page on disk.

Sub Foo()
    Dim dapNewPage As DataAccessPage
    Set dapNewPage = _
        Application.CreateDataAccessPage("c:\footest.htm", True)
    DoCmd.Close acDataAccessPage, dapNewPage.Name, acSaveYes
    Set dapNewPage = _
        Application.CreateDataAccessPage("c:\footest.htm", False)
    DoCmd.Close acDataAccessPage, dapNewPage.Name, acSaveYes
End Sub


 CreateDatabase Method (MDB)

CreateDatabase Method (MDB)

The CreateDatabase method in the DAO object library creates a new Access database (.mdb) database from Visual Basic, opens the new database, appends it to the Databases collection, and saves to disk.

Use of the CreateDatabase command doesn't affect the database that's currently open in the Microsoft Access Database window. A database that you've opened in the Database window remains open and is the first database in the Databases collection.

To open a database that you have created with CreateDatabase in the Database window, you must click Open Database on the File menu.


CreateDatabase Method Example

CreateDatabase Method Example (MDB)

The following example uses CreateDatabase to create a new, encrypted database named Newdb.mdb:

Sub NewDatabase()
    Dim wspDefault As Workspace, dbs As Database
    Dim tdf As TableDef, fld1 As Field, fld2 As Field
    Dim idx As Index, fldIndex As Field

    Set wspDefault = DBEngine.Workspaces(0)
    ' Create new, encrypted database.
    Set dbs = wspDefault.CreateDatabase("Newdb.mdb", _
        dbLangGeneral, dbEncrypt)
    ' Create new table with two fields.
    Set tdf = dbs.CreateTableDef("Contacts")
    Set fld1 = tdf.CreateField("ContactID", dbLong)
    fld1.Attributes = fld1.Attributes + dbAutoIncrField
    Set fld2 = tdf.CreateField("ContactName", dbText, 50)
    ' Append fields.
    tdf.Fields.Append fld1
    tdf.Fields.Append fld2
    ' Create primary key index.
    Set idx = tdf.CreateIndex("PrimaryKey")
    Set fldIndex = idx.CreateField("ContactID", dbLong)
    ' Append index fields.
    idx.Fields.Append fldIndex
    ' Set Primary property.
    idx.Primary = True
    ' Append index.
    tdf.Indexes.Append idx
    ' Append TableDef object.
    dbs.TableDefs.Append tdf
    dbs.TableDefs.Refresh
    Set dbs = Nothing
End Sub


CreateEventProc, InsertLines Methods Example

The following example creates a new form, adds a command button, and creates a Click event procedure for the command button:

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_ClickEventProc
End Function


CreateField Method Example (MDB)

The following example creates a new table with two new fields. One of the fields is an AutoNumber field. The procedure also makes this field the primary key in the table.

Sub NewTable()
    Dim dbs As Database
    Dim tdf As TableDef, fld1 As Field, fld2 As Field
    Dim idx As Index, fldIndex As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create new table with two fields.
    Set tdf = dbs.CreateTableDef("Contacts")
    Set fld1 = tdf.CreateField("ContactID", dbLong)
    fld1.Attributes = fld1.Attributes + dbAutoIncrField
    Set fld2 = tdf.CreateField("ContactName", dbText, 50)
    ' Append fields.
    tdf.Fields.Append fld1
    tdf.Fields.Append fld2
    ' Create primary key index.
    Set idx = tdf.CreateIndex("PrimaryKey")
    Set fldIndex = idx.CreateField("ContactID", dbLong)
    ' Append index fields.
    idx.Fields.Append fldIndex
    ' Set Primary property.
    idx.Primary = True
    ' Append index.
    tdf.Indexes.Append idx
    ' Append TableDef object.
    dbs.TableDefs.Append tdf
    dbs.TableDefs.Refresh
    Set dbs = Nothing
End Sub


CreateForm, CreateReport Methods 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


AddFromFile Method (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
    ' Create new reference.
    Set ref = References.AddFromFile(strFileName)
    ReferenceFromFile = True

Exit_ReferenceFromFile:
    Exit Function

Error_ReferenceFromFile:
    MsgBox Err & ": " & Err.Description
    ReferenceFromFile = False
    Resume Exit_ReferenceFromFile
End 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 If
End Sub


CreateGroupLevel Method 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 method creates both the header and footer for the group level. The header and footer are then sized.

Sub CreateGL()
    Dim varGroupLevel As Variant

    ' Create new group level on OrderDate field.
    varGroupLevel = CreateGroupLevel("OrderReport", "OrderDate", _
        True, True)
    ' Set height of header/footer sections.
    Reports!OrderReport.Section(acGroupLevel1Header).Height = 400
    Reports!OrderReport.Section(acGroupLevel1Footer).Height = 400
End Sub


CreateGroup Method (MDB)

Once you have created a new Group object and appended it to the Groups collection of a Workspace or User object, you can verify that the new group exists by examining the Name list box on the Groups tab of the User And Group Accounts dialog box. This dialog box is available by pointing to Security on the Tools menu and clicking User and Group Accounts.


CreateIndex Method Example (MDB)

The following example creates a new Index object on an Employees table. The new index consists of two fields, LastName and FirstName.

Sub NewIndex()
    Dim dbs As Database, tdf As TableDef
    Dim idx As Index
    Dim fldLastName As Field, fldFirstName As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Employees table.
    Set tdf = dbs.TableDefs!Employees
    ' Return reference to new index.
    Set idx = tdf.CreateIndex("FullName")
    ' Create and append index fields.
    Set fldLastName = idx.CreateField("LastName", dbText)
    Set fldFirstName = idx.CreateField("FirstName", dbText)
    idx.Fields.Append fldLastName
    idx.Fields.Append fldFirstName
    ' Append Index object and refresh collection.
    tdf.Indexes.Append idx
    tdf.Indexes.Refresh
    Set dbs = Nothing
End Sub


Create Method Example

The following example uses Create to create a new, encrypted database named Newdb.mdb:

Note The Create method is not supported in ADPs by the SQL provider released with Microsoft Access 2000. A reference to "Microsoft ADO ext. 2.1 for DDL and Security" must be set to use this example.

Sub NewDatabase()
    Dim cat As New ADOX.Catalog

 cat.Create "Provider=Microsoft.Jet.OLEDB.4.0;" _
   & "Data Source=Newdb.mdb;" _
    & "Jet OLEDB:Encrypt Database=True"

    Set cat = Nothing
End Sub


 CreateProperty Method (MDB)

CreateProperty Method (MDB)

Microsoft Access defines a number of properties on data access objects. These properties are not automatically recognized by the Microsoft Jet database engine. In order to set or return values for a Microsoft Access–defined property in Visual Basic, you must specifically add the property to the Properties collection of the object to which it applies. You can do this by using the CreateProperty method to create the property and then appending it to the Properties collection.

For example, Microsoft Access defines the Description property of a TableDef object. If this property hasn't already been set from table Design view, you must use the CreateProperty method to create the property and then append it to the Properties collection in order to set the property from Visual Basic.

A Microsoft Access–defined property is automatically added to the Properties collection when it is first set from the Microsoft Access window. If the property has already been set in this way, then you don't need to add it to the Properties collection.

When you write code to set a Microsoft Access–defined property, you should include an error-handling routine that creates a Property object representing that property and appends it to the Properties collection if it does not already exist in the collection.

When you refer to a Microsoft Access–defined property in Visual Basic, you must explicitly refer to the Properties collection. For example, you would refer to the AppTitle property in the following manner, once it exists within the Properties collection of a Database object representing the current database.

Dim dbs As Database
Set dbs = CurrentDb
dbs.Properties!AppTitle = "Northwind Traders"

Note You need to create and append only the Microsoft Access properties that apply to DAO objects. You can set other Microsoft Access properties in Visual Basic by using the standard object.property syntax.


CreateProperty Method Example (MDB)

The first procedure in the following example, the SetAccessProperty function, is a generic function that you can use to set a property. If the property you wish to set already has a corresponding Property object in the Properties collection, the function simply sets the property to the desired value. If the property does not have a corresponding Property object in the Properties collection, then the function creates the Property object and appends it to the Properties collection.

The second procedure sets the Subject property using the SetAccessProperty function. The Subject property is a database property that can also be set on the Summary tab of the Database Properties dialog box, available by clicking Database Properties on the File menu.

The Subject property applies to a DAO object — the SummaryInfo Document object, which is defined by Microsoft Access. If the Subject property doesn't already exist in the Properties collection for the SummaryInfo Document object, the SetAccessProperty function adds it.

Function SetAccessProperty(obj As Object, strName As String, _
        intType As Integer, varSetting As Variant) As Boolean
    Dim prp As Property
    Const conPropNotFound As Integer = 3270

    On Error GoTo ErrorSetAccessProperty
    ' Explicitly refer to Properties collection.
    obj.Properties(strName) = varSetting
    obj.Properties.Refresh
    SetAccessProperty = True

ExitSetAccessProperty:
    Exit Function

ErrorSetAccessProperty:
    If Err = conPropNotFound Then
        ' Create property, denote type, and set initial value.
        Set prp = obj.CreateProperty(strName, intType, varSetting)
        ' Append Property object to Properties collection.
        obj.Properties.Append prp
        obj.Properties.Refresh
        SetAccessProperty = True
        Resume ExitSetAccessProperty
    Else
        MsgBox Err & ": " & vbCrLf & Err.Description
        SetAccessProperty = False
        Resume ExitSetAccessProperty
    End If
End Function

The following procedure calls the SetAccessProperty function to set the Subject property.

Sub CallPropertySet()
    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.
    Set doc = ctr.Documents!SummaryInfo
    blnReturn = SetAccessProperty(doc, _
        "Subject", dbText, "Business Contacts")
    ' Evaluate return value.
    If blnReturn = True Then
        Debug.Print "Property set successfully."
    Else
        Debug.Print "Property not set successfully."
    End If
End Sub


CreateQueryDef Method Example (MDB)

This example uses the CreateQueryDef method to create and execute both a temporary and a permanent QueryDef. The GetrstTemp function is required for this procedure to run.

Sub CreateQueryDefX()

    Dim dbsNorthwind As Database
    Dim qdfTemp As QueryDef
    Dim qdfNew As QueryDef

    Set dbsNorthwind = OpenDatabase("Northwind.mdb")

    With dbsNorthwind
        ' Create temporary QueryDef.
        Set qdfTemp = .CreateQueryDef("", _
            "SELECT * FROM Employees")
        ' Open Recordset and print report.
        GetrstTemp qdfTemp
        ' Create permanent QueryDef.
        Set qdfNew = .CreateQueryDef("NewQueryDef", _
            "SELECT * FROM Categories")

' Open Recordset and print report.
        GetrstTemp qdfNew
        ' Delete new QueryDef because this is a demonstration.
        .QueryDefs.Delete qdfNew.Name
        .Close
    End With

End Sub

Function GetrstTemp(qdfTemp As QueryDef)

    Dim rstTemp As Recordset

    With qdfTemp
        Debug.Print .Name
        Debug.Print "    " & .SQL
        ' Open Recordset from QueryDef.
        Set rstTemp = .OpenRecordset(dbOpenSnapshot)

        With rstTemp
            ' Populate Recordset and print number of records.

.MoveLast
            Debug.Print "    Number of records = " & _
                .RecordCount
            Debug.Print
            .Close
        End With

    End With

End Function


CreateRelation Method Example (MDB)

The following example creates a new Relation object that defines a relationship between a Categories table and a Products table. The Categories table is the primary table in the relationship, and the Products table is the foreign table. The CategoryID field is the primary key in the Categories table, and a foreign key in the Products table.

To test this example in the Northwind sample database, click Relationships on the Tools menu, and delete the relationship between the Categories table and the Products table. Close the Relationships window, saving the current configuration at the prompt. Run the following procedure. Then view the Relationships window again to see the new relationship.

Sub NewRelation()
    Dim dbs As Database, rel As Relation, fld As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create new Relation object and specify foreign table.
    Set rel = dbs.CreateRelation("CategoryProducts", _
        "Categories", "Products")
    ' Set attributes to enforce referential integrity.
    rel.Attributes = dbRelationUpdateCascade And _
        dbRelationDeleteCascade
    ' Create field in Relation object.
    Set fld = rel.CreateField("CategoryID")
    ' Specify field name in foreign table.
    fld.ForeignName = "CategoryID"
    ' Append Field object to Fields collection of Relation object.
    rel.Fields.Append fld
    ' Append Relation object to Relations collection.
    dbs.Relations.Append rel
    dbs.Relations.Refresh
    Set dbs = Nothing
End Sub


Create a new SQL database

The Create Method is not supported by the SQL Server provider for OLEDB and ADO in Microsoft Access 2000. However, you can create a new SQL database in Visual Basic using the Create Database SQL keywords in conjunction with the ADO Command object.


CreateTableDef Method Example (MDB)

The following example creates a new TableDef object and appends it to the TableDefs collection of the current database.

Sub NewTable()
    Dim dbs As Database, tdf As TableDef, fld As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return TableDef object variable that points to new table.
    Set tdf = dbs.CreateTableDef("Contacts")
    ' Define new field in table.
    Set fld = tdf.CreateField("ContactName", dbText, 40)
    ' Append Field object to Fields collection of TableDef object.
    tdf.Fields.Append fld
    tdf.Fields.Refresh
    ' Append TableDef object to TableDefs collection of database.
    dbs.TableDefs.Append tdf
    dbs.TableDefs.Refresh
    Set dbs = Nothing
End Sub


CreateUser Method (MDB)

Once you have created a new User object and appended it to the Users collection of a Workspace or Group object, you can verify that the new user exists by examining the Name list box on the Users tab of the User And Group Accounts dialog box. This dialog box is available by pointing to Security on the Tools menu and clicking User and Group Accounts.


Creating Table Indexes Example

The following example creates a new Index object on an Employees table. The new index consists of two fields, LastName and FirstName.

Note A reference to "Microsoft ADO ext. 2.1 for DDL and Security" must be set to use this example.

Sub NewIndex()
    Dim cat As New ADOX.Catalog, tbl As ADOX.Table
    Dim idx As New ADOX.Index

    ' Return reference to current database.
    Set cat.ActiveConnection = CurrentProject.Connection
    ' Return reference to Employees table.
    Set tbl = cat.Tables!Employees
    ' Return reference to new index.
    idx.Name = "FullName"
    idx.Columns.Append "LastName", adVarWChar
    idx.Columns.Append "FirstName", adVarWChar
    tbl.Indexes.Append idx

    ' Append Index object and refresh collection.
    tbl.Indexes.Refresh
    Set cat = Nothing
End Sub


CurrentDb Method Example

The following example uses the CurrentDb method to return a Database object variable pointing to the current database. It then enumerates all the fields in the Employees table in that database.

Sub ListFields()
    Dim dbs As Database, tdf As TableDef, fld As Field

    ' Return Database object variable pointing to current database.
    Set dbs = CurrentDb
    ' Return TableDef object variable pointing to Employees table.
    Set tdf = dbs.TableDefs!Employees
    ' Enumerate fields in Employees table.
    For Each fld In tdf.Fields
        Debug.Print fld.Name
    Next fld
End Sub


Close Method Example (MDB)

The following example creates a Database object that points to the current database and opens a table-type Recordset object based on a Customers table in the database. The procedure uses the Close method on the Recordset object variable to free the memory resources it has been using. It uses the Set statement with the Nothing keyword to free resources used by the Database object variable.

You can also use the Close method of the Database object to close it and free memory. The Close method of the Database object doesn't actually close the database that's open in Microsoft Access; it only frees the resources used by the Database object variable.

Using an object's Close method and setting the object variable to Nothing are equivalent ways to free memory.

Sub UseClose()
    Dim dbs As Database, rst As Recordset

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create table-type recordset.
    Set rst = dbs.OpenRecordset("Customers")
    .
    .
    .
    ' Close recordset to free memory.
    rst.Close
    ' Free memory used by object variable.
    Set dbs = Nothing
End Sub


Refresh Method Example (MDB)

The following example refreshes the Indexes collection of a TableDef object. In a database in a multiuser environment, you can use the Refresh method to show changes made by other users to the Index objects in a TableDef object's Indexes collection.

Sub RefreshIndex()
    Dim dbs As Database, tdf As TableDef
    Dim idx As Index, fld As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Employees
    tdf.Indexes.Refresh
    For Each idx In tdf.Indexes
        Debug.Print idx.Name; ":"
        For Each fld In idx.Fields
            Debug.Print "   "; fld.Name
        Next fld
    Next idx
    Set dbs = Nothing
End Sub


DefaultControl Method Example

The following example creates a new form and uses the DefaultControl method to return a Control object representing the default command button. The procedure sets some of the default properties for the command button, then creates a new command button on the form.

Sub SetDefaultProperties()
    Dim frm As Form, ctlDefault As Control, ctlNew As Control

    ' Create new form.
    Set frm = CreateForm
    ' Return Control object representing default command button.
    Set ctlDefault = frm.DefaultControl(acCommandButton)
    ' Set some default properties.
    With ctlDefault
        .FontWeight = 700
        .FontSize = 12
        .Width = 3000
        .Height = 1000
    End With
    ' Create new command button.
    Set ctlNew = CreateControl(frm.Name, acCommandButton, , , , 500, 500)
    ' Set control's caption.
    ctlNew.caption = "New Command Button"
    ' Restore form.
    DoCmd.Restore
End Sub


DefaultWorkspaceClone Method 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
        Debug.Print ">>>"; prp.Name; "   "; prp.Value
    Next prp
End Sub


Delete Method Example

The following example creates a column in a table and then deletes it.

Sub DeleteColumn()
    Dim cat As New ADOX.Catalog, tbl As ADOX.Table

    ' Return reference to current database.
    Set cat.ActiveConnection = CurrentProject.Connection
    Set tbl = cat.Tables!Employees
    ' Append new Column object.
    tbl.Columns.Append "MiddleInitial", adVarWChar, 2
    tbl.Columns.Refresh
    ' Delete new Column object.
    tbl.Columns.Delete "MiddleInitial"
tbl.Columns.Refresh
    Set cat = Nothing
End Sub


DeleteLines Method, Lines Property 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_DeleteWholeLine
End 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 If
End Sub


Delete Method Example (MDB)

The following example creates a field in a table and then deletes the field:

Sub DeleteField()
    Dim dbs As Database, tdf As TableDef
    Dim fldInitial As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Employees
    ' Create new Field object.
    Set fldInitial = tdf.CreateField("MiddleInitial", dbText, 2)
    ' Append new Field object.
    tdf.Fields.Append fldInitial
    ' Refresh Fields collection.
    tdf.Fields.Refresh
    ' Delete new Field object.
    tdf.Fields.Delete fldInitial.Name
    tdf.Fields.Refresh
    Set dbs = Nothing
End Sub


Dropdown Method Example

The following example shows how you can use the Dropdown method within the GotFocus event procedure to force a combo box named SupplierID to drop down when it receives the focus.

Private Sub SupplierID_GotFocus()
    Me!SupplierID.Dropdown
End Sub


Echo Method (Application 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 False
End Sub


Edit Method Example (MDB)

The following example opens a Recordset object and locates each record satisfying the search criteria for the Title field. The procedure then uses the Edit method to prepare the record for subsequent editing, changes the job title, and saves the change.

Sub ChangeTitle()
    Dim dbs As Database, rst As Recordset
    Dim strCriteria As String, strNewTitle As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Set search criteria.
    strCriteria = "Title = 'Sales Representative'"
    strNewTitle = "Account Executive"
    ' Create dynaset-type Recordset object.
    Set rst = dbs.OpenRecordset("Employees", dbOpenDynaset)
    ' Find first occurrence.
    rst.FindFirst strCriteria
    ' Loop until no matching records.
    Do Until rst.NoMatch
        With rst
            .Edit                            ' Enable editing.
            !Title = strNewTitle    ' Change title.
            .Update                        ' Save changes.
            .FindNext strCriteria    ' Find next occurrence.
        End With
    Loop
    rst.Close
    Set dbs = Nothing
End Sub

Tip Using an update query to alter data is more efficient. For example, you can use the following code to achieve the same results:

Sub ChangeTitleSQL()
    Dim dbs As Database
    Dim strSQL As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create SQL string.
    strSQL = "UPDATE Employees SET Title = 'Account Executive' " _
        & "WHERE Title = 'Sales Representative' "
    ' Run action query.
    dbs.Execute strSQL
    ' Return number of records updated.
    Debug.Print dbs.RecordsAffected
    Set dbs = Nothing
End Sub


Execute Method Example

The following example executes an SQL string and prints the number of records affected:

Sub RecordsUpdated()
    Dim intRecordsAffected As Integer
    Dim strSQL As String

    strSQL = "UPDATE Employees SET Title = " _
        & "'Senior Sales Representative' " _
        & "WHERE Title = 'Sales Representative';"

    CurrentProject.Connection.Execute strSQL, intRecordsAffected
    Debug.Print intRecordsAffected
End Sub


Execute Method Example (MDB)

The following example executes an action query and prints the number of records affected:

Sub RecordsUpdated()
    Dim dbs As Database, qdf As QueryDef
    Dim strSQL As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    strSQL = "UPDATE Employees SET Title = " _
        & "'Senior Sales Representative' " _
        & "WHERE Title = 'Sales Representative';"
    ' Create new QueryDef.
    Set qdf = dbs.CreateQueryDef("UpdateTitles", strSQL)
    ' Execute QueryDef.
    qdf.Execute
    Debug.Print qdf.RecordsAffected
    Set dbs = Nothing
End Sub


FieldSize Property Example

FieldSize Property Example (MDB)

The following example uses the FieldSize property to return the size in bytes of two fields in an Employees table. The Notes field contains Memo data and the Photo field contains Long Binary (OLE Object) data.

Sub GetFieldSize()
    Dim dbs As Database, rst As Recordset
    Dim fldNotes As Field, fldPhoto As Field
    Dim strSQL As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Construct SQL statement to return Notes and Photo fields.
    strSQL = "SELECT Notes, Photo FROM Employees;"
    ' Create dynaset-type Recordset object.
    Set rst = dbs.OpenRecordset(strSQL)
    Set fldNotes = rst!Notes
    Set fldPhoto = rst!Photo
    ' Move to first record.
    rst.MoveFirst
    Debug.Print "Size of Notes:"; "    "; "Size of Photo:"
    ' Print sizes of fields for each record in Recordset object.
    Do Until rst.EOF
        Debug.Print fldNotes.FieldSize; "    "; fldPhoto.FieldSize
        rst.MoveNext
    Loop
    rst.Close
    Set dbs = Nothing
End Sub


Find Method

The ActiveX Data Objects (ADO) version of the Find Method supports only singular column searches. As a result, using the "And" or "Or" keywords to append criteria will not work.

Creating a new recordset will frequently provide better performance and does not limit you to single column filters.

Right:
rs.Find "FirstName = 'Nancy'"

Wrong:
rs.Find "FirstName = 'Nancy' And LastName = 'Davolio'"


Find Method Example

The following example creates a dynaset-type Recordset object and then uses the Find method to locate the first record satisfying the specified criteria. The procedure then finds the remaining records that satisfy the criteria.

Sub FindRecord()
    Dim rst As New ADODB.Recordset
    Dim strCriteria As String

    ' Define search criteria.
    strCriteria = "[ShipCountry] = 'UK'"
    ' Create a dynaset-type Recordset object based on Orders table.
    rst.Open "Orders", CurrenProject.Connection, adOpenKeyset, adLockOptimistic)
    ' Find first matching record.
    rst.Find strCriteria
    ' Check if record is found.
    If rst.EOF Then
        MsgBox "No record found."
    Else
        ' Find other matching records.
        Do Until rst.EOF
            Debug.Print rst!ShipCountry; "   "; rst!OrderDate
            rst.Find strCriteria
        Loop
    End If
    rst.Close
End Sub


FindFirst, FindLast, FindNext, FindPrevious Methods Example (MDB)

The following example creates a dynaset-type Recordset object and then uses the FindFirst method to locate the first record satisfying the specified criteria. The procedure then finds the remaining records that satisfy the criteria.

Sub FindRecord()
    Dim dbs As Database, rst As Recordset
    Dim strCriteria As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Define search criteria.
    strCriteria = "[ShipCountry] = 'UK' And " _
        & "[OrderDate] >= #1-1-95#"
    ' Create a dynaset-type Recordset object based on Orders table.
    Set rst = dbs.OpenRecordset("Orders", dbOpenDynaset)
    ' Find first matching record.
    rst.FindFirst strCriteria
    ' Check if record is found.
    If rst.NoMatch Then
        MsgBox "No record found."
    Else
        ' Find other matching records.
        Do Until rst.NoMatch
            Debug.Print rst!ShipCountry; "   "; rst!OrderDate
            rst.FindNext strCriteria
        Loop
    End If
    rst.Close
    Set dbs = Nothing
End Sub


Find, ReplaceLine Methods Example

The following function finds a specified string in a module and replaces the line that contains that string with a new specified line.

Function FindAndReplace(strModuleName As String, _
    strSearchText As String, _
    strNewText As String) As Boolean
    Dim mdl As Module
    Dim lngSLine As Long, lngSCol As Long
    Dim lngELine As Long, lngECol As Long
    Dim strLine As String, strNewLine As String
    Dim intChr As Integer, intBefore As Integer, _
        intAfter As Integer
    Dim strLeft As String, strRight As String

    ' Open module.
    DoCmd.OpenModule strModuleName
    ' Return reference to Module object.
    Set mdl = Modules(strModuleName)

    ' Search for string.
    If mdl.Find(strSearchText, lngSLine, lngSCol, lngELine, _
        lngECol) Then
        ' Store text of line containing string.
        strLine = mdl.Lines(lngSLine, Abs(lngELine - lngSLine) + 1)
        ' Determine length of line.
        intChr = Len(strLine)
        ' Determine number of characters preceding search text.
        intBefore = lngSCol - 1
        ' Determine number of characters following search text.
        intAfter = intChr - CInt(lngECol - 1)
        ' Store characters to left of search text.

        strLeft = Left$(strLine, intBefore)
        ' Store characters to right of search text.
        strRight = Right$(strLine, intAfter)
        ' Construct string with replacement text.
        strNewLine = strLeft & strNewText & strRight
        ' Replace original line.
        mdl.ReplaceLine lngSLine, strNewLine
        FindAndReplace = True
    Else
        MsgBox "Text not found."
        FindAndReplace = False
    End If

Exit_FindAndReplace:
    Exit Function

Error_FindAndReplace:

MsgBox Err & ": " & Err.Description
    FindAndReplace = False
    Resume Exit_FindAndReplace
End Function


FollowHyperlink Method Example

The following function prompts a user for a hyperlink address and then follows the hyperlink:

Function GetUserAddress() As Boolean
    Dim strInput As String

    On Error GoTo Error_GetUserAddress
    strInput = InputBox("Enter a valid address")
    Application.FollowHyperlink strInput, , True
    GetUserAddress = True

Exit_GetUserAddress:
    Exit Function

Error_GetUserAddress:
    MsgBox Err & ": " & Err.Description
    GetUserAddress = False
    Resume Exit_GetUserAddress
End Function

You could call this function with a procedure such as the following:

Sub CallGetUserAddress()
    If GetUserAddress = True Then
        MsgBox "Successfully followed hyperlink."
    Else
        MsgBox "Could not follow hyperlink."
    End If
End Sub


Follow Method Example

The following example sets the HyperlinkAddress property of a command button and then opens the hyperlink when the form is loaded.

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

Private Sub Form_Load()
    Dim ctl As CommandButton

    Set ctl = Me!Command0
    With ctl
        .Visible = False
        .HyperlinkAddress = "http://www.microsoft.com/"
        .Hyperlink.Follow
    End With
End Sub


GetChunk Method

After assigning the results of the GetChunk method to a string variable, you can use the Visual Basic Len function to determine the number of characters in the string. Or you can use the LenB function to determine the number of bytes used to represent that string.


GetRows Method Example

The following example uses the GetRows method to return a two-dimensional array containing all rows of data in a Recordset object:

Sub RowsArray()
    Dim rst As New ADODB.Recordset, strSQL As String
    Dim varRecords As Variant, intI As Integer, intJ As Integer

    ' Build SQL statement that returns specified fields.
    strSQL = "SELECT FirstName, LastName, HireDate " _
        & "FROM Employees"
    ' Open dynaset-type Recordset object.
    rst.Open strSQL, CurrentProject.Connection, adOpenKeyset, adLockOptimistic
    ' Move to end of recordset.
    rst.MoveLast
    ' Return to first record.
    rst.MoveFirst
    ' Return all rows into array.
    varRecords = rst.GetRows(rst.RecordCount)
    ' Find upper bound of second dimension.
    For intI = 0 To UBound(varRecords, 2)
        Debug.Print
        ' Find upper bound of first dimension.
        For intJ = 0 To UBound(varRecords, 1)
            ' Print data from each row in array.
            Debug.Print varRecords(intJ, intI)
        Next intJ
    Next intI
    rst.Close

End Sub


GetRows Method Example (MDB)

The following example uses the GetRows method to return a two-dimensional array containing all rows of data in a Recordset object:

Sub RowsArray()
    Dim dbs As Database, rst As Recordset, strSQL As String
    Dim varRecords As Variant, intI As Integer, intJ As Integer

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Build SQL statement that returns specified fields.
    strSQL = "SELECT FirstName, LastName, HireDate " _
        & "FROM Employees"
    ' Open dynaset-type Recordset object.
    Set rst = dbs.OpenRecordset(strSQL)
    ' Move to end of recordset.
    rst.MoveLast
    ' Return to first record.
    rst.MoveFirst
    ' Return all rows into array.
    varRecords = rst.GetRows(rst.RecordCount)
    ' Find upper bound of second dimension.
    For intI = 0 To UBound(varRecords, 2)
        Debug.Print
        ' Find upper bound of first dimension.
        For intJ = 0 To UBound(varRecords, 1)
            ' Print data from each row in array.
            Debug.Print varRecords(intJ, intI)
        Next intJ
    Next intI
    rst.Close
    Set dbs = Nothing
End Sub


 GetOption, SetOption Methods

GetOption, SetOption Methods

Language-specific information

Use these methods to inspect or set any of the options in the Options dialog box (Tools menu). This includes all of the options in the Right-to-Left tab that have been implemented for right-to-left and bidirectional use.


GetOption, SetOption Methods Example

The following example uses the GetOption method to return the Default Field Type option setting from the Tables/Queries tab of the Options dialog box and then saves the setting in a variable. If the Default Field Type option isn't currently set to Text, Microsoft Access displays a dialog box asking the user whether it should set the option to Text. If the user clicks Yes, the SetOption method changes the option.

Sub ChangeFieldSize()
    ' Constant represents Text setting of Default
    ' Field Type option.
    Const conText = 0

    Dim varSize As Variant, intResponse As Integer
    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 If
End Sub


GoToPage Method (Application Object) 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


HyperlinkPart Method Example

The following example uses all four of the part argument constants to display information returned by the HyperlinkPart method 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 example:

DisplayHyperlinkParts "MyHyperlinkTableName", "MyHyperlinkFieldName"

Sub DisplayHyperlinkParts(strTable As String, strField As String)
    Dim rst As New ADODB.Recordset
    Dim strMsg As String

    rst.Open(strTable,currentproject.connection,_
        adOpenForwardOnly, adLockReadOnly)

    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) _
            & vbCrLf & "ScreenTip = " _
            & HyperlinkPart(rst(strField), acScreenTip) _
            & vbCrLf & "Full Address = " _
            & HyperlinkPart(rst(strField), acFullAddress)
        ' Show parts returned by HyperlinkPart function.
        MsgBox strMsg
        rst.MoveNext
    Wend
End Sub

When you use the HyperlinkPart method in a query, the part argument is required. For example, the following SQL statement uses the HyperlinkPart method 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 SubAddr, HyperlinkPart([URL],4)
AS ScreenTip
FROM Links;


InsertText Method 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_InsertProc
End Function


Line Method Example

The following example uses the Line method to draw a red rectangle five pixels inside the edge of a report named EmployeeReport. The RGB function is used to make the line red.

To try this example in Microsoft Access, create a new report. 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
    DrawLine
End 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.
    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, B
End Sub


Move Method Example

The following example uses the Move method to move forward two rows in a Recordset object:

Sub MoveForward()
    Dim rst As New ADODB.Recordset
    Dim strCriteria As String

    ' Open dynaset-type Recordset object.
    rst.Open "SELECT * FROM Orders ORDER BY ShipCountry;" _
, currentProject.connection, adOpenKeyset, adLockOptimistic
    rst.MoveLast
    rst.MoveFirst
    ' Check number of records in Recordset object.
    If rst.RecordCount > 2 Then
        ' Move forward two rows.
        rst.Move 2
        Debug.Print rst!ShipCountry
    End If
    rst.Close
End Sub


MoveFirst, MoveLast, MoveNext, MovePrevious Methods Example

The following example uses the MoveLast method to populate the Recordset object so the number of records can be counted. The MoveFirst method then moves the current record pointer to the first record in the Recordset object. The procedure prompts the user to enter a number, then moves that number of records forward.

Sub MoveThroughRecords()
    Dim rst As New ADODB.Recordset, intI As Integer
    Dim intNumber As Integer

    rst.Open "Products", CurrentProject.Connection, adOpenKeyset, adLockOptimistic
    ' Populate Recordset object.
    rst.MoveLast
    ' Return to first record.
    rst.MoveFirst
    ' Get number smaller than number of records.
    intNumber = InputBox("Please enter a number less than " _
        & rst.RecordCount & ".")
    ' Move specified number of records.
    For intI = 1 To intNumber
        rst.MoveNext
    Next intI
    Debug.Print rst!ProductName
    rst.Close

End Sub


MoveFirst, MoveLast, MoveNext, MovePrevious Methods Example (MDB)

The following example uses the MoveLast method to populate the Recordset object so the number of records can be counted. The MoveFirst method then moves the current record pointer to the first record in the Recordset object. The procedure prompts the user to enter a number, then moves that number of records forward.

Sub MoveThroughRecords()
    Dim dbs As Database, rst As Recordset, intI As Integer
    Dim strNumber As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    Set rst = dbs.OpenRecordset("Products")
    ' Populate Recordset object.
    rst.MoveLast
    ' Return to first record.
    rst.MoveFirst
    ' Get number smaller than number of records.
    strNumber = InputBox("Please enter a number less than " _
        & rst.RecordCount & ".")
    ' Move specified number of records.
    For intI = 1 To strNumber
        rst.MoveNext
    Next intI
    Debug.Print rst!ProductName
    rst.Close
    Set dbs = Nothing
End Sub


Move Method Example (MDB)

The following example uses the Move method to move forward two rows in a Recordset object:

Sub MoveForward()
    Dim dbs As Database, rst As Recordset
    Dim strCriteria As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Open dynaset-type Recordset object.
    Set rst = dbs.OpenRecordset("SELECT * FROM Orders " _
        & "ORDER BY ShipCountry;")
    rst.MoveLast
    rst.MoveFirst
    ' Check number of records in Recordset object.
    If rst.RecordCount > 2 Then
        ' Move forward two rows.
        rst.Move 2
        Debug.Print rst!ShipCountry
    End If
    rst.Close
    Set dbs = Nothing
End Sub


NewCurrentDatabase 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 a COM component. For example, you might run the following code from Microsoft Excel, Microsoft Visual Basic, or 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 Object, tdf As Object, fld As Variant
    Dim strDB As String
    Const DB_Text As Long = 10
    Const FldLen As Integer = 40

    ' Initialize string to database path.
    strDB = "C:\My Documents\Newdb.mdb"
    ' Create new instance of Microsoft Access.
    Set appAccess = _
        CreateObject("Access.Application.9")
    ' 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. _
        CreateField("CompanyName", DB_Text, FldLen)
    ' Append Field and TableDef objects.
    tdf.Fields.Append fld
    dbs.TableDefs.Append tdf
    Set appAccess = Nothing
End Sub


OpenDatabase Method Example

Open Method Example

The following example returns a Connection variable that points to the current connection. Then it opens a different connection called Another.mdb by using the Open method. The procedure then enumerates all Table objects in both databases.

To try this example, create a new database called Another.mdb, close it, and place it in the same directory as the database from which you are running the code.

Sub OpenAnother()
    Dim cat As New ADOX.Catalog, catAnother As New ADOX.Catalog
    Dim cnnAnother As New ADODB.Connection
    Dim tbl As ADOX.Table

    ' Return reference to current database.
    Set cat.ActiveConnection = CurrentProject.Connection
cnnAnother.Provider = "Microsoft.Jet.OLEDB.4.0"     cnnAnother.Open "DATA SOURCE=Another.mdb"
    ' Return reference to Another.mdb.
    Set catAnother.ActiveConnection = cnnAnother
    ' Enumerate all Table objects in each database.
    Debug.Print CurrentProject.Connection.Properties("Data Source Name") & ":"
    For Each tbl In cat.Tables
        Debug.Print tbl.Name
    Next tbl
    Debug.Print vbCrLf & cnnAnother.Properties("Data Source Name") & ":"
    For Each tbl In catAnother.Tables
        Debug.Print tbl.Name
    Next tbl
    Set cat = Nothing
    Set cnnAnother = Nothing
    Set catAnother = Nothing
End Sub

Note If running this code in an ADP the provider will have to be set to "SQLOLEDB.1" and the ConnectionString parameter for the connection's OPEN method will need to be set to point to a SQL database.

The following example opens a keyset-type Recordset object and prints the number of records in the Recordset object.

Sub UKOrders()
    Dim rst As New ADODB.Recordset
    Dim strSQL As String

    strSQL = "SELECT * FROM Orders WHERE [ShipCountry] = 'UK'"
    rst.Open strSQL, CurrentProject.Connection, adOpenKeyset, adLockOptimistic
    rst.MoveLast
    Debug.Print rst.RecordCount
    rst.Close
End Sub


 OpenConnection Method

OpenConnection Method

You can use the OpenConnection method to open an ADO connection to an existing Microsoft Access project (.adp) or Access database (.mdb) as the current Access project or database in the Microsoft Access window.

Syntax

object.OpenConnection [baseconnectionstring][, userid][, password]

The OpenConnection method has the following arguments.

Argument | Description
object | The CurrentProject or CodeProjectobject.
baseconnectionstring | A string expression that is the base connection string of the database.
userid | A string expression that is the name of the existing Access project, 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.adp
password | Note If you don't supply the filename extension, .adp is appended to the filename. You can use this method or the OpenCurrentDatabase method to open .adp files.

Remarks

The OpenConnection method is similar to the Open method of an ADO Connection object. This method establishes the physical connection to the data source. After this method successfully completes, the connection is live, the Connection and BaseConnectionString properties are set, and the Database window or data access page should be repopulated with data from the new connection. All parameters of this method are optional. If no base connection string is supplied, then the connection is re-established using the previous base connection string (but the user must call CloseConnection before calling OpenConnection again). In the case of an Access project, the BaseConnectionString property can only specify the SQL Server OLE DB Provider.


OpenCurrentDatabase Method 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 a COM component. For example, you might run the following code from Microsoft Excel, Microsoft Visual Basic, or 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()
    ' Initialize string to database path.
    Const strConPathToSamples = "C:\Program " _
        & "Files\Microsoft Office\Office\Samples\Northwind.mdb"

    strDB = strConPathToSamples & "Northwind.mdb"
    ' Create new instance of Microsoft Access.
    Set appAccess = _
        CreateObject("Access.Application")
    ' Open database in Microsoft Access window.
    appAccess.OpenCurrentDatabase strConPathToSamples
    ' Open Orders form.
    appAccess.DoCmd.OpenForm "Orders"
End Sub


OpenDatabase Method (MDB)

In Microsoft Access, use the CurrentDb function to return a reference to the current database and assign it to a Database variable, as shown in the following example.

Dim dbsCurrent As Database
Set dbsCurrent = CurrentDb

Use the OpenDatabase method to open a database other than the current database from Visual Basic.


OpenDatabase Method Example (MDB)

The following example returns a Database variable that points to the current database. Then it opens a different database called Another.mdb by using the OpenDatabase method. The procedure then enumerates all TableDef objects in both databases.

To try this example, create a new database called Another.mdb, close it, and place it in the same directory as the database from which you are running the code.

Sub OpenAnother()
    Dim wsp As Workspace
    Dim dbs As Database, dbsAnother As Database
    Dim tdf As TableDef

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to default workspace.
    Set wsp = DBEngine.Workspaces(0)
    ' Return reference to Another.mdb.
    Set dbsAnother = wsp.OpenDatabase("Another.mdb")
    ' Enumerate all TableDef objects in each database.
    Debug.Print dbs.Name & ":"
    For Each tdf in dbs.TableDefs
        Debug.Print tdf.Name
    Next tdf
    Debug.Print
    Debug.Print dbsAnother.Name & ":"
    For Each tdf in dbsAnother.TableDefs
        Debug.Print tdf.Name
    Next tdf
    Set dbs = Nothing
    Set dbsAnother = Nothing
End Sub


OpenRecordset Method Example (MDB)

The following example opens a dynaset-type Recordset object and prints the number of records in the Recordset object.

Sub UKOrders()
    Dim dbs As Database, rst As Recordset
    Dim strSQL As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    strSQL = "SELECT * FROM Orders WHERE [ShipCountry] = 'UK'"
    Set rst = dbs.OpenRecordset(strSQL)
    rst.MoveLast
    Debug.Print rst.RecordCount
    rst.Close
    Set dbs = Nothing
End Sub


Print Method

The Visual Basic Print method applies only to the Debug object in Microsoft Access, never to a Form object. The Debug object is required when you use the Print method in Microsoft Access.

Don't confuse the Visual Basic Print method with the Microsoft Access Print method, which applies only to a Report object.


Print Method 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 strMessage
End Sub


PSet Method Example

The following example uses the PSet method to draw a line through the horizontal axis of a report.

To try this example in Microsoft Access, create a new report. 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 intI
End Sub


Quit Method (Application 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 acPrompt
End Sub


 Raise Method

Raise Method

The Raise method raises a specified Visual Basic error. The properties of the Err object are set as though the error had actually occurred in running code. However, this works only for Visual Basic errors, not for Microsoft Access errors or Microsoft Jet database engine errors.

If you use the Raise method with an error number reserved by Microsoft Access or by the Jet database engine, the value of the Err object's Description property is "Application-defined or object-defined error." To determine the descriptive string for a Microsoft Access or Jet database engine error that hasn't actually occurred in running code, use the AccessError method.

The AccessError method takes a Long value that represents an error number and returns the descriptive string associated with the error.


Recalc Method Example

The following example uses the Recalc method to update controls on an Orders form. This form includes the Freight text box, which displays the freight cost, and a calculated control that displays the total cost of an order including freight. If the statement containing the Recalc method is placed in the AfterUpdate event procedure for the Freight text box, the total cost of an order is recalculated every time a new freight amount is entered.

Sub Freight_AfterUpdate()
    Me.Recalc
End Sub


Refresh Method Example

The following example refreshes the Indexes collection of a Table object. In a database in a multiuser environment, you can use the Refresh method to show changes made by other users to the Index objects in a Table object's Indexes collection.

Sub RefreshIndex()
    Dim cat As New ADOX.Catalog, tbl As ADOX.Table
    Dim idx As ADOX.Index, clm As ADOX.Column

    ' Return reference to current database.
    Set cat.ActiveConnection = CurrentProject.Connection
    Set tbl = cat.Tables!Employees
    tbl.Indexes.Refresh
    For Each idx In tbl.Indexes
        Debug.Print idx.Name; ":"
        For Each clm In idx.Columns
            Debug.Print "   "; clm.Name
        Next clm
    Next idx
    Set cat = Nothing
End Sub


RefreshDatabaseWindow 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"
    RefreshDatabaseWindow
End Sub


RefreshTitleBar Method Example

The following example sets the AppTitle property of the current database and applies the RefreshTitleBar method to update the title bar.

Sub ChangeTitle()
    Dim obj As Object
    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

ErrorHandler:
    If Err.Number = conPropNotFoundError Then
        Set obj = dbs.CreateProperty("AppTitle", dbText, "Contacts Database")
        dbs.Properties.Append obj
    Else
        MsgBox "Error: " & Err.Number & vbCrLf & Err.Description
    End If
    Resume Next
End Sub


Refresh Method Example

The following example uses the Refresh method to update the records in the underlying record source for the form Customers whenever the form receives the focus:

Private Sub Form_Activate()
    Me.Refresh
End Sub


Remove Method (References Collection) 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.

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_AddReference
End 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_RemoveReference
End Function


Repaint Method Example

The following example uses the Repaint method to repaint a form when the form receives the focus:

Private Sub Form_Activate()
    Me.Repaint
End Sub


Requery Method (Control or Form Object) Example

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.Requery
End Sub


 Reset Method

Reset Method

In Microsoft Access 2000, you can use the Toolbar Properties sheet to reset a built-in menu bar or toolbar. Point to Toolbars on the View menu and click Customize, then click the Properties button in the Customize dialog box. Select the built-in menu bar or toolbar you want in the Selected Toolbar box, and then click the Restore Defaults button. You can't reset a custom menu bar or toolbar, or a specific shortcut menu.

The Reset button in the Customize dialog box resets the selected built-in menu bar or toolbar, or all built-in shortcut menus if you select Shortcut Menus in the Customize dialog box. The Reset command on the shortcut menu that's displayed when you right-click a particular built-in control on a menu bar or toolbar while the Customize dialog box is open resets that control to its original state. The Reset button and Reset command are equivalent to the Reset method.

The Restore Defaults button not only resets the menu bar or toolbar controls' image, text, and the commands they run, but also restores all of the original settings for the menu bar or toolbar, including its original position and visibility.


Open Method (Recordset)

In Microsoft Access, use the Connection property of the CurrentProject object to reference the open connection of the current database, as shown in the following exampl.

Dim rsCurrent As ADODB.Recordset
rsCurrent.Open "Select * From Employees", _
    CurrentProject.Connection


RunCommand Method 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_OpenOptionsDialog
End Function


Run Method Example

The following example runs a user-defined Sub procedure in a module in a Microsoft Access database from another application that acts as an 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 9.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.9")
    ' Open WizCode database in Microsoft Access window.
    appAccess.OpenCurrentDatabase "C:\My Documents\WizCode.mdb", False
    ' Run Sub procedure.
    appAccess.Run "Greeting", "Joe"
    Set appAccess = Nothing
End Sub


Scale Method 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)
    DrawCircle
End 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


Seek Method Example (MDB)

The following example creates a new Index object on an Employees table. The new index consists of two fields, LastName and FirstName. The procedure then uses the Seek method to find a specified record.

Sub NewIndex()
    Dim dbs As Database, tdf As TableDef, idx As Index
    Dim fldLastName As Field, fldFirstName As Field, _
        rst As Recordset

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Employees table.
    Set tdf = dbs.TableDefs!Employees
    ' Return Index object that points to new index.
    Set idx = tdf.CreateIndex("FullName")
    ' Create and append index fields.
    Set fldLastName = idx.CreateField("LastName", dbText)
    Set fldFirstName = idx.CreateField("FirstName", dbText)
    idx.Fields.Append fldLastName
    idx.Fields.Append fldFirstName
    ' Append Index object.
    tdf.Indexes.Append idx
    tdf.Indexes.Refresh
    ' Open table-type Recordset object.
    Set rst = dbs.OpenRecordset("Employees")
    ' Set current index to new index.
    rst.Index = idx.Name
    ' Specify record to find.
    rst.Seek "=", "Fuller", "Andrew"
    If rst.NoMatch Then
        Debug.Print "Seek unsuccessful!"
    Else
        Debug.Print "Seek successful."
    End If
    rst.Close
    Set dbs = Nothing
End Sub


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


SetPermissions Method

The SetPermissions method uses the following parameters in Microsoft Access

Object | ObjectType | ObjectTypeID
Forms | adPermObjProviderSpecific | {c49c842e-9dcb-11d1-9f0a-00c04fc2c2e0}
Reports | adPermObjProviderSpecific | {c49c8430-9dcb-11d1-9f0a-00c04fc2c2e0}
DataPages** | N/A | N/A
Macros | adPermObjProviderSpecific | {c49c842f-9dcb-11d1-9f0a-00c04fc2c2e0}
Modules * | adPermObjProviderSpecific | {c49c8432-9dcb-11d1-9f0a-00c04fc2c2e0}
Table | adPermObjTable | N/A
View | adPermObjView | N/A
Procedure | adPermObjProcedure | N/A

**Security is not supported for Datapages

*Security with modules is only available for versions of Microsoft Access prior to Access 2000 and only when used with the latest Jet Provider.


SetPermissions Method Example

The following example shows how to set the permissions for a Microsoft Access form.

Note SetPermissions is not supported in Access projects .(adp) with the version of the SQL provider shipped with Microsoft Access 2000.


SizeToFit Method Example

The following example creates a new form and creates a new command button on the form. The procedure then sets the control's Caption property and sizes the control to fit the caption.

Sub SizeNewControl()
    Dim frm As Form, ctl As Control

    ' Create new form.
    Set frm = CreateForm
    ' Create new command button.
    Set ctl = CreateControl(frm.Name, _
        acCommandButton, , , , 500, 500)
    ' Restore form.
    DoCmd.Restore
    ' Set control's Caption property.
    ctl.Caption = "Extremely Long Control Caption"
    ' Size control to fit caption.
    ctl.SizeToFit
End Sub


SysCmd Method 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 Function
CloseObjects:
    On Error Resume Next
    rst.Close
    dbs.Close
    On Error GoTo 0
    DoCmd.Hourglass False
    Return
End Function

The next example illustrates how you can use the SysCmd method 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.CurrentObjectType
strObjName = Application.CurrentObjectName
intObjState = SysCmd(acSysCmdGetObjectState, intObjType, strObjName)
If intObjState <> 0 Then
    .
    .
    .
End If


TextHeight, TextWidth Methods Example

The following example uses the TextHeight and TextWidth methods to determine the amount of vertical and horizontal space required to print a text string in the report's current font.

To try this example in Microsoft Access, create a new report. Set the OnPrint property of the Detail section to [Event Procedure]. Enter the following code in the report's module, then switch to Print Preview.

Private Sub Detail_Print(Cancel As Integer, _
    PrintCount As Integer)
    ' Set unit of measure to twips (default scale).
    Me.Scalemode = 1
    ' Print name and 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


 TransferText Action/Method

TransferText Action/Method

Language-specific information

When Microsoft Access is enabled for right-to-left functionality, it provides an additional argument for the TransferText method and action. The Code Page argument has been added to the to the text file description.

TransferText method and action has the following additional argument.

Added Arguments | Description
Code Page | The name of the code page to import from, export to, or link to. You can select one of the code page names from the drop-down list.

Syntax

DoCmd.TransferText ([TransferType], [SpecificationName], [TableName], [FileName], [HasFieldNames], [HTMLTableName], [CodePage])

Argument | Description
codepage | Enter the numeric value associated with the desired code page. You can view the supported values in the Code page list box of the TransferText macro action.


Undo Method 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.Undo
End Sub

The next example uses the Undo method to reset all changes to a form before the form is updated.

Private Sub Form_BeforeUpdate(Cancel As Integer)
    Me.Undo
End Sub


 UpdateBatch

UpdateBatch Method

The UpdateBatch method of an ADO recordset can be used to send multiple recordset updates to the server in one call and can significantly reduce process times for some recordset updates. However, this is not the case with Jet databases. When the UpdateBatch method is used with a Jet database (.mdb), Jet still processes each instruction individually therefore, process times using the UpdateBatch method will generally have an opposite adverse affect of actually increasing process times by more than 100 percent.


UseDefaultFolderSuffix Method Example

This example sets the folder suffix for the data access page ("Inventory") to the default suffix.

DataAccessPages("Inventory").WebOptions.UseDefaultFolderSuffix


AccessObjectProperty Object, AccessObjectProperties Collection Example

This illustrates how to add custom properties to a form using the AccessObjectProperties collection and Add method.

Sub AddCustomFormProperty(strFormName As String, _
                                  strPropName As String, _
                                  varPropValue As Variant)
    ' Add custom properties to the AccessObjectProperties
    '  collection that is associated with an AccessObject object.

    With CurrentProject.AllForms(strFormName).Properties
        .Add strPropName, varPropValue
    End With
End Sub


Application Object Example

The following example prints some current property settings of the Application object, sets an option, and then quits the application, saving all objects:

Sub ApplicationInformation()
    ' Print name and type of current object.
    Debug.Print Application.CurrentObjectName
    Debug.Print Application.CurrentObjectType
    ' Set 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 acSaveYes
End Sub

The next example shows how to use Microsoft Access as a COM component. From Microsoft Excel, Visual Basic, or another application that acts as a COM 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 9.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, strReportName
End Sub

Sub PrintAccessReport(strDB As String, _
     strReportName As String)
    ' Return reference to Microsoft Access
    ' Application object.
    Set appAccess = New Access.Application
    ' 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 = Nothing
End Sub


 CodeProject Object

CodeProject Object

The CodeProject object refers to the project for the code database of a Microsoft Access project (.adp) or Access database (.mdb).

Remarks

The CodeProject object has several collections that contain specific AccessObject objects within the code database. The following table lists the name of each collection defined by Access project and the types of objects it contains.

Collections | Object type
AllForms | All forms
AllReports | All reports
AllMacros | All macros
AllModules | All modules
AllDataAccessPages | All data access pages

Note The collections in the preceding table contain all of the respective objects in the database regardless if they are opened or closed.

For example, an AccessObject object representing a form is a member of the AllForms collection, which is a collection of AccessObject objects within the current database. Within the AllForms collection, individual members of the collection are indexed beginning with zero. You can refer to an individual AccessObject object in the AllForms collection either by referring to the form by name, or by referring to its index within the collection. If you want to refer to a specific object in the AllForms collection, it's better to refer to it by name because a item's collection index may change. If the object name includes a space, the name must be surrounded by brackets ([ ]).

Syntax | Example
AllForms!formname | AllForms!OrderForm
AllForms![form name] | AllForms![Order Form]
AllForms("formname") | AllForms("OrderForm")
AllForms(index) | AllForms(0)


 Collection Object

Collection Object

In Microsoft Access, a Collection object can consist of a set of objects of any type. You can create a Collection object that consists of several objects of the same type or objects of different types.

The collection defined by a Collection object can contain any combination of Microsoft Access objects, data access objects, and objects from any other application that exposes its objects to Microsoft Access. You can also add a Collection object to a collection defined by a Collection object.

The collection can also contain user-defined objects that you create in Microsoft Access. For example, you can create user-defined objects with custom methods and properties from a form module or report module. Then you can add these objects to a collection defined by a Collection object, and manipulate them as a set.


CommandBarControls Collection Object

Although most Microsoft Access collections are zero-based, all command bar collections are 1-based. Note, however, that you can use the For Each...Next syntax to iterate through the objects in a collection without having to worry about specific index numbers.


CommandBars Collection Object

Although most Microsoft Access collections are zero-based, all command bar collections are 1-based. Note, however, that you can use the For Each...Next syntax to iterate through the objects in a collection without having to worry about specific index numbers.


Connection Object, Connection Collection

When working with ActiveX Data Objects (ADO) in Microsoft Access, you will often want a Connection object variable that represents the connection to the current database provider. Use the Connection property of the CurrentProject object to return a Connection object for the database you are currently working in. This Connection object is automatically appended to the Connections collection.

For example, suppose you are currently working with the Northwind sample database in Microsoft Access. You can create a Connection object that links to the provider for that database by first declaring a Connection object variable, then pointing it to the Connection object returned by the Connection property of the CurrentProject object.

Dim cnn As ADODB.Connection
Set cnn = CurrentProject.Connection

You don't need to know the name of the provider in order to use the current database. If you want to know the name of the current provider, check the ConnectionString property of the Connection object, which contains the provider name and the to the database. To find its position in the Connections collection, enumerate through the collection.

From Visual Basic code, you can create multiple independent Connection object variables to represent connections to several databases. In this way, you can manipulate more than one database at a time from code. You can also create multiple Connection object variables and point them to the current database.

Note Each reference to the Connection Property returns a new connection object pointing to your active connection. If you want to perform several actions on that connection, such as with transactions, you must assign the Connection to a variable as described above.


 Container Object, Containers Collection (MDB)

Container Object, Containers Collection (MDB)

In addition to the Container objects defined by the Microsoft Jet database engine, the following five Container objects are defined by Microsoft Access.

Container name | Contains information about
Forms | Saved forms
Modules | Saved modules
Reports | Saved reports
DataAccessPages | Saved DataAccessPages
Scripts | Saved macros

The Container objects defined by Microsoft Access are Microsoft Access database objects, not Data Access Objects (DAO). These Container objects provide the Jet database engine with information about Microsoft Access objects. The Jet database engine uses this information to implement security on Microsoft Access database objects in the same way it does for DAO objects.

The Container objects defined by Microsoft Access and the Container objects defined by the Jet database engine are all included in the Containers collection in Microsoft Access.

The Documents collection of a Container object contains Document objects representing the individual objects of the type described by the Container object. For example, the Forms Container object has a Documents collection that might include a Document object corresponding to a form named Orders.

With the exception of Modules, you can use Container objects to establish and enforce permissions for Microsoft Access database objects. To set permissions for a Container object, set the UserName property of the Container object to the name of an existing User or Group object. Then set the Permissions property for the Container object.

Note Don't confuse the particular types of Container objects with the collection types of the same name. The Forms and Reports Container objects each contain Documents collections, which include individual Document objects representing each saved form or report. The Forms and Reports collections refer only to open forms or reports.

The modules container is still present in Microsoft Access 2000 for backward compatibility but since security for modules is now handled by the Protection feature in the Visual Basic environment, permissions and user related properties for individual modules is no longer supported.


Container Object, Containers Collection Example

The following example grants programmers full access to all modules in a database, and grants all other users read-only permissions on modules:

Sub SetModulePermissions()
    Dim dbs As Database, wsp As Workspace, ctr As Container
    Dim grp As Group

    ' Return reference to default workspace.
    Set wsp = DBEngine.Workspaces(0)
    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Modules container.
    Set ctr = dbs.Containers!Modules
    wsp.Groups.Refresh
    For Each grp In wsp.Groups
        ctr.UserName = grp.Name
        If ctr.UserName = "Programmers" Then
            ctr.Permissions = ctr.Permissions Or dbSecFullAccess
        Else
            ctr.Permissions = ctr.Permissions Or acSecModReadDef
        End If
    Next grp
    Set dbs = Nothing
End Sub


Control Object, Controls Collection 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 ctl
End Sub


Create Key Example

The following example creates a new Key object that defines a relationship between a Categories table and a Products table. The Categories table is the primary table in the relationship, and the Products table is the foreign table. The CategoryID field is the primary key in the Categories table, and a foreign key in the Products table.

To test this example in the Northwind sample database, click Relationships on the Tools menu, and delete the relationship between the Categories table and the Products table. Close the Relationships window, saving the current configuration at the prompt. Run the following procedure. Then view the Relationships window again to see the new relationship.

Note Currently creating foreignkeys are not supported in ADPs with the version of the SQL provider shipped with Microsoft Access 2000. A reference to "Microsoft ADO ext. 2.1 for DDL and Security" must be set to use this example.

Sub CreateForeignKey()
   Sub CreateKey()
    Dim Rel As New ADOX.Key
    Dim cat As New ADOX.Catalog
    cat.ActiveConnection = CurrentProject.Connection

    With Rel
        .Name = "CatProd"
        .Type = adKeyForeign
        .RelatedTable = "Categories"
        .Columns.Append "CategoryID"
        .Columns("CategoryID").RelatedColumn = "CategoryID"
    End With
    cat.Tables("Products").Keys.Append Rel
End Sub


CurrentProject Object Example

The following example prints some current property settings of the CurrentProject object and then sets an option to display hidden objects within the application:

Sub ApplicationInformation()
    ' Print name and type of current object.
    Debug.Print Application.CurrentProject.FullName
    Debug.Print Application.CurrentProject.ProjectType
    ' Set Hidden Objects option under Show on View Tab
    'of the Options dialog box.
    Application.SetOption "Show Hidden Objects", True
End Sub

The next example shows how to use the CurrentProject object using Automation from another Office application. First, from the other application, 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 9.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 verifies that the specified report exists using the CurrentProject object and AllReports collection.

Sub GetAccessData()
' Declare object variable in declarations section of a module
    Dim appAccess As Access.Application
    Dim strDB As String
    Dim strReportName As String

    strDB = "C:\Program Files\Microsoft "_
        & "Office\Office\Samples\Northwind.mdb"
    strReportName = InputBox("Enter name of report to be verified", _
        "Report Verification")
    VerifyAccessReport strDB, strReportName
End Sub

Sub VerifyAccessReport(strDB As String, _
     strReportName As String)
    ' Return reference to Microsoft Access
    ' Application object.
    Set appAccess = New Access.Application
    ' Open database in Microsoft Access.
    appAccess.OpenCurrentDatabase strDB
    ' Verify report exists.
    On Error Goto ErrorHandler
    appAccess.CurrentProject.AllReports(strReportName)
    MsgBox "Report " & strReportName & _
        " verified within Northwind database."
    appAccess.CloseCurrentDatabase
    Set appAccess = Nothing
Exit Sub
ErrorHandler:
    MsgBox "Report " & strReportName & _
        " does not exist within Northwind database."
    appAccess.CloseCurrentDatabase
    Set appAccess = Nothing
End Sub


 DataAccessPage Object

DataAccessPage Object

 DataAccessPages collection (DataAccessPage object)

A DataAccessPage object refers to a particular Microsoft Access data access page.

Remarks

A DataAccessPage object is a member of the DataAccessPages collection, which is a collection of all currently open data access pages. Within the DataAccessPages collection, individual data access pages are indexed beginning with zero. You can refer to an individual DataAccessPage object in the DataAccessPages collection either by referring to the data access page by name, or by referring to its index within the collection. If you want to refer to a specific data access page in the DataAccessPages collection, it's better to refer to the data access page by name because a data access page's collection index may change. If the data access name includes a space, the name must be surrounded by brackets ([ ]).

Syntax | Example
DataAccessPages!pagename | DataAccessPages!SalePage
DataAccessPages![page name] | DataAccessPages![Sale Page]
DataAccessPages("pagename") | DataAccessPages("Sale Page")
DataAccessPages(index) | DataAccessPages(0)


DataAccessPage Object, DataAccessPages Collection Example

The following example creates a new data access page and sets certain properties:

Sub NewDataAccessPage()
    Dim dap As DataAccessPage
    ' Create new data access page.
    Set dap = CreateDataAccessPage("c:\My Documents\Sales Entry", _
            True)
    ' Set data access page Tag property.
    dap.Tag = "Sales Entry Data Access Page"
    ' Restore data access page.
    DoCmd.Restore
End Sub

The next example enumerates the DataAccessPages collection and prints the name of each data access page in the DataAccessPages collection.

Sub AllOpenDataAccessPages()
    Dim dap As DataAccessPage

    Set dbs = Application.CurrentProject
    ' Search for open objects in DataAccessPages collection.
    For Each dap In dbs.AllDataAccessPages
        If dap.IsLoaded = TRUE then
            ' Print name of form.
            Debug.Print dap.Name
        End If
    Next dap
End Sub


 Database Object, Databases Collection

Database Object, Databases Collection (MDB)

When working with Data Access Objects from Microsoft Access, you will often need a Database object variable that represents the current database. Use the CurrentDb function to return a Database object for the database that is currently open. This Database object is automatically appended to the Databases collection.

For example, suppose you are currently working with the Northwind sample database in Microsoft Access. You can create a Database object that refers to that database by first declaring a Database object variable, then pointing it to the Database object returned by the CurrentDb function.

Dim dbs As Database
Set dbs = CurrentDb

You don't need to know the name of the database or its position in the Databases collection in order to use the current database. If you do want to know the name of the current database, check the Name property of the Database object, which contains the path and file name of the database. To find its position in the Databases collection, enumerate through the collection.

You can open only one database at a time in the Microsoft Access window. From Visual Basic code, however, you can create multiple independent Database object variables to represent multiple open databases. In this way, you can manipulate more than one database at a time from code. You can also create multiple Database object variables and point them to the current database.

Note In your Visual Basic code, use the CurrentDb function to return a Database object that refers to the current database, rather than the DBEngine(0)(0) syntax. The CurrentDb function creates another instance of the current database, while the DBEngine(0)(0) syntax refers to the open copy of the current database. Using the CurrentDb function enables you to create more than one variable of type Database that 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 environment.


Database Object, Databases Collection Example (MDB)

The following example shows three ways to return a Database object in Microsoft Access. The procedure returns a Database object representing the current database, which is open in the Microsoft Access window. Next, the procedure creates another database called Newdb.mdb and saves it to disk. Then it opens an existing database called Another.mdb. Finally, it enumerates all Database objects in the Databases collection.

Sub ReferenceDatabases()
    Dim wsp As Workspace
    Dim dbsCurrent As Database, dbsNew As Database
    Dim dbsAnother As Database, dbs As Database

    ' Return reference to current database.
    Set dbsCurrent = CurrentDb
    ' Return reference to default workspace.
    Set wsp = DBEngine.Workspaces(0)
    ' Create new Database object.
    Set dbsNew = wsp.CreateDatabase("Newdb.mdb", dbLangGeneral)
    ' Open database other than current database.
    Set dbsAnother = wsp.OpenDatabase("Another.mdb")
    ' Enumerate all open databases.
    For Each dbs in wsp.Databases
        Debug.Print dbs.Name
    Next dbs
    For Each dbs In wsp.Databases
        Set dbs = Nothing
    Next dbs
    Set wsp = Nothing
End Sub


 DBEngine Object

DBEngine Object (MDB)

Microsoft Access provides a means of manipulating Data Access Objects (DAO) from other applications through Automation, formerly called OLE Automation. If you are controlling Microsoft Access from another application, such as Visual Basic or Microsoft Excel, you can use the DBEngine property of the Microsoft Access Application object to return a reference to the DBEngine object. All DAO objects and collections are then accessible through the DBEngine object.


DBEngine Object Example (MDB)

The following example prints all the properties of the DBEngine object:

Sub EngineProperties()
    Dim prp As Property

    For Each prp In DBEngine.Properties
        Debug.Print prp.Name
    Next prp
End Sub


DefaultWebOptions Object Example

The following example checks to see whether Microsoft Office Web components are downloaded when a saved data access page is displayed and sets the download flag accordingly.

Set objAppWebOptions = Application.DefaultWebOptions
With objAppWebOptions
    If .DownloadComponents = True Then
        strCompDownload = "Loaded"
    Else
        strCompDownload = "Not Loaded"
    End If
End With


DoCmd Object Example

The following example opens a form in Form view and moves to a new record.

Sub ShowNewRecord()
    DoCmd.OpenForm "Employees", acNormal
    DoCmd.GoToRecord , , acNewRec
End Sub


 Document Object, Documents Collection

Document Object, Documents Collection

In addition to the Document objects defined by the Microsoft Jet database engine, the following Document objects are defined by Microsoft Access.

Document | Container | Contains information about
Form | Forms | Saved form
Macro | Scripts | Saved macro
Module | Modules | Saved module
Report | Reports | Saved report
DataAccessPage | DataAccessPages | Saved DataAccessPage
SummaryInfo | Databases | Database document summary
UserDefined | Databases | User-defined properties

The Document objects defined by Microsoft Access are Microsoft Access database objects, not Data Access Objects (DAO). These Document objects provide the Jet database engine with information about Microsoft Access objects. The Jet database engine uses this information to implement security on Microsoft Access database objects in the same way it does for DAO objects.

The Documents collection of a Container object contains Document objects representing the individual objects of the type described by the Container object. For example, the Forms Container object has a Documents collection that might include a Document object corresponding to a form named Orders.

Microsoft Access defines two Document objects in the Databases Container object — SummaryInfo and UserDefined.

The SummaryInfo Document object provides programmatic access to document summary properties — including Title, Subject, Author, Keywords, Comments, Manager, Company, Category, and Hyperlink Base. You can also set these properties on the Summary tab of the Database Properties dialog box, available by clicking Database Properties on the File menu.

To set these properties in Visual Basic, you must create them and append them to the Properties collection of the SummaryInfo Document object if they haven't already been set in the Database Properties dialog box. Once a property has been created, you must explicitly refer to the Properties collection to set it. In the following example, doc is an object variable pointing to the SummaryInfo Document object:

doc.Properties!Title = "Northwind Traders"

For more information on creating and setting Microsoft Access–defined properties, search the Help index for "Property object" and "CreateProperty method."

The UserDefined Document object provides programmatic access to user-defined properties defined on the Custom tab of the Database Properties dialog box. You can also create these properties in Visual Basic and append them to the Properties collection of the UserDefined Document object.

Note Don't confuse properties defined in the Properties collection of a Database document with properties defined in the Properties collection of a Database object. You can create user-defined properties in either Properties collection, but only those defined on the SummaryInfo or UserDefined Document objects can be set from the Database Properties dialog box.

You can use Document objects to establish and enforce permissions for individual Microsoft Access database objects. To set permissions for a Document object, set the UserName property of the Document object to the name of an existing User or Group object. Then set the Permissions property for the Document object.

Note Don't confuse the particular types of Container objects with the collection types of the same name. The Forms and Reports Container objects each contain Documents collections, which include individual Document objects representing each saved form or report. The Forms and Reports collections refer only to open forms or reports.


Document Object, Documents Collection Example (MDB)

The following example prints the name of each Form Document object in the current database and the date it was last modified:

Sub DocumentModified()
    Dim dbs As Database, ctr As Container, doc As Document

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return referenct to Forms container.
    Set ctr = dbs.Containers!Forms
    ' Enumerate through Documents collection of Forms container.
    For Each doc In ctr.Documents
        ' Print Document object name and value of
        ' LastUpdated property.
        Debug.Print doc.Name; "      "; doc.LastUpdated
    Next doc
    Set dbs = Nothing
End Sub


Dynaset-Type Recordset Object Example (MDB)

The following example creates a dynaset-type Recordset object, then checks the Updatable property of the Recordset object:

Sub RecentHires()
    Dim dbs As Database, rst As Recordset
    Dim strSQL As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Open recordset on Employees table.
    Set rst = dbs.OpenRecordset("Employees", dbOpenDynaset)
    Debug.Print rst.Updatable
    rst.Close
    Set dbs = Nothing
End Sub


 Error Object

Error Object

The Description property of an Error object contains the descriptive string associated with a particular error. You can read the Description property only if the error has occurred.

To determine the descriptive string associated with an error that hasn't occurred, use the Microsoft Access AccessError function. The AccessError function takes an error number as an argument and returns the descriptive string. For example, if you want to determine the descriptive string associated with error 3021, you might use the AccessError function as follows:

Debug.Print AccessError(3021)

Microsoft Access prints the descriptive string associated with error 3021, "No current record", to the Debug window.


Error Object, Errors Collection Example (MDB)

The following example generates an error by attempting to open a Recordset object on a nonexistent Students table. Information about the error is stored in both the DAO Error object and the Visual Basic Err object. The procedure prints the value of the Description, Source, and Number properties of the Error object. Then it prints the values of the corresponding properties of the Err object.

Note that the last Error object in the Errors collection should always refer to the same error as the Err object. That is, the value of Err.Number should be equivalent to Errors.Count – 1. If these two values aren't equivalent, information in the Errors collection may be outdated. Use the Refresh method to ensure that the Errors collection includes the most recent error information.

Sub CheckError()
    Dim dbs As Database, tdf As TableDef, rst As Recordset
    ' Declare Error object variable for enumeration
    ' of Errors collection.
    Dim errX As Error

    ' Ignore errors.
    On Error Resume Next
    ' Clear error in Err object.
    Err.Clear
    ' Refresh Errors collection.
    Errors.Refresh
    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Attempt to open Recordset object on nonexistent table.
    Set rst = dbs.OpenRecordset("Students")
    Debug.Print "DAO Error Object:"
    ' Print number of errors in Errors collection.
    Debug.Print ">>>Number of errors: "; Errors.Count
    ' Enumerate Errors collection and key properties.
    For Each errX In DBEngine.Errors
        Debug.Print errX.Description
        Debug.Print errX.Source
        Debug.Print errX.Number
    Next errX
    Debug.Print
    Debug.Print "VBA Err Object:"
    ' Display corresponding properties of Err object.
    Debug.Print Err.Description
    Debug.Print Err.Source
    Debug.Print Err.Number
    Set dbs = Nothing
End Sub


 Field Object, Fields Collection

Field Object, Fields Collection (MDB)

In addition to the properties defined by the Microsoft Jet database engine, a Field object in the Fields collection of a QueryDef object or a TableDef object may also contain the following Microsoft Access application-defined properties.

For details on reading and setting these properties, search the online index for the individual properties and the Property object.

Caption | DecimalPlaces
ColumnHidden | Description
ColumnOrder | Format
ColumnWidth | InputMask


Field Object, Fields Collection Example (MDB)

The following example creates a new Field object, sets some of its properties, and appends it to the Fields collection of a TableDef object. The procedure then enumerates all fields in the Fields collection of the TableDef object.

Sub NewField()
    Dim dbs As Database, tdf As TableDef
    Dim fld As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Employees table.
    Set tdf = dbs.TableDefs!Employees
    ' Create new Field object.
    Set fld = tdf.CreateField("SSN#")
    ' Set Type and Size properties of Field object.
    fld.Type = dbText
    fld.Size = 11
    ' Append field.
    tdf.Fields.Append fld
    ' Enumerate all fields in Fields collection of TableDef object.
    For Each fld in tdf.Fields
        Debug.Print fld.Name
    Next fld
    Set dbs = Nothing
End Sub


FormatConditions, FormatCondition Object Example

The following example adds a conditional formatting to a text box, "Textbox1" and sets some properties of the newly added FormatCondition object.

With Forms("form1").Controls("Textbox1").FormatConditions _
    .Add(acFieldValue, acGreaterThan, "=[Textbox2]")
    .BackColor = RGB(255,255,255)
    .FontBold = True
    .ForeColor = RGB(255,0,0)
End With

The following example sets format properties for an existing conditional format for the "Textbox1" control.

With forms("forms1").Controls("Textbox1").FormatConditions(1)
    .BackColor = RGB(255,255,255)
    .FontBold = True
    .ForeColor = RGB(255,0,0)
End With


Form Object, Forms Collection Example

The following example creates a new form and sets certain properties:

Sub NewForm()
    Dim frm As Form

    ' Create new form.
    Set frm = CreateForm
    ' Set form properties.
    With frm
        .RecordSource = "Products"
        .Caption = "Products Form"
        .ScrollBars = 0
        .NavigationButtons = True
    End With
    ' Restore form.
    DoCmd.Restore
End Sub

The next example enumerates the Forms collection and prints the name of each form in the Forms collection. It then enumerates the Controls collection of each form and prints the name of each control on the form.

Sub AllOpenForms()
    Dim frm As Form, ctl As Control

    ' Enumerate Forms collection.
    For Each frm In Forms
        ' Print name of form.
        Debug.Print frm.Name
        ' Enumerate Controls collection of each form.
        For Each ctl In frm.Controls
            ' Print name of each control.
            Debug.Print ">>>"; ctl.Name
        Next ctl
    Next frm
End Sub

The following example uses the Forms collection in an expression. If you have a form called Orders with a control named ShipCountry, you can use the IIf function to return a value based on the current value of the control. If the value of ShipCountry is Null, the expression returns a zero-length string; otherwise, it returns the field's contents. Enter the following expression in the ControlSource property of a text box on a form:

= IIf(IsNull(Forms!Orders! ShipCountry), "", _
     Forms!Orders!ShipCountry)


 Group Object, Groups Collection

Group Object, Groups Collection (MDB)

You can create Group objects to establish and enforce permissions for Microsoft Access database objects as well as for Data Access Objects. For example, you can set security for forms, reports, macros.

A Group object has a Name property that you can use in setting permissions for a Container or Document object. For example, you can assign the value of a Group object's Name property to the UserName property of a Container or Document object. You can then set the Permissions property of the Container or Document object to establish permissions for the group of users defined by the UserName property. Or you can read the Permissions property to determine existing permissions for that group.


Group Object, Groups Collection Example (MDB)

The following example creates a new User object and appends it to the Users collection of a Workspace object. It then creates a new Group object and appends it to the Groups collection of the Workspace object. The new Group object is also appended to the Groups collection of the User object. The new group is then given modify and delete permissions for modules.

Note that in order to assign users to groups, you must either append a User object to the Users collection of a Group object, or append a Group object to the Groups collection of a User object. It doesn't matter which option you choose; either will result in the specified user being included in the specified group.

Note When programming security, you should avoid including password and PID information in your code. The following example is intended for demonstration purposes only.

Sub NewMacrosGroup()
    Dim wsp As Workspace, dbs As Database
    Dim usr As User, grp As Group, grpMember As Group
    Dim ctr As Container

    ' Return referenct to default workspace.
    Set wsp = DBEngine.Workspaces(0)
    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create User object and append to Users collection
    ' of Workspace object.
    Set usr = wsp.CreateUser("Pat Smith", _
        "123abc789xyz", "Password")
    wsp.Users.Append usr
    ' Create Group object and append to Groups
    ' collection of Workspace object.
    Set grp = wsp.CreateGroup("Programmers", "321xyz987abc")
    wsp.Groups.Append grp
    ' Append Group object to Groups collection of User object.
    Set grpMember = usr.CreateGroup("Programmers")
    usr.Groups.Append grpMember
    ' Refresh Groups collection of User object.
    usr.Groups.Refresh
    ' Return Container object.
    Set ctr = dbs.Containers!Scripts
    ' Set UserName property of Container object.
    ctr.UserName = grpMember.Name
    'Add modify and delete permissions for new group
    ' on all modules.
    ctr.Permissions = ctr.Permissions Or acSecMacWriteDef
    Set dbs = Nothing
    Set wsp = Nothing
End Sub


 Hyperlink Object Example

Hyperlink Object Example

The following example activates the hyperlink associated with a command button in the active form.

Me!Command0.Hyperlink.Follow

The following example sets the HyperlinkAddress property of a command button and then opens the hyperlink when the form is loaded.

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

Private Sub Form_Load()
    Dim ctl As CommandButton
    Set ctl = Me!Command0
    With ctl
        .Visible = False
        .HyperlinkAddress = "http://www.microsoft.com/"
        .Hyperlink.Follow
    End With
End Sub


Index Object, Indexes Collection Example

Index Object, Indexes Collection Example (MDB)

The following example creates a new index on an Employees table:

Sub NewIndex()
    Dim dbs As Database, tdf As TableDef, idx As Index
    Dim fld1 As Field, fld2 As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Employees table.
    Set tdf = dbs.TableDefs!Employees
    Set idx = tdf.CreateIndex("EmployeeNameIndex")
    Set fld1 = idx.CreateField("LastName")
    Set fld2 = idx.CreateField("FirstName")
    idx.Fields.Append fld1
    idx.Fields.Append fld2
    idx.Required = True
    tdf.Indexes.Append idx
    Set dbs = Nothing
End Sub


Module Object, 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_LinesInModule
End Function


Page Object, 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)
    ' Enumerate controls on currently selected page.
    Debug.Print pge.Name & " Controls:"
    For Each ctl In pge.Controls
        Debug.Print ctl.Name
    Next ctl
    Debug.Print
End Sub


Parameter Object, Parameters Collection Example (MDB)

The following example creates a new parameter query and supplies values for the parameters:

Sub NewParameterQuery()
    Dim dbs As Database, qdf As QueryDef, rst As Recordset
    Dim prm As Parameter, strSQL As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Construct SQL string.
    strSQL = "PARAMETERS [Beginning OrderDate] DateTime, " _
        & "[Ending OrderDate] DateTime; SELECT * FROM Orders " & _
        "WHERE (OrderDate Between[Beginning OrderDate] " _
        & "And [Ending OrderDate]);"
    ' Create new QueryDef object.
    Set qdf = dbs.CreateQueryDef("ParameterQuery", strSQL)
    ' Supply values for parameters.
    qdf.Parameters![Beginning OrderDate] = #4/1/95#
    qdf.Parameters![Ending OrderDate] = #4/30/95#
    ' Open recordset on QueryDef object.
    Set rst = qdf.OpenRecordset
    rst.MoveLast
    MsgBox "Query returned " & rst.RecordCount & " records."
    rst.Close
    Set dbs = Nothing
End Sub


 Property Object, Properties Collection

Property Object, Properties Collection (MDB)

Several types of properties exist in Microsoft Access. Each of these properties can be represented in Visual Basic code by a Property object variable, and each is a member of a Properties collection.

Properties that Apply to Data Access Objects

  • Built-in properties are defined by the Microsoft Jet database engine for all Data Access Objects (DAO).

  • User-defined properties can be added to some DAO objects. These DAO objects include Database, Index, QueryDef, and TableDef objects, and Field objects in the Fields collection of a QueryDef or TableDef object.

  • Some properties defined by Microsoft Access apply to DAO objects. These properties can generally be set either in the Microsoft Access window or from Visual Basic. The Jet database engine cannot recognize these properties until corresponding Property objects are specifically created and appended to the Properties collection. The DAO objects to which such properties may apply are QueryDef and TableDef objects, and Field objects in the Fields collection of a QueryDef or TableDef object. For lists of these Microsoft Access–defined properties, see the Microsoft Access Specifics topic for the TableDef, QueryDef, and Field objects.

Microsoft Access–defined properties that apply to DAO objects differ from properties defined by the Jet database engine in several ways.

To refer to a user-defined property or a property defined by Microsoft Access, you must explicitly refer to the Properties collection. The fastest way to refer to a Microsoft Access property is by the following syntax:

object.Properties!propertyname

In the preceding example, object is a DAO object and propertyname is the name of a Microsoft Access property.

You can also use the following, slightly slower syntax:

object.Properties("name")

In contrast, to refer to properties defined by the Jet database engine, you can simply use the object.name syntax.

If you are setting the value of a Microsoft Access-defined property for the first time, you first need to create it by using the CreateProperty method. For example, the Caption property of a Field object is a Microsoft Access–defined property. If you haven't previously set the Caption property in table Design view, but are setting the property for the first time from Visual Basic code, you must first create that property by using the CreateProperty method and append it to the Properties collection before you can set its value.

A Microsoft Access–defined property is automatically appended to the Properties collection the first time it is set in the Microsoft Access window, so if you have already set a property in the user interface, you don't need to create and append the property in code. For example, you can set the Caption property for a table in Datasheet view by clicking Font on the Format menu. This property is then included in the Properties collection of a TableDef object that points to the table.

Until you have set a Microsoft Access–defined property either in table Design view or from Visual Basic code, that property won't appear in the Properties collection. When you set these properties from Visual Basic, you should include error-handling code that checks to see if the property exists in the Properties collection, and creates and appends the property if it doesn't.

Properties that Apply to Microsoft Access Objects

Like DAO objects, every Microsoft Access object contains a Properties collection, which has built-in Property objects. For example, Property objects that apply to a form are members of the Properties collection of the Form object.

You can also create user-defined properties for Microsoft Access objects. For example, you might create a property called TextType that applies to a text box control.

Property objects in the Properties collections of Form, Report, and Control objects differ from DAO Property objects in that they don't have an Inherited property.

You can enumerate the Property objects in the Properties collections of Form, Report, and Control objects. However, the Microsoft Access Application object and the Screen object have Properties collections that can't be enumerated. Additionally, the properties of these objects are read-only.


Property Object, Properties Collection Example (MDB)

The following example creates a property that is defined by Microsoft Access, but applies to DAO objects. Because the Microsoft Jet database engine cannot recognize properties defined by Microsoft Access, you must create a new Property object and append it to the Properties collection if you are setting the property for the first time.

You can use the same function to set a user-defined property on a Microsoft Access object or on a DAO object.

Note that you must specify the correct constant for the type argument when you create the property. If you're not certain which data type you should use, search the Help index for the individual property.

Function SetAccessProperty(obj As Object, strName As String, _
        intType As Integer, varSetting As Variant) As Boolean
    Dim prp As Property
    Const conPropNotFound As Integer = 3270

    On Error GoTo ErrorSetAccessProperty
    ' Explicitly refer to Properties collection.
    obj.Properties(strName) = varSetting
    obj.Properties.Refresh
    SetAccessProperty = True

ExitSetAccessProperty:
    Exit Function

ErrorSetAccessProperty:
    If Err = conPropNotFound Then
        ' Create property, denote type, and set initial value.
        Set prp = obj.CreateProperty(strName, intType, varSetting)
        ' Append Property object to Properties collection.
        obj.Properties.Append prp
        obj.Properties.Refresh
        SetAccessProperty = True
        Resume ExitSetAccessProperty
    Else
        MsgBox Err & ": " & vbCrLf & Err.Description
        SetAccessProperty = False
        Resume ExitSetAccessProperty
    End If
End Function

You could call the preceding function with a procedure such as the following:

Sub CallPropertySet()
    Dim dbs As Database, tdf As TableDef
    Dim blnReturn As Boolean

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Employees table.
    Set tdf = dbs.TableDefs!Employees
    ' Call SetAccessProperty function.
    blnReturn = SetAccessProperty(tdf, _
        "DatasheetFontItalic", dbBoolean, True)
    ' Evaluate return value.
    If blnReturn = True Then
        Debug.Print "Property set successfully."
    Else
        Debug.Print "Property not set successfully."
    End If
End Sub


 QueryDef Object, QueryDefs Collection

QueryDef Object, QueryDefs Collection (MDB)

In addition to the properties defined by the Microsoft Jet database engine, a QueryDef object may also contain these Microsoft Access application–defined properties. For details on checking and setting these properties, search the Help index for the individual properties and the Property object.

DatasheetFontItalic | FrozenColumns
DatasheetFontHeight | LogMessages
DatasheetFontName | RecordLocks
DatasheetFontUnderline | RowHeight
DatasheetFontWeight | ShowGrid
Description | UseTransaction


QueryDef Object, QueryDefs Collection Example

QueryDef Object, QueryDefs Collection Example (MDB)

The following example checks to see if there is a query called RecentHires in the current database, and deletes it from the QueryDefs collection if it exists. Then the procedure creates a new QueryDef object and opens it in Datasheet view.

Sub NewQuery()
    Dim dbs As Database, qdf As QueryDef
    Dim strSQL As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Refresh QueryDefs collection.
    dbs.QueryDefs.Refresh
    ' If RecentHires query exists, delete it.
    For Each qdf in dbs.QueryDefs
        If qdf.Name = "RecentHires" Then
            dbs.QueryDefs.Delete qdf.Name
        End If
    Next qdf
    ' Create SQL string to select employees hired on or
    ' after 1-1-94.
    strSQL = "SELECT * FROM Employees WHERE HireDate >= #1-1-94#;"
    ' Create new QueryDef object.
    Set qdf = dbs.CreateQueryDef("RecentHires", strSQL)
    ' Open query in Datasheet view.
    DoCmd.OpenQuery qdf.Name
    Set dbs = Nothing
End Sub


Recordset Object, Recordsets Collection Example (MDB)

The following example opens a table-type Recordset object, a dynaset-type Recordset object, and a snapshot-type Recordset object. Then it displays the value of the Updatable property for the Recordset objects.

Sub NewRecordsets()
    Dim dbs As Database, rst As Recordset
    Dim rstEmployees As Recordset, rstOrders As Recordset
    Dim rstProducts As Recordset, strSQL As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create table-type Recordset object.
    Set rstEmployees = dbs.OpenRecordset("Employees", dbOpenTable)
    ' Create dynaset-type Recordset object.
    Set rstOrders = dbs.OpenRecordset("Employees", dbOpenDynaset)
    ' Create snapshot-type Recordset object.
    Set rstProducts = dbs.OpenRecordset("Products", dbOpenSnapshot)
    ' Print value of Updatable property for each Recordset object.
    For Each rst In dbs.Recordsets
        Debug.Print rst.Name; "   "; rst.Updatable
    Next rst
    ' Free all object variables.
    rstEmployees.Close
    rstOrders.Close
    rstProducts.Close
    Set dbs = Nothing
End Sub


Reference Object, 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_ReferenceFromFile
End 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 If
End Sub


Relation Object, Relations Collection Example

Relation Object, Relations Collection Example (MDB)

The following example removes the existing relationship between an Employees table and an Orders table and then re-creates the relationship by creating a new Relation object.

Sub NewRelation()
    Dim dbs As Database
    Dim fld As Field, rel As Relation

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Find existing EmployeesOrders relation.
    For Each rel In dbs.Relations
        If rel.TABLE = "Employees" And _
            rel.ForeignTable = "Orders"
        Then
        ' Prompt user before deleting relation.
        If MsgBox(rel.Name & " already exists. " _
            & vbCrLf _
            & "This relation will be deleted and " _
            & "re-created.", vbOK) = vbOK
        Then
                dbs.Relations.Delete rel.Name
            ' If user chooses Cancel, exit procedure.
            Else
                Exit Sub
            End If
        End If
    Next rel
    ' Create new relationship and set its properties.
    Set rel = dbs.CreateRelation("EmployeesOrders", "Employees", "Orders")
    ' Set Relation object attributes to enforce
    ' referential integrity.
    rel.Attributes = dbRelationDeleteCascade + _
        dbRelationUpdateCascade
    ' Create field in Fields collection of Relation object.
    Set fld = rel.CreateField("EmployeeID")
    ' Provide name of foreign key field.
    fld.ForeignName = "EmployeeID"
    ' Append field to Relation object and
    ' Relation object to database.
    rel.Fields.Append fld
    dbs.Relations.Append rel
    MsgBox "Relation '" & rel.Name & "' created."
    Set dbs = Nothing
End Sub


Report Object, Reports Collection Example

The following example creates a new report and sets certain properties:

Sub NewReport()
    Dim rpt As Report

    ' Return variable of data type Report pointing to
    ' new Report object.
    Set rpt = CreateReport
    ' Set properties for new report.
    With rpt
        .RecordSource = "Products"
        .Caption = "Products Report"
    End With
    ' Restore new report.
    DoCmd.Restore
End Sub

The next example enumerates the Reports collection and prints the name of each report in the Reports collection. It then enumerates the Controls collection of each report and prints the name of each control on the report.

Sub AllOpenReports()
    Dim rpt As Report, ctl As Control

    ' Enumerate Reports collection.
    For Each rpt In Reports
        ' Print name of report.
        Debug.Print rpt.Name
        ' Enumerate Controls collection of each report.
        For Each ctl In rpt.Controls
            ' Print name of each control.
            Debug.Print ">>>"; ctl.Name
        Next ctl
    Next rpt
End Sub


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


Snapshot-Type Recordset Object Example (MDB)

The following example creates a snapshot-type Recordset object from an SQL statement, then prints the value of the Updatable property for the Recordset object. Since snapshot-type Recordset objects are never updatable, the value of this property will always be False (0).

Sub LongTermEmployees()
    Dim dbs As Database, qdf As QueryDef, rst As Recordset
    Dim strSQL As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Construct SQL string.
    strSQL = "SELECT * FROM Employees WHERE HireDate <= #1-1-94#;"
    ' Open snapshot-type Recordset object.
    Set rst = dbs.OpenRecordset(strSQL, dbOpenSnapshot)
    Debug.Print rst.Updatable
    rst.Close
    Set dbs = Nothing
End Sub


 TableDef Object, TableDefs Collection

TableDef Object, TableDefs Collection (MDB)

In addition to the properties defined by the Microsoft Jet database engine, a TableDef object may also contain the following Microsoft Access application–defined properties. For details on reading and setting these properties, search the Help index for the individual properties and the Property object.

DatasheetFontHeight | Description
DatasheetFontItalic | FrozenColumns
DatasheetFontName | RowHeight
DatasheetFontUnderline | ShowGrid
DatasheetFontWeight |


TableDef Object, TableDefs Collection Example

TableDef Object, TableDefs Collection Example (MDB)

The following example creates a new TableDef object, defines a field within it, and appends it to the TableDefs collection of the current database:

Sub NewTable()
    Dim dbs As Database, tdf As TableDef, fld As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create new TableDef object.
    Set tdf = dbs.CreateTableDef("Contacts")
    ' Create new Field object.
    Set fld = tdf.CreateField("ContactName", dbText, 30)
    ' Append new objects.
    tdf.Fields.Append fld
    dbs.TableDefs.Append tdf
    Set dbs = Nothing
End Sub


Table-Type Recordset Object Example (MDB)

The following example opens a table-type Recordset object, then finds a specified record:

Sub FindEmployee()
    Dim dbs As Database, tdf As TableDef
    Dim rst As Recordset, idx As Index
    Dim fldLastName As Field, fldFirstName As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Employees table.
    Set tdf = dbs.TableDefs!Employees
    ' Create new index.
    Set idx = tdf.CreateIndex("FullName")
    ' Create and append index fields.
    Set fldLastName = idx.CreateField("LastName", dbText)
    Set fldFirstName = idx.CreateField("FirstName", dbText)
    idx.Fields.Append fldLastName
    idx.Fields.Append fldFirstName
    ' Append Index object.
    tdf.Indexes.Append idx
    ' Open table-type Recordset object.
    Set rst = dbs.OpenRecordset("Employees")
    ' Set current index to new index.
    rst.Index = idx.Name
    ' Specify record to find.
    rst.Seek "=", "Fuller", "Andrew"
    If rst.NoMatch Then
        Debug.Print "Seek failed."
    Else
        Debug.Print "Seek successful."
    End If
    rst.close
    Set dbs = Nothing
End Sub


 User Object, Users Collection

User Object, Users Collection (MDB)

You can create User objects to establish and enforce permissions for Microsoft Access database objects as well as for Data Access Objects. For example, you can set security for forms, reports, macros.

A User object has a Name property that you can use in setting permissions for a Container or Document object. For example, you can assign the value of a User object's Name property to the UserName property of a Container or Document object. You can then set the Permissions property of the Container or Document object to establish permissions for the user defined by the UserName property. Or you can read the Permissions property to determine existing permissions for that user.


User Object, Users Collection Example

User Object, Users Collection Example (MDB)

The following example creates a new User object and appends it to the Users collection of a Workspace object. It then creates a new Group object and appends it to the Groups collection of the Workspace object. The new User object is also appended to the Users collection of the Group object. The new user is then given read-data permissions on tables.

Note that in order to assign users to groups, you must either append a User object to the Users collection of a Group object, or append a Group object to the Groups collection of a User object. It doesn't matter which option you choose; either will result in the specified user being included in the specified group.

Note When programming security, you should avoid including password and PID information in your code. The following example is intended for demonstration purposes only.

Sub NewTablesUser()
    Dim wsp As Workspace, dbs As Database
    Dim usr As User, grp As Group, usrMember As User
    Dim ctr As Container, doc As Document

    ' Return reference to default workspace.
    Set wsp = DBEngine.Workspaces(0)
    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create User object and append to Users collection
    ' of Workspace object.
    Set usr = wsp.CreateUser("Chris Jones", _
        "123abc456DEF", "Password")
    wsp.Users.Append usr
    ' Create Group object and append to Groups
    ' collection of Workspace object.
    Set grp = wsp.CreateGroup("Marketing", "321xyz654EFD")
    wsp.Groups.Append grp
    ' Append new User object to Users collection of
    ' new Group object.
    Set usrMember = grp.CreateUser("Chris Jones")
    grp.Users.Append usrMember
    ' Refresh Users collection of Group object.
    grp.Users.Refresh
    ' Return Container object.
    Set ctr = dbs.Containers!Tables
    ' Set UserName property of Container object.
    ctr.UserName = usrMember.Name
    ' Add retrieve permissions for new user on all tables.
    ctr.Permissions = ctr.Permissions Or dbSecRetrieveData
    Set dbs = Nothing
    Set wsp = Nothing
End Sub


WebOptions Object Example

The following example checks to see whether Microsoft Office Web components are downloaded when a saved data access page ("Inventory") is displayed and sets the download flag accordingly.

Set objAppWebOptions = DataAccessPages("Inventory").WebOptions
With objAppWebOptions
    If .DownloadComponents = True Then
        strCompDownload = "Loaded"
    Else
        strCompDownload = "Not Loaded"
    End If
End With


AbsolutePosition Property Example

AbsolutePosition Property Example (MDB)

The following example finds a particular record in a dynaset-type Recordset object and determines the ordinal position of that record:

Sub RecordOrdinalPosition()
    Dim dbs As Database, rst As Recordset

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to dynaset-type Recordset object object.
    Set rst = dbs.OpenRecordset("SELECT * FROM Orders WHERE " _
        & "ShippedDate >= #1-1-96#;")
    ' Find first order shipped to London.
    rst.FindFirst "ShipCity = 'London'"
    ' Return ordinal position of that record.
    Debug.Print rst.AbsolutePosition
    rst.Close
    Set dbs = Nothing
End Sub


ActiveControl 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.ActiveControl
If ctlCurrentControl.Name = "txtCustomerID" Then
    .            ' Do this.
    .
    .
ElseIf ctlCurrentControl.Name = "btnCustomerDetails" Then
    .            ' Do this.
    .
    .
End If


 ActiveDataAccessPage Property

ActiveDataAccessPage Property

You can use the ActiveDataAccessPage property to identify or refer to the data access page that has the focus.

Setting

The ActiveDataAccessPage property setting contains a reference to the DataAccessPage object that has the focus at run time.

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

Remarks

Use the ActiveDataAccessPage property to refer to an active data access page together with one of its properties or methods. The following example displays the Name property setting of the active data access page:

Dim pgCurrentPage As DataAccessPage
Set pgCurrentPage = Screen.ActiveDataAccessPage
MsgBox "Current Data Page is " & pgCurrentPage.Name

If no data access page has the focus when you use the ActiveDataAccessPage property, an error occurs.


ActiveDatasheet Property Example

The following example uses the ActiveDatasheet property to identify the datasheet cell with the focus, or if more than one cell is selected, the location of the first row and column in the selection.

Sub GetSelection()
    Dim 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 " & lngFirstColumn
GetSelection_Bye:
    Exit Sub
GetSelection_Err:
    If Err = conNoActiveDatasheet Then
        Resume GetSelection_Bye
    End If
End Sub


ActualSize Property

The ADO ActualSize property is equivalent to the FieldSize property in DAO. Use the ActualSize when you want to return the size of the data actually stored in a field from Visual Basic.


Alias Property Example

The following example sets the RecordSource property for a form to an SQL statement that uses the AS clause to specify Managers as the alias for the Employees table.

Dim strGetSQL AS String
strGetSQL = "SELECT 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.LastName
FROM Employees INNER JOIN Employees AS Managers
ON Employees.ReportsTo = Managers.EmployeeID;


AllowBypassKey Property Example

The following example shows a procedure named SetBypassProperty 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 AllowBypassKey property and, if the property isn't found, uses the CreateProperty method to append it to the Properties collection. This is necessary because this property doesn't appear in the Properties collection until its been added.

Sub SetBypassProperty()
Const DB_Boolean As Long = 1
    ChangeProperty "AllowBypassKey", DB_Boolean, False
End Sub

Function ChangeProperty(strPropName As String, varPropType As Variant, varPropValue As Variant) As Integer
    Dim dbs As Object, prp As Variant
    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 If
End Function


AllowFilters Property Example

The following example shows a function that toggles a form's AllowFilters property on and off:

Function ToggleAllowFilters() As Integer
    Forms!Customers.AllowFilters = Not Forms!Customers.AllowFilters
End Function


 AllPermissions Property (MDB)

AllPermissions Property (MDB)

Microsoft Access defines four types of Container objects in addition to those defined by the Microsoft Jet database engine. These include the Forms, Reports, Scripts, or Modules Container objects. Individual Form, Report, Script and Module Document objects belong to the Documents collections of these Container objects. For these Container and Document objects, you can also set the AllPermissions property to the following constants.

Constant | User or group can
acSecFrmRptReadDef | Open the form or report in Design view but not make any changes.
acSecFrmRptWriteDef | Modify or delete the form or report in Design view.
acSecFrmRptExecute | Open the form in Form view or Datasheet view; print or open the report in Sample Preview or Print Preview.
acSecMacReadDef | Open the Macro window and view a macro without making changes.
acSecMacWriteDef | Modify or delete the macro in the Macro window.
acSecModReadDef | Open the module but not make any changes.
acSecModWriteDef | Modify or delete the contents of a module.

Note acSecModReadDef and acSecModWriteDef are included for backward compatibility only. Since Module access is now controlled by the Protection property in the Visual Basic envronment, these constants are no longer valid parameters in Microsoft Access2000.


AllPermissions Property Example

AllPermissions Property Example (MDB)

The following example checks the AllPermissions property for the Forms Container object and determines whether the user specified by the UserName property has full access to forms.

Note that the And operator performs a bitwise comparison to determine what permissions are currently set.

Sub CheckAllPermissions()
    Dim dbs As Database, ctr As Container

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Forms container.
    Set ctr = dbs.Containers!Forms
    ' Check if AllPermissions property includes full access.
    If (ctr.AllPermissions And dbSecFullAccess = _
            dbSecFullAccess) Then
        MsgBox "User " & ctr.UserName _
            & " has full access to all forms."
    End If
    Set dbs = Nothing
End Sub


AlwaysSaveInDefaultEncoding Property Example

This example sets the encoding to the default encoding. The encoding is used when you save the data access page as a Web page.

Application.DefaultWebOptions.AlwaysSaveInDefaultEncoding = True


AppIcon, AppTitle Properties Example

The following example shows how to change the AppIcon and AppTitle properties in a Microsoft Access database (.mdb). If the properties haven't already been set or created, you must create them and append them to the Properties collection by using the CreateProperty method.

Sub cmdAddProp_Click()
    Dim intX As Integer
    Const DB_Text As Long = 10
    intX = AddAppProperty("AppTitle", DB_Text, "My Custom Application")
    intX = AddAppProperty("AppIcon", DB_Text, "C:\Windows\Cars.bmp")
    Application.RefreshTitleBar
End Sub

Function AddAppProperty(strName As String, varType As Variant, varValue As Variant) As Integer
    Dim dbs As Object, prp As Variant
    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 If
End Function


Application and DBEngine Properties Example

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

Private Sub Command1_Click()
    DisplayApplicationInfo Me
End 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.
        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


Assistant Property 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 9.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:"
        ' Return Assistant's visible state to original setting.
        .Visible = blnState
    End With
End Sub


Attributes Property (MDB)

If you set the Attributes property of a TableDef object to dbHiddenObject, Microsoft Access hides the TableDef object. The TableDef object exists in the TableDefs collection, but you cannot see it in the Database window, even if you have selected the Show Hidden Objects option in the Options dialog, which is available by clicking on the Tools menu.

To create a TableDef object that can be either hidden or visible, set the Attributes property to dbSystemObject. You can then make the TableDef object visible in the Database window by selecting Show System Objects in the Options dialog.


Attributes Property Example

Attributes Property Example (MDB)

The following example checks the Attributes property for each table in the current database, and prints the names of system and hidden tables provided by the Microsoft Jet database engine.

Note that the And operator performs a bitwise comparison to determine whether an attribute is currently set.

Sub CheckAttributes()
    Dim dbs As Database, tdf As TableDef

    ' Return reference to current database.
    Set dbs = CurrentDb
    For Each tdf In dbs.TableDefs
        ' Compare property setting and constant in question.
        If (tdf.Attributes And dbSystemObject) Or _
                (tdf.Attributes And dbHiddenObject) Then
            Debug.Print tdf.Name
        End If
    Next tdf
    Set dbs = Nothing
End Sub


BaseConnectionString Property Example

The following example displays the BaseConnectionString property setting of the current project:

Dim objCurrent As Object
Set objCurrent = Application.CurrentProject
MsgBox "The current base connection is " _
    & objCurrent.BaseConnectionString


 BeginGroup Property

BeginGroup Property

In Microsoft Access 2000, you can use the Toolbar Control Properties dialog box for command bar controls to determine whether or not a control on a command bar is at the beginning of a group of controls. A separator bar is displayed before the control on the command bar. Display the Customize dialog box by pointing to Toolbars on the View menu and clicking Customize. For menu bar and toolbar controls, display the menu bar or toolbar, and then right-click the control whose BeginGroup property you want to set. For shortcut menu controls, select the Shortcut Menus check box on the Toolbars tab of the Customize dialog box, then find the shortcut menu control you want on the menu bar that's displayed and right-click the control. Click the Properties command. Select or clear the Begin A Group check box.

The separator bar that appears at the beginning of a group of controls isn't a control itself, and doesn't affect item counts or indexes in the CommandBarControls collection.


BOF, EOF Properties Example

BOF, EOF Properties Example (MDB)

The following example uses the EOF property of a Recordset object to move the current record pointer past the last record in the Recordset object, then uses the BOF property to move the current record pointer to before the first record in the Recordset object.

Sub EndsOfFile()
    Dim dbs As Database, rst As Recordset

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Open recordset on Orders table.
    Set rst = dbs.OpenRecordset("Orders")
    ' Do until end of file.
    Do Until rst.EOF
        ' Move to next record.
        rst.MoveNext
        .
        .
        .
    Loop
    ' Move to last record to set a current record.
    rst.MoveLast
    ' Do until beginning of file.
    Do Until rst.BOF
        rst.MovePrevious
        .
        .
        .
    Loop
    rst.Close
    Set dbs = Nothing
End Sub


Bookmark Property

The Bookmark property applies to the Recordset object. You can set it only using Visual Basic

Note Don't confuse this property with the Microsoft Access Bookmark property, which applies to a Form object and stores a bookmark for a particular record in the table or query underlying the form. These two properties don't interfere with each other; you can have separate bookmarks on a form and on a Recordset object at the same time.


Bookmark 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 ADO Bookmark property, which moves the form's current record to the found name.

Private Sub cmdFindContactName_Click()
    Dim rst As adodb.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 If
End Sub


BorderColor, BackColor, ForeColor Properties Example

The following example uses the RGB function to set the BorderColor, BackColor, and ForeColor properties depending on the value of the txtPastDue text box. You can also use the QBColor function to set these properties. Putting the following code in the Form_Current( ) event sets the control display characteristics as soon as the user opens a form or moves to a new record.

Sub Form_Current()
    Dim curAmntDue As Currency, lngBlack As Long
    Dim lngRed As Long, lngYellow As Long, lngWhite As Long

    If Not IsNull(Me!txtPastDue.Value) Then
        curAmntDue = Me!txtPastDue.Value
    Else
        Exit Sub
    End If
    lngRed = RGB(255, 0, 0)
    lngBlack = RGB(0, 0, 0)
    lngYellow = RGB(255, 255, 0)
    lngWhite = RGB(255, 255, 255)
    If curAmntDue > 100 Then
        Me!txtPastDue.BorderColor = lngRed
        Me!txtPastDue.ForeColor = lngRed
        Me!txtPastDue.BackColor = lngYellow
    Else
        Me!txtPastDue.BorderColor = lngBlack
        Me!txtPastDue.ForeColor = lngBlack
        Me!txtPastDue.BackColor = lngWhite
    End If
End Sub


BuiltIn Property 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 ref
End Sub


 Calendar Property

Calendar Property

Language-specific information

The Calendar property specifies or determines a value that indicates the calendar to be used by Visual Basic date-related functions.

Setting

The Calendar property uses the following settings.

Setting | Visual Basic | Description
Gregorian | 0 | (Default) Gregorian calendar will be used for Visual Basic date-related calculations and formatting.
Hijri | 1 | Hijri calendar will be used Visual Basic date-related calculations and formatting.

Note Microsoft Access 2000 date-related processing is done in Visual Basic. When Access 2000 opens a database, the Calendar property for Visual Basic is set according to the value of the Calendar database property. If a Visual Basic procedure changes the Visual Basic Calendar property, it is the responsibility of the procedure to restore the Calendar setting needed by Access 2000 before quitting.

The language of Hijri month names is always Arabic. Hijri month names are always returned in full month name format.

For more information about the Calendar database property, see Use database calendars.


Calendar Property Example

The following example creates a function to convert dates strings between the supported calendar systems. The example code that follows uses the function to convert a Gregorian date string to the equivalent Hijri string in long date format.

Function ConvertDateString ( _
        ByRef StringIn As String, _
        ByVal OldCalendar As Integer, _
        ByVal NewCalendar As Integer, _
        ByRef NewFormat As String) As String
    Dim SavedCal As Integer
    Dim d As Date
    Dim s As String

    ' Save Access calendar to restore when finished
    SavedCal = Calendar

    ' Convert date to new calendar and format
    Calendar = OldCalendar    ' Change to StringIn calendar
    d = Cdate (StringIn)        ' Convert from String to Date
    Calendar = NewCalendar    ' Change to calendar of new string
    s = CStr(d)            ' Convert to short format String
    ConvertDateString = Format (s, NewFormat)    'Reformat
    Calendar = SavedCal
End Function

Call ConvertDateString function from a procedure to perform conversion…

Sub MySub
    Dim GregorianDate As String
    Dim HijriDate As String
    Dim GregorianCalendar As Integer
    Dim HijriCalendar As Integer
    Dim HijriFormat As String
    GregorianDate = #12/31/93#
    GregorianCalendar = 0
    HijriCalendar = 1
    HijriFormat = "Long Date"
    ' Returns 7/18/1414
    HijriDate = ConvertDateString (GregorianDate, _
        GregorianCalendar, HijriCalendar, HijriFormat)
End Sub


 Caption Property (Command Bars)

Caption Property (Command Bars)

In Microsoft Access 2000, you can use the Toolbar Control Properties dialog box for command bar controls to set the caption for a control on a command bar. Display the Customize dialog box by pointing to Toolbars on the View menu and clicking Customize. For menu bar and toolbar controls, display the menu bar or toolbar, and then right-click the control whose Caption property you want to set. For shortcut menu controls, select the Shortcut Menus check box on the Toolbars tab of the Customize dialog box, then find the shortcut menu control you want on the menu bar that's displayed and right-click the control. Click the Properties command. Enter the caption you want in the Caption box.

When you display a control's Caption property setting in the Toolbar Control Properties dialog box or in Visual Basic, the ampersand (&) for the accelerator key is displayed (for example, &Paste). When you reference the control in Visual Basic, you can choose to include the ampersand (or not). For example, the following references are identical:

CommandBars("Menu Bar").Controls("Tools")
CommandBars("Menu Bar").Controls("&Tools")

When setting the Caption property, you must include the ampersand if you want the control to have an accelerator key.


CheckIfOfficeIsHTMLEditor Property Example

This example causes the default system HTML editor to be used (instead of Office applications) when editing a Web page.

Application.DefaultWebOptions.CheckIfOfficeIsHTMLEditor = False


CodeContextObject Property 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 If
End Sub

Function ErrorMessage(strText As String, intType As Integer, _
        intErrVal As Integer) As Integer
    Dim objCurrent As Object
    Dim strMsgboxTitle As String
    Set objCurrent = CodeContextObject
    strMsgboxTitle = "Error in " & objCurrent.Name
    strText = strText & "Error #" & intErrVal _
        & " occured in " & objCurrent.Name
    ErrorMessage = MsgBox(strText, intType, strMsgboxTitle)
    Err = 0
End Function


CollatingOrder Property Example

CollatingOrder Property Example (MDB)

The following example checks the CollatingOrder property for the current database:

Sub SetSortOrder()
    Dim dbs As Database

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Check CollatingOrder property for database.
    Debug.Print dbs.CollatingOrder
    Set dbs = Nothing
End Sub


ColumnHeadings Property 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 Products
INNER JOIN (Orders INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID)
ON Products.ProductID = [Order Details].ProductID
WHERE (((Orders.ShippedDate) Between #1/1/94# And #12/31/94#))
GROUP BY Products.ProductName PIVOT "Qtr " & DatePart("q",[ShippedDate],1,0);


ColumnHidden Property Example

The following example hides the ProductID field in Datasheet view of the Products form.

Forms!Products!ProductID.ColumnHidden = -1

The next example also hides the ProductID field in Datasheet view of the Products table. To set the ColumnHidden property, the example uses the ShowColumn and SetFieldProperty procedures, which are in the database's standard module.

Dim dbs As Object
Set dbs = CurrentDb
ShowColumn dbs.TableDefs!Products.Fields!ProductID, False

Sub ShowColumn(fldObject As Variant, intShow As Integer)
    ' Set ColumnHidden property.
    SetFieldProperty fldObject, "ColumnHidden", dbLong, Not intShow
End Sub

Sub SetFieldProperty(fldField As Variant, strPropertyName As String, _
        intPropertyType As Integer, varPropertyValue As Variant)
    ' Set field property without producing nonrecoverable run-time error.
    Const conErrPropertyNotFound = 3270
    Dim prpProperty As Variant
    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 If
End Sub


ColumnOrder Property Example

The following example displays the ProductName and QuantityPerUnit fields in the first two columns in Datasheet view of the Products form.

Forms!Products!ProductName.ColumnOrder = 1
Forms!Products!QuantityPerUnit.ColumnOrder = 2

The next example displays the ProductName and QuantityPerUnit fields in the first two columns of the Products table in Datasheet view. To set the ColumnOrder property, the example uses the SetFieldProperty procedure. 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 TableDef
Set dbs = CurrentDb
Set tdfProducts = dbs!Products
SetFieldProperty tdfProducts!ProductName, "ColumnOrder", dbLong, 2
SetFieldProperty 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 If
End Sub


Column, ColumnCount Properties 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

    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 If
End Sub


CommandBars Property 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 9.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 If
End 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 If
End Sub


 Type Property (Command Bars)

Type Property (Command Bars)

In Microsoft Access 2000, you can use the Toolbar Properties dialog box to change the type of a custom menu bar, toolbar, or shortcut menu. Point to Toolbars on the View menu and click Customize, then click the Properties button in the Customize dialog box. Select the custom menu bar, toolbar, or shortcut menu you want in the Selected Toolbar box, and then select the new type for the menu bar, toolbar, or shortcut menu in the Type box. You can't change the type of a built-in menu bar, toolbar, or shortcut menu.

If you set the type of a command bar to "Popup", the command bar disappears from the Toolbars list in the Customize dialog box. The command bar moves to the menu bar that's displayed when you select the Shortcut Menus box in the Toolbars list (this menu bar displays all the shortcut menus in Microsoft Access).


ConnectionString Property Example

The following example displays the ConnectionString property setting of the currently active data access page:

Dim objCurrent As Object
Set objCurrent = Application.DataAccessPages(0)
MsgBox "The current base connection is " _
    & objCurrent.ConnectionString


Connect, SourceTableName Properties Example

Connect, SourceTableName Properties Example (MDB)

The following example creates a TableDef object in the specified database. The procedure then sets its Connect and SourceTableName properties and appends the object to the TableDefs collection.

Sub ConnectSource()
    Dim dbs As Database, tdf As TableDef

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create new TableDef object.
    Set tdf = dbs.CreateTableDef("PDXAuthor")
    ' Attach Paradox table Author in database C:\PDX\Publish.
    tdf.Connect = "Paradox 4.X;Database=C:\PDX\Publish"
    tdf.SourceTableName = "Author"
    dbs.TableDefs.Append tdf
    Set dbs = Nothing
End Sub


Container, Permissions Properties Example

Container, Permissions Properties Example (MDB)

The following example determines the name of the Container object to which a Document object belongs, and sets permissions accordingly for the specified group account. Remember that you must denote a particular user or group account before you set permissions for an object. The following example assumes that you have defined a Marketers group.

Microsoft Access defines additional Container objects beyond those defined by the Microsoft Jet database engine. These include the Form, Report, Script, and Module Container objects.

Note that the Or operator performs a bitwise comparison to determine whether an attribute is currently set.

Sub SetDocPermissions(docUnknown As Document)
    Dim strContainerName As String

    ' Set UserName property to valid existing group account.
    docUnknown.UserName = "Marketers"
    ' Get value of Container property.
    strContainerName = docUnknown.Container.Name
    Select Case strContainerName
        Case "Forms"
            ' Set permissions for Form Document object.
            docUnknown.Permissions = docUnknown.Permissions Or _
                acSecFrmRptWriteDef
        Case "Reports"
            ' Set permissions for Report Document object.
            docUnknown.Permissions = docUnknown.Permissions Or _
                acSecFrmRptExecute
        Case "Scripts"
            ' Set permissions for Script Document object.
            docUnknown.Permissions = docUnknown.Permissions Or _
                acSecMacWriteDef
        Case "Modules"
            ' Set permissions for Module Document object.
            docUnknown.Permissions = docUnknown.Permissions Or _
                acSecModReadDef
        Case Else
            Exit Sub
    End Select
End Sub


Context Property

This property is not supported in Microsoft Access.


ControlBox Property Example

The following example sets the ControlBox property on the WarningDialog form to False (0):

Forms!WarningDialog.ControlBox = False


ControlSource Property Example

The following example sets the ControlSource property for a text box named AddressPart to a field named City:

Forms!Customers!AddressPart.ControlSource = "City"

The next example sets the ControlSource property for a text box named Expected to the expression =Date() + 7.

Me!Expected.ControlSource = "=Date() + 7"


ControlType, AllowAdditions, AllowDeletions, AllowEdits Properties Example

The following example examines the ControlType property for all controls on a form. For each label and text box control, the procedure toggles the SpecialEffect property for those controls. When the label controls' SpecialEffect property is set to Shadowed and the text box controls' SpecialEffect property is set to Normal and the AllowAdditions, AllowDeletions, and AllowEdits properties are all set to True, 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 = IFalse Then
        With frm
            .AllowAdditions = False
            .AllowDeletions = False
            .AllowEdits = False
        End With
    Else
        With frm
            .AllowAdditions = True
            .AllowDeletions = True
            .AllowEdits = True
        End With
    End If
End Sub


CountOfLines, CountOfDeclarationLines Properties 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.CountOfDeclarationLines
End Function


Count Property 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 If
End 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 Integer
Dim intReportControls As Integer
intFormControls = Forms!Employees.Count
intReportControls = Reports!FreightCharges.Count


CurrentObjectType, CurrentObjectName Properties Example

The following example uses the CurrentObjectType and CurrentObjectName properties with the SysCmd function to determine if the active object is the Products form and if this form is open and has been changed but not saved. If these conditions are true, the form is saved and then closed.

Sub CheckProducts()
    Dim intState As Integer
    Dim intCurrentType As Integer
    Dim strCurrentName As String

    intCurrentType = Application.CurrentObjectType
    strCurrentName = Application.CurrentObjectName
    If intCurrentType = acForm And strCurrentName = "Products" Then
        intState = SysCmd(acSysCmdGetObjectState, intCurrentType, _
             strCurrentName)
        ' Products form changed but not saved.
        If intState = acObjStateDirty + _
            acObjStateOpen Then
            ' Close Products form and save changes.
            DoCmd.Close intCurrentType, _
                strCurrentName, acSaveYes
        End If
    End If
End Sub


CurrentPage, PageCount Properties Example

The following example shows how to use the CurrentPage and PageCount properties to navigate to a page within a snapshot file.

Sub Navigate()
    Dim lngPageNum As Long
    Dim snpCtl As SnapshotViewer
    Set snpCtl = Me.SnapShot1.Object
    lngPageNum = InputBox("Enter snapshot page to display")
    If IsNumeric(lngPageNum) And Len(lngPageNum) > 0 Then
        If lngPageNum <= snpCtl.PageCount Then
            snpCtl.CurrentPage = lngPageNum
        Else
            Msgbox "Please enter a value between 1 and " _
                & snpCtl.PageCount
            Exit Sub
        End If
    End If
End Sub


CurrentRecord Property Example

The following example shows how to use the CurrentRecord property to determine the record number of the current record being displayed. The general-purpose CurrentFormRecord procedure assigns the value of the current record to the variable lngrecordnum.

Sub CurrentFormRecord(frm As Form)
    Dim lngrecordnum As Long

    lngrecordnum = frm.CurrentRecord
End Sub


CurrentSectionLeft, CurrentSectionTop Properties Example

The following example displays the CurrentSectionLeft and CurrentSectionTop property settings for a control on a continuous form. Whenever the user moves to a new record, the property settings for the current section are displayed in the lblStatus label in the form's header.

Private Sub Form_Current()
    Dim intCurTop As Integer, intCurLeft As Integer

    intCurTop = Me.CurrentSectionTop
    intCurLeft = Me.CurrentSectionLeft
    Me!lblStatus.Caption = intCurLeft & " , " & intCurTop
End Sub


CurrentView Property 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 Select
End Sub


AllowZeroLength Property Example

AllowZeroLength Property Example (MDB)

The following example creates a new Field object and sets its AllowZeroLength property to True (–1):

Sub ZeroLengthField()
    Dim dbs As Database, tdf As TableDef, fld As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Employees table.
    Set tdf = dbs.TableDefs!Employees
    ' Create new field in Employees table.
    Set fld = tdf.CreateField("SpouseName", dbText, 15)
    ' Allow zero-length strings in field.
    fld.AllowZeroLength = True
    ' Append Field object.
    tdf.fields.Append fld
    Set dbs = Nothing
End Sub


Bookmark, Bookmarkable Properties Example

Bookmark, Bookmarkable Properties Example (MDB)

The following example moves through the records of the Employees table from the beginning of the file to the end and stores the value of the Bookmark property for each record in an array.

' Include this statement in Declarations section of module.
Option Compare Binary

Sub RecordPositions()
    Dim dbs As Database, rst As Recordset, fld As Field
    Dim intI As Integer
    ' Declare array to hold bookmarks.
    Dim varRecord() As Variant

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Open table-type Recordset object.
    Set rst = dbs.OpenRecordset("Employees")
    ' Return reference to LastName field.
    Set fld = rst.Fields!LastName
    ' Redimension array with value of RecordCount
    ' property as upper bound.
    ReDim varRecord(0 To rst.RecordCount - 1)
    intI = 0
    ' Check Bookmarkable property of Recordset object.
    If rst.Bookmarkable Then
        Do Until rst.EOF
            ' Populate array with bookmarks.
            varRecord(intI) = rst.Bookmark
            ' Increment counter.
            intI = intI + 1
            rst.MoveNext
        Loop
    End If
    rst.Close
    Set dbs = Nothing
End Sub


Count Property Example

Count Property Example (MDB)

The following example prints the names and total number of fields in an Orders table:

Sub CountFields()
    Dim dbs As Database, tdf As TableDef
    Dim fld As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Orders table.
    Set tdf = dbs.TableDefs!Orders
    ' Count fields in Fields collection of TableDef object.
    Debug.Print tdf.Fields.Count
    ' List names of all fields.
    For Each fld In tdf.Fields
        Debug.Print fld.Name
    Next fld
    Set dbs = Nothing
End Sub


DefaultValue Property Example

DefaultValue Property Example (MDB)

The following example creates a new Field object and sets its DefaultValue property. The procedure then appends the new object to the Fields collection of the Employees table in the TableDefs collection of the database.

Sub NewField()
    Dim dbs As Database, tdf As TableDef
    Dim fld As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Employees table.
    Set tdf = dbs.TableDefs!Employees
    ' Create Field object.
    Set fld = tdf.CreateField("DaysOfVacation", dbText, 20)
    ' Set field properties.
    fld.DefaultValue = "10"
    ' Append fld to Fields collection.
    tdf.Fields.Append fld
    Set dbs = Nothing
End Sub


 FieldSize Property (MDB)

FieldSize Property (MDB)

The DAO FieldSize property is different from the Microsoft Access FieldSize property, which is set in table Design view. The DAO FieldSize property returns the number of bytes in a Field object of type Memo or OLE Object.

You set the Microsoft Access FieldSize property in order to limit the size of a field in a table. The FieldSize property is only available in table Design view. From Visual Basic, use the Size property to set the size of a field in a table.


Filter Property Example

Filter Property Example (MDB)

The following example prompts the user to enter the name of a country on which to filter, and then sets the Filter property of a dynaset-type Recordset object. For example, if the user enters "Italy", the filtered recordset will contain only those records in which the ShipCountry field contains the string "Italy".

Note that you first create a dynaset-type Recordset object and set its Filter property, then open a second dynaset-type Recordset object based on the first. Setting the Filter property of the first Recordset object doesn't actually affect the records that it contains, so you need to create a second Recordset object in order to see the effects of the filter.

Sub SetRecordsetFilter()
    Dim dbs As Database, strInput As String
    Dim rstOrders As Recordset, rstFiltered As Recordset

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Prompt for value on which to filter.
    strInput = InputBox("Enter name of country on "
        & "which to filter.")
    ' Create dynaset-type Recordset object.
    Set rstOrders = dbs.OpenRecordset("Orders", dbOpenDynaset)
    ' Set filter condition.
    rstOrders.Filter = "ShipCountry = '" & strInput & "'"
    ' Create filtered dynaset-type Recordset object.
    Set rstFiltered = rstOrders.OpenRecordset
    rstOrders.Close
    rstFiltered.Close
    Set dbs = Nothing
End Sub

Tip In most situations, it's more efficient to create the second Recordset object with the desired conditions in one step. When you know what data you want to select, it's generally more efficient to create a recordset with an SQL statement. The next example shows how you can create just one recordset and obtain the same results as in the preceding example:

Sub CreateRecordsetWithSQL()
    Dim dbs As Database, rst As Recordset
    Dim strInput As String

    Set dbs = CurrentDb
    strInput = InputBox("Enter name of country on which to filter.")
    Set rst = dbs.OpenRecordset("SELECT * FROM " _
        & "Orders WHERE ShipCountry = '" & strInput _
        & "';")
    rst.MoveLast
    MsgBox "Recordset contains " & rst.RecordCount & " records."
    rst.Close
    Set dbs = Nothing
End Sub


IgnoreNulls, Unique Properties Example

IgnoreNulls, Unique Properties Example (MDB)

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
    Set dbs = Nothing
End Sub


Name Property Example

Name Property Example (MDB)

The following example creates two new TableDef objects and names them. The name of the first TableDef object is included as an argument to the CreateTableDef method. The name of the second TableDef object is set by using the Name property, after the TableDef object has been created.

Note that you must define fields in the table before the TableDef object can be appended to the TableDefs collection.

Sub NameNewTables()
    Dim dbs As Database
    Dim tdfDefinitions As TableDef, tdfSynonyms As TableDef

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create new TableDef object.
    Set tdfDefinitions = dbs.CreateTableDef("Definitions")
    ' Create second TableDef object.
    Set tdfSynonyms = dbs.CreateTableDef("")
    ' Set Name property for second TableDef object.
    tdfSynonyms.Name = "Synonyms"
    .                            ' Create fields.
    .
    .
    dbs.TableDefs.Append tdfDefinitions
    dbs.TableDefs.Append tdfSynonyms
    Set dbs = Nothing
End Sub


ODBCTimeout Property Example

ODBCTimeout Property Example (MDB)

The following example sets the ODBCTimeout property to 120 seconds, creates a query, and runs it on a database on an ODBC server:

Sub SetTimeout()
    Dim dbs As Database
    Dim qdf As QueryDef, rst As Recordset

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create new QueryDef object.
    Set qdf = dbs.CreateQueryDef("All Cust", _
        "SELECT * FROM Customers;")
    qdf.Connect = "ODBC;DSN=HumanResources;SERVER=HRSRVR: " _
        & "UID=Smith; PWD=Sesame"
    ' Log on to server and run query.
    qdf.ODBCTimeout = 120
    Set rst = qdf.OpenRecordset()
    ' Perform operations with recordset.
    .
    .
    .
    rst.Close
    Set dbs = Nothing
End Sub


Primary Property Example

Primary Property Example (MDB)

The following example checks the Primary property of each index on a Products table, and prints the fields making up the primary key:

Sub SetIndex()
    Dim dbs As Database, tdf As TableDef, fld As Field
    Dim idx As Index

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Products table.
    Set tdf = dbs.TableDefs!Products
    ' Enumerate through Indexes collection of TableDef object.
    For Each idx In tdf.Indexes
        ' Check Primary property of Recordset object.
        If idx.Primary Then
            For Each fld In idx.Fields
                Debug.Print fld.Name
            Next fld
        End If
    Next idx
    Set dbs = Nothing
End Sub


Required Property Example

Required Property Example (MDB)

The following example creates a new Index object on an Employees table and sets the Required property for the index. The new index consists of two fields, LastName and FirstName.

Sub NewIndex()
    Dim dbs As Database, tdf As TableDef, idx As Index
    Dim fldLastName As Field, fldFirstName As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Employees table.
    Set tdf = dbs.TableDefs!Employees
    ' Create new index.
    Set idx = tdf.CreateIndex("FullName")
    ' Create and append index fields.
    Set fldLastName = idx.CreateField("LastName", dbText)
    Set fldFirstName = idx.CreateField("FirstName", dbText)
    idx.Fields.Append fldLastName
    idx.Fields.Append fldFirstName
    ' Ensure value is entered for each field in index.
    idx.Required = True
    ' Append Index object.
    tdf.Indexes.Append idx
    Set dbs = Nothing
End Sub


ValidationRule, ValidationText Properties Example

ValidationRule, ValidationText Properties Example (MDB)

The following example sets the ValidationRule and ValidationText properties for two fields in an Order Details table. Once these properties have been set, you can view them in table Design view as well.

Sub SetValidation()
    Dim dbs As Database, tdf As TableDef
    Dim fldQuantity As Field, fldDiscount As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return referent to Order Details table.
    Set tdf = dbs.TableDefs![Order Details]
    Set fldQuantity = tdf.Fields!Quantity
    Set fldDiscount = tdf.Fields!Discount
    ' Set ValidationRule and ValidationText.
    fldQuantity.ValidationRule = ">= 4"
    fldQuantity.ValidationText = "Quantity must be " _
        & "four or more items."
    fldDiscount.ValidationRule = "Between .05 and .30"
    fldDiscount.ValidationText = "Discount must be " _
        & "between 5% and 30%."
    Set dbs = Nothing
End Sub


Database Properties Example

In the following example, you can set or create a custom user-defined property that will appear on the Custom tab of the 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 = True

SetCustom_Bye:
    Exit Function

SetCustom_Err:
    If Err = conPropertyNotFound Then
        Set prp = doc.CreateProperty(strPropName, intPropType, strPropValue)
        doc.Properties.Append prp        ' Append to collection.
        Resume Next
    Else                                        ' Unknown error.
        SetCustomProperty = False
        Resume SetCustom_Bye
    End If
End Function

The next example demonstrates how to display information from the Summary tab of the 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"
    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 If
End Function


DatasheetBackColor, DatasheetForeColor Properties 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 property is set, the CreateProperty method is used to add the property to the object's Properties collection.

Dim dbs As Object, objProducts As Object
Const lngForeColor As Long = 8388608        ' Dark blue.
Const lngBackColor As Long = 12632256        ' Light gray.
Const DB_Long As Long = 4
Set dbs = CurrentDb
Set objProducts = dbs!Products
SetTableProperty objProducts, "DatasheetBackColor", DB_Long, lngBackColor
SetTableProperty objProducts, "DatasheetForeColor", DB_Long, lngForeColor

Sub SetTableProperty(objTableObj As Object, strPropertyName As String, _
        intPropertyType As Integer, varPropertyValue As Variant)
    Const conErrPropertyNotFound = 3270
    Dim prpProperty As Variant
    On Error Resume Next                ' Don't trap errors.
    objTableObj.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 = objTableObj.CreateProperty(strPropertyName, _
                intPropertyType, varPropertyValue)
            objTableObj.Properties.Append prpProperty
            Err.Clear
        End If
    End If
    objTableObj.Properties.Refresh
End Sub


DatasheetFontItalic, DatasheetFontUnderline Properties Example

The following example displays the data and field names in Datasheet view of the Products form as italic and underlined.

Forms![Products].DatasheetFontItalic = True
Forms![Products].DatasheetFontUnderline = True

The next example displays the data and field names in Datasheet view of the Products table as italic and underlined.

To set the DatasheetFontItalic and DatasheetFontUnderline properties, the example uses the SetTableProperty procedure, which is in the database's standard module.

Dim dbs As Object, objProducts As Object
Const DB_Boolean As Long = 1
Set dbs = CurrentDb
Set objProducts = dbs![Products]
SetTableProperty objProducts, "DatasheetFontItalic", DB_Boolean, True
SetTableProperty objProducts, "DatasheetFontUnderline", DB_Boolean, True

Sub SetTableProperty(objTableObj As Object, 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 Variant
    On Error Resume Next                ' Don't trap errors.
    objTableObj.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 '" & objTableObj.Name & "'", 48, "SetTableProperty"
        Else
            On Error GoTo 0
            Set prpProperty = objTableObj.CreateProperty(strPropertyName, _
                intPropertyType, varPropertyValue)
            objTableObj.Properties.Append prpProperty
        End If
    End If
    objTableObj.Properties.Refresh
End Sub


DatasheetFontName, DatasheetFontHeight, DatasheetFontWeight Properties 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 Object, objProducts As Object
Set dbs = CurrentDb
Const DB_Text As Long = 10
Const DB_Integer As Long = 3
Set objProducts = dbs!Products
SetTableProperty objProducts, "DatasheetFontName", DB_Text, "MS Serif"
SetTableProperty objProducts, "DatasheetFontHeight", DB_Integer, 10
SetTableProperty objProducts, "DatasheetFontWeight", DB_Integer, 500

The next example makes the same changes as the preceding example in Datasheet view of the open Products form.

Forms!Products.DatasheetFontName = "MS Serif"
Forms!Products.DatasheetFontHeight = 10
Forms!Products.DatasheetFontWeight = 500


 DataType Property

DataType Property

Language-specific information

Microsoft Access 2000 has revised the DataType property so the Date/Time setting can accommodate the Hijri calendar.

Remarks

If Hijri is the current Visual Basic Calendar setting, Access 2000 stores date and time values for the Hijri years 100 to 9666. More specifically, the supported Hijri date range is 1/1/100 (Gregorian Aug 2, 718) through 4/3/9666 (Gregorian Dec 31, 9999).


DataUpdatable Property Example

DataUpdatable Property Example (MDB)

The following example creates two Recordset objects, a dynaset-type Recordset object and a snapshot-type Recordset object, from the same table. The procedure then checks the DataUpdatable property for the LastName field in each Recordset object. The setting of the DataUpdatable property is True (–1) for the dynaset-type Recordset object, and False (0) for the snapshot-type Recordset object.

Sub CheckUpdatable()
    Dim dbs As Database
    Dim rstDynaset As Recordset, rstSnapshot As Recordset
    Dim fldDynaset As Field, fldSnapshot As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Open dynaset-type Recordset object.
    Set rstDynaset = dbs.OpenRecordset("Employees", _
        dbOpenDynaset)
    ' Open snapshot-type Recordset object.
    Set rstSnapshot = dbs.OpenRecordset("Employees", _
        dbOpenSnapshot)
    ' Get Field object variables pointing to field in
    ' each Recordset object.
    Set fldDynaset = rstDynaset.Fields!LastName
    Set fldSnapshot = rstSnapshot.Fields!LastName
    ' Get current record.
    rstDynaset.MoveFirst
    rstSnapshot.MoveFirst
    ' Display value of DataUpdatable property for each
    ' Recordset object.
    Debug.Print "DataUpdatable (Dynaset-type Recordset): "; _
        fldDynaset.DataUpdatable
    Debug.Print "DataUpdatable (Snapshot-type Recordset): "; _
        fldSnapshot.DataUpdatable
    rstDynaset.Close
    rstSnapshot.Close
    Set dbs = Nothing
End Sub


DateCreated, LastUpdated Properties Example

DateCreated, LastUpdated Properties Example (MDB)

The following example enumerates through all QueryDef objects in the database and lists those which have been created or changed within the last sixty days:

Sub TimeUpdated()
    Dim dbs As Database, tdf As TableDef, qdf As QueryDef
    Dim strList As String, dtePast As Date

    ' Return reference to current database.
    Set dbs = CurrentDb
    dtePast = Date - 60
    ' Enumerate through QueryDefs collection.
    For Each qdf In dbs.QueryDefs
        ' Evaluate LastUpdated and DateCreated properties.
        If (qdf.LastUpdated > dtePast) Or (qdf.DateCreated > dtePast) Then
            ' Create list.
            strList = strList & vbCrLf & qdf.Name
        End If
    Next qdf
    MsgBox strList
    Set dbs = Nothing
End Sub


 DefaultValue Property

DefaultValue Property

If the ADO DefaultValue property setting is an expression, it can't contain user-defined functions, Microsoft Access domain aggregate functions, SQL aggregate functions, the CurrentUser function, the Eval function, or references to queries, forms, or other Field objects.


 DefaultValue Property (MDB)

DefaultValue Property (MDB)

In Microsoft Access, if you set the DAO DefaultValue property to GenUniqueID( ) to create an AutoNumber field, you must also set the Attributes property to dbAutoIncrement. If you don't set the Attributes property in this way, Microsoft Access won't assign the AutoNumber data type to the field, and you'll get an error when you try to view the table in Datasheet view.

The following code shows how you can create a field with the AutoNumber data type, given a TableDef object variable tdf and a Field object variable fld.

Set fld = tdf.CreateField("EmployeeID", dbLong)
fld.DefaultValue = "GenUniqueID()"
fld.Attributes = dbAutoIncrField
tdf.Fields.Append fld

If the DAO DefaultValue property setting is an expression, it can't contain user-defined functions, Microsoft Access domain aggregate functions, SQL aggregate functions, the CurrentUser function, the Eval function, or references to queries, forms, or other Field objects.


 DefinedSize Property

DefinedSize Property

The ADO DefinedSize property is equivalent to the Size property in DAO as well as the FieldSize property in table Design view. Use the DefinedSize property to set the FieldSize using Visual Basic.

Note In Microsoft Access, the Memo data type field can contain up to 2.14 gigabytes of information. However, the amount of data displayed in a control on a form or report is limited by the amount of system memory.


Description Property

The Description property applies to the Error object and returns a string associated with an error. You can access it only by using Visual Basic.

Note Don't confuse this property with the Microsoft Access Description property, which describes a table or query and its fields.


DestConnectStr, DestinationDB, DestinationTable Properties 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'
SELECT Customer.[CompanyName], Customer.Phone
FROM 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.Phone
INTO Contacts IN 'C:\Pdoxdata' [Paradox 3.x;] FROM Customer;


Dirty Property Example

The following example enables the btnUndo button when data is changed. The UndoEdits( ) subroutine is called from the AfterUpdate event of text box controls. Clicking the enabled btnUndo button restores the original value of the control 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 If
End 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 ctlC
End Sub


DistinctCount Property Example

DistinctCount Property Example (MDB)

The following example prints the number of unique values in the indexes on the OrderID and OrderDate fields of an Orders table. Note that the DistinctCount property is guaranteed to return the number of unique values in an index only immediately after an index has been created with the CreateIndex method, or after a database has been compacted or converted by using the CompactDatabase method.

Sub CountKeys()
    Dim dbs As Database, tdf As TableDef
    Dim idx As Index, fldOrderID As Field, fldOrderDate As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Orders table.
    Set tdf = dbs.TableDefs!Orders
    ' Create new index.
    Set idx = tdf.CreateIndex("OrderDateIndex")
    ' Create and append index fields.
    Set fldOrderDate = idx.CreateField("OrderDate", dbDate)
    idx.Fields.Append fldOrderDate
    ' Append new index.
    tdf.Indexes.Append idx
    ' Refresh Indexes collection.
    tdf.Indexes.Refresh
    ' Print value of DistinctCount property for new index.
    Debug.Print idx.DistinctCount
    Set dbs = Nothing
End Sub


CurrentProject Object, Document, and IsLoaded Property Example

This procedure illustrates how to use VBA code to add text to a data access page. The following information is supplied in the arguments to this procedure:

strPageName | The name of an existing data access page.
strID | The ID property (attribute) for the tag that contains the text you want to work with.
strText | The text to insert.
blnReplace | Whether to replace existing text in the tag.

Function DAPInsertText(strPageName As String, _
    strID As Variant, strText As String, _
    Optional blnReplace As Boolean = True) As Boolean

    Dim blnWasLoaded As Boolean

    On Error GoTo DAPInsertText_Err

    ' Determine if the page exists and whether it is
    ' currently open. If not open then open it in
    ' design view.
    If DAPExists(strPageName) = True Then
        If CurrentProject.AllDataAccessPages(strPageName) _
            .IsLoaded = False Then
            blnWasLoaded = False
            With DoCmd
                .Echo False
                .OpenDataAccessPage strPageName, _
                    acDataAccessPageDesign
            End With
        Else
            blnWasLoaded = True
        End If
    Else
        DAPInsertText = False
        Exit Function
    End If

    ' Add the new text to the specified tag.
    With DataAccessPages(strPageName).Document
        If blnReplace = True Then
            .All(strID).innerText = strText
        Else
            .All(strID).innerText = .All(strID).innerText & strText
        End If
        ' Make sure the text is visible.
        With .All(strID).Style
            If .display = "none" Then .display = ""
        End With
    End With

    ' Clean up after yourself.
    With DoCmd
        If blnWasLoaded = True Then
        .Save
    Else
        .Close acDataAccessPage, strPageName, acSaveYes
        End If
    End With
    DAPInsertText = True
DAPInsertText_End:
    DoCmd.Echo True
    Exit Function
DAPInsertText_Err:
    MsgBox "Error #" & Err.Number & ": " & Err.Description
    DAPInsertText = False
    Resume DAPInsertText_End
End Function


DownloadComponents Property Example

This example allows the Office Web components to be downloaded with the specified Web page, if they are not already installed.

Application.DefaultWebOptions.DownloadComponents = True
Application.DefaultWebOptions.LocationOfComponents = _
    Application.CurrentProject & "\foo"


 Enabled Property (FormatCondition Object)

Enabled Property (FormatCondition Object)

You can use the Enabled property to set or return the status of the conditional format in the FormatCondition object.

Setting

The Enabled property setting is a Boolean value that indicates whether the conditional format is enabled or disabled. True (-1) enables the conditional format. False (0) disables the conditional format. The default is True.

The Enabled property is available only by using Visual Basic.

Remarks

When the Enabled property is True, the conditional format can be displayed in the Conditional Formatting dialog box. The Conditional Formatting dialog box is available by clicking Conditional Formatting on the Format menu.


Enabled, Locked Properties - Applies To

Enabled, Locked Properties — Applies To

Enabled Property

Locked Property


 Enabled Property (Command Bars)

Enabled Property (Command Bars)

You can use this property to disable (dimmed) or enable a menu item or command button. This property applies to menu names, submenu names, and items on submenus. The Enabled property replaces the functionality supplied by the SetMenuItem action and SetMenuItem method in Microsoft Access 95.

You can disable a menu item that Microsoft Access would normally enable, but you can't enable a menu item that Microsoft Access would normally disable.


Enabled, Locked Properties Example

The following example toggles the Enabled property of a command button and the Enabled and Locked properties of a control, depending on the type of employee displayed in the current record. If the employee is a manager, then the SalaryDetails button is enabled and the PersonalInfo control is unlocked and enabled.

Sub Form_Current()
    If Me!EmployeeType = "Manager" Then
        Me!SalaryDetails.Enabled = True
        Me!PersonalInfo.Enabled = True
        Me!PersonalInfo.Locked = False
    Else
        Me!SalaryDetails.Enabled = False
        Me!PersonalInfo.Enabled = False
        Me!PersonalInfo.Locked = True
    End If
End Sub


Encoding Property Example

This example checks to see whether the default document encoding is Western.

If Application.DefaultWebOptions.Encoding = msoEncodingWestern Then
    strDocEncoding = "Western"
Else
    strDocEncoding = "Other"
End If


Error, ReadyState, SnapshotPath Properties Example

The following example shows one way to use the Error, ReadyState, and SnapshotPath properties to load a snapshot file into a snapshot control. In this example, snpCtl is a variable representing a snapshot control on a form and strFilePath is the fully-qualified path to a snapshot file to be displayed.

Function LoadSnapshotFile(snpCtl As Object, strFilePath As String) As Boolean
    Const conSnpFinishedDownload As Integer = 4
    With snpCtl
        .SnapshotPath = strFilePath
        Do While .ReadyState < conSnpFinishedDownload
            DoEvents
        Loop
        If .Error = 0 Then
            LoadSnapshotFile = True
            Exit Function
        Else
            MsgBox "Error loading snapshot file", _
                vbOKOnly, "Snapshot Error = " & .Error
            LoadSnapShotFile = False
        End If
    End With
End Function


Event Properties - Visual Basic Example

Event Properties — Visual Basic Example

The following example shows how you can use the value entered in the Country control to determine which of two different macros to run when you click the Print Country Report button.

Private Sub Country_AfterUpdate()
    If Country = "Canada" Then
        [Print Country Report].OnClick = "PrintCanadaReport"
    ElseIf Country = "USA" Then
        [Print Country Report].OnClick = "PrintUSAReport"
    End If
End Sub


Event Properties and Objects They Apply To

Event Property | Applies To
AfterDelConfirm | Forms.
AfterInsert | Forms.
AfterUpdate* | Forms. Controls (bound object frame, check box, combo box, list box, option button, option group, text box, toggle button) on a form.
BeforeDelConfirm | Forms.
BeforeInsert | Forms.
BeforeUpdate* | Forms. Controls (bound object frame, check box, combo box, list box, option button, option group, text box, toggle button) on a form.
OnActivate | Forms and reports.
OnApplyFilter | Forms.
OnChange | Controls (combo box, 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.
OnDeactivate | Forms and reports.
OnDelete | Forms.
OnDirty | 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.
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.
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.
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.

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


FastLaserPrinting Property Example

The following example shows how to set the FastLaserPrinting property for the Invoice report while in report Design view:

DoCmd.OpenReport "Invoice", acDesign
Reports!Invoice.FastLaserPrinting = True
DoCmd.Close acReport, "Invoice", acSaveYes


FeatureInstall Property Example

This example checks the value of the FeatureInstall property. If the property is set to msoFeatureInstallNone, the code displays a message box that asks the user whether they want to change the property setting. If the user responds "Yes", the property is set to msoFeatureInstallOnDemand. The example uses an object variable named MyOfficeApp that is dimensioned as an application object.

With MyOfficeApp
    If .FeatureInstall = msoFeatureInstallNone Then
        Reply = MsgBox("Uninstalled features for " _
            & "this application may " & vbCrLf _
            & "cause a run-time error when called." _
            & vbCrLf & vbCrLf _
            & "Would you like to change this setting" & vbCrLf _
            & "to automatically install missing features?", _
            vbYesNo, "Feature Install Setting")
            If Reply = vbYes Then
                .FeatureInstall = msoFeatureInstallOnDemand
            End If
    End If
End With


FeatureTips Property

This property isn't available in Microsoft Access.


FillColor, FillStyle Properties 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.

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), intColor
End Sub


 Filter Property

Filter Property

The Filter property applies a filter to a Recordset object. You can set it only by using Visual Basic.

Note The Microsoft Access Filter property applies a filter to a form. You can set it by using a macro, Visual Basic, or a form's property sheet in form Design view.


FolderSuffix Property Example

This example returns the folder suffix used by the data access page ("Inventory"). The suffix is returned in the string variable strFolderSuffix.

strFolderSuffix = DataAccessPages("Inventory").WebOptions.FolderSuffix


FontBold Property Example

The following Print event procedure prints a report title and the current date in a bold style on a report at the coordinates specified by the CurrentX and CurrentY property settings.

Private Sub ReportHeader0_Print(Cancel As Integer, _
     PrintCount As Integer)
    Dim MyDate

    MyDate = Date
    Me.FontBold = True
    ' Print report title in bold.
    Me.Print("Sales Management Report")
    Me.Print(MyDate)
End Sub


ForceNewPage Property Example

The following example returns the ForceNewPage property setting for the detail section of the Sales By Date report and assigns it to the intGetVal variable.

Dim intGetVal As Integer
intGetVal = Reports![Sales By Year].Section(acDetail).ForceNewPage


ForeignName, ForeignTable, Table Properties Example

ForeignName, ForeignTable, Table Properties Example (MDB)

The following example shows how you can use the ForeignName, ForeignTable, and Table properties when you create a relationship between two existing tables — in this case, Employees (the primary table) and Orders (the foreign table) in the current database. EmployeeID is the primary key in the Employees table, and also a foreign key in the Orders table. The relationship is one-to-many and referential integrity is enforced.

Note that the And operator performs a bitwise comparison to determine what permissions are currently set.

Sub NewRelation()
    Dim dbs As Database
    Dim fld As Field, rel As Relation

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Find existing EmployeesOrders relation.
    For Each rel In dbs.Relations
        If rel.Table = "Employees" _
            And rel.ForeignTable = "Orders"
            Then
            ' Prompt user before deleting relation.
            If MsgBox(rel.Name & " already exists. " _
                & vbCrLf & "The relation will " _
                & "be deleted and re-created.", _
                    vbOK) = vbOK
            Then
                dbs.Relations.Delete rel.Name
            ' If user chooses Cancel, exit procedure.
            Else
                Exit Sub
            End If
        End If
    Next rel
    ' Create new relationship and set its properties.
    Set rel = dbs.CreateRelation("EmployeesOrders")
    ' Set Table property.
    rel.Table = "Employees"
    ' Set ForeignTable property.
    rel.ForeignTable = "Orders"
    ' Set Relation object attributes to enforce
    ' referential integrity.
    rel.Attributes = dbRelationDeleteCascade And _
        dbRelationUpdateCascade
    ' Create field in Fields collection of Relation.
    Set fld = rel.CreateField("EmployeeID")
    ' Provide name of foreign key field.
    fld.ForeignName = "EmployeeID"
    ' Append field to Relation and Relation to database.
    rel.Fields.Append fld
    dbs.Relations.Append rel
    MsgBox "Relation '" & rel.Name & "' created."
    Set dbs = Nothing
End Sub


Foreign Property Example

Foreign Property Example (MDB)

The following example prints the value of the Foreign property for each index in an Orders table:

Sub CheckForeign()
    Dim dbs As Database, tdf As TableDef, idx As Index

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Orders table.
    Set tdf = dbs.TableDefs!Orders
    ' Enumerate through Indexes collection of table.
    For Each idx In tdf.Indexes
        ' Print value of Foreign property.
        Debug.Print idx.Name; "        "; idx.Foreign
    Next idx
    Set dbs = Nothing
End Sub


 Format Property - Date/Time Data Type

Format Property — Date/Time Data Type

You can set the Format property to predefined date and time formats or use custom formats for the Date/Time data type.

Setting

Predefined Formats

The following table shows the predefined Format property settings for the Date/Time data type.

Setting | Description
General Date | (Default) If the value is a date only, no time is displayed; if the value is a time only, no date is displayed. This setting is a combination of the Short Date and Long Time settings. Examples: 4/3/93, 05:34:00 PM, and 4/3/93 05:34:00 PM.
Long Date | Same as the Long Date setting in the Regional Settings Properties dialog box in Windows Control Panel. Example: Saturday, April 3, 1993.
Medium Date | Example: 3-Apr-93.
Short Date | Same as the Short Date setting in the Regional Settings Properties dialog box in Windows Control Panel. Example: 4/3/93. Warning The Short Date setting assumes that dates between 1/1/00 and 12/31/29 are twenty-first century dates (that is, the years are assumed to be 2000 to 2029). Dates between 1/1/30 and 12/31/99 are assumed to be twentieth century dates (that is, the years are assumed to be 1930 to 1999).
Long Time | Same as the setting on the Time tab in the Regional Settings Properties dialog box in Windows Control Panel. Example: 5:34:23 PM.
Medium Time | Example: 5:34 PM.
Short Time | Example: 17:34.

Custom Formats

You can create custom date and time formats by using the following symbols.

Symbol | Description
: (colon) | Time separator. Separators are set in the Regional Settings Properties dialog box in Windows Control Panel.
/ | Date separator.
c | Same as the General Date predefined format.
d | Day of the month in one or two numeric digits, as needed (1 to 31).
dd | Day of the month in two numeric digits (01 to 31).
ddd | First three letters of the weekday (Sun to Sat).
dddd | Full name of the weekday (Sunday to Saturday).
ddddd | Same as the Short Date predefined format.
dddddd | Same as the Long Date predefined format.
w | Day of the week (1 to 7).
ww | Week of the year (1 to 53).
m | Month of the year in one or two numeric digits, as needed (1 to 12).
mm | Month of the year in two numeric digits (01 to 12).
mmm | First three letters of the month (Jan to Dec).
mmmm | Full name of the month (January to December).
q | Date displayed as the quarter of the year (1 to 4).
y | Number of the day of the year (1 to 366).
yy | Last two digits of the year (01 to 99).
yyyy | Full year (0100 to 9999).
h | Hour in one or two digits, as needed (0 to 23).
hh | Hour in two digits (00 to 23).
n | Minute in one or two digits, as needed (0 to 59).
nn | Minute in two digits (00 to 59).
s | Second in one or two digits, as needed (0 to 59).
ss | Second in two digits (00 to 59).
ttttt | Same as the Long Time predefined format.
AM/PM | Twelve-hour clock with the uppercase letters "AM" or "PM", as appropriate.
am/pm | Twelve-hour clock with the lowercase letters "am" or "pm", as appropriate.
A/P | Twelve-hour clock with the uppercase letter "A" or "P", as appropriate.
a/p | Twelve-hour clock with the lowercase letter "a" or "p", as appropriate.
AMPM | Twelve-hour clock with the appropriate morning/afternoon designator as defined in the Regional Settings Properties dialog box in Windows Control Panel.

Custom formats are displayed according to the settings specified in the Regional Settings Properties dialog box in Windows Control Panel. Custom formats inconsistent with the settings specified in the Regional Settings Properties dialog box are ignored.

Note If you want to add a comma or other separator to your custom format, enclose the separator in quotation marks like this: mmm d", "yyyy.


Format Property - Date/Time Data Type Example

Format Property — Date/Time Data Type Example

The following are examples of custom date/time formats.

Setting | Display
ddd", "mmm d", "yyyy | Mon, Jun 2, 1997
mmmm dd", "yyyy | June 02, 1997
"This is week number "ww | This is week number 22
"Today is "dddd | Today is Tuesday

You could use a custom format to display "A.D." before or "B.C." after a year depending on whether a positive or negative number is entered. To see this custom format work, create a new table field, set its data type to Number and enter a format as follows:

"A.D. " #;# " B.C."

Positive numbers are displayed as years with an "A.D." before the year. Negative numbers are displayed as years with a "B.C." after the year.


 Format Property - Number and Currency Data Types

Format Property — Number and Currency Data Types

You can set the Format property to predefined number formats or custom number formats for the Number and Currency data types.

Setting

Predefined Formats

The following table shows the predefined Format property settings for numbers.

Setting | Description
General Number | (Default) Display the number as entered.
Currency | Use the thousand separator; follow the settings specified in Regional Settings in Windows Control Panel for negative amounts, decimal and currency symbols, and decimal places.
Euro | Use the currency format, with the euro symbol ( [image] ), regardless of the currency symbol specified in Regional Settings in Windows Control Panel.
Fixed | Display at least one digit; follow the settings specified in Regional Settings in Windows Control Panel for negative amounts, decimal and currency symbols, and decimal places.
Standard | Use the thousand separator; follow the settings specified in Regional Settings in Windows Control Panel for negative amounts, decimal symbols, and decimal places.
Percent | Multiply the value by 100 and append a percent sign (%); follow the settings specified in Regional Settings in Windows Control Panel for negative amounts, decimal symbols, and decimal places.
Scientific | Use standard scientific notation.

Custom Formats

Custom number formats can have one to four sections with semicolons (;) as the list separator. Each section contains the format specification for a different type of number.

Section | Description
First | The format for positive numbers.
Second | The format for negative numbers.
Third | The format for zero values.
Fourth | The format for Null values.

For example, you could use the following custom Currency format:

$#,##0.00[Green];($#,##0.00)[Red];"Zero";"Null"

This number format contains four sections separated by semicolons and uses a different format for each section.

If you use multiple sections but don't specify a format for each section, entries for which there is no format either will display nothing or will default to the formatting of the first section.

You can create custom number formats by using the following symbols.

Symbol | Description
. (period) | Decimal separator. Separators are set by double-clicking Regional Settings in Windows Control Panel.
, (comma) | Thousand separator.
0 | Digit placeholder. Display a digit or 0.
# | Digit placeholder. Display a digit or nothing.
$ | Display the literal character "$".
% | Percentage. The value is multiplied by 100 and a percent sign is appended.
E– or e– | Scientific notation with a minus sign (–) next to negative exponents and nothing next to positive exponents. This symbol must be used with other symbols, as in 0.00E–00 or 0.00E00.
E+ or e+ | Scientific notation with a minus sign next to negative exponents and a plus sign (+) next to positive exponents. This symbol must be used with other symbols, as in 0.00E+00.

Remarks

You can use the DecimalPlaces property to override the default number of decimal places for the predefined format specified for the Format property.

The predefined currency and euro formats follow the settings in Regional Settings in Windows Control Panel. You can override these by entering your own currency format.


Format Property - Number and Currency Data Types Example

Format Property — Number and Currency Data Types Example

The following are examples of the predefined number formats.

Setting | Data | Display
General Number | 3456.789 –3456.789 $213.21 | 3456.789 –3456.789 $213.21
Currency | 3456.789 –3456.789 | $3,456.79 ($3,456.79)
Fixed | 3456.789 –3456.789 3.56645 | 3456.79 –3456.79 3.57
Standard | 3456.789 | 3,456.79
Percent | 3 0.45 | 300% 45%
Scientific | 3456.789 –3456.789 | 3.46E+03 –3.46E+03

The following are examples of custom number formats.

Setting | Description
0;(0);;"Null" | Display positive values normally; display negative values in parentheses; display the word "Null" if the value is Null.
+0.0;–0.0;0.0 | Display a plus (+) or minus (–) sign with positive or negative numbers; display 0.0 if the value is zero.


 Format Property - Text and Memo Data Types

Format Property — Text and Memo Data Types

You can use special symbols in the setting for the Format property to create custom formats for Text and Memo fields.

Setting

You can create custom text and memo formats by using the following symbols.

Symbol | Description
@ | Text character (either a character or a space) is required.
& | Text character is not required.
< | Force all characters to lowercase.
> | Force all characters to uppercase.

Custom formats for Text and Memo fields can have up to two sections. Each section contains the format specification for different data in a field.

Section | Description
First | Format for fields with text.
Second | Format for fields with zero-length strings and Null values.

For example, if you have a text box control in which you want the word "None" to appear when there is no string in the field, you could type the custom format @;"None" as the control's Format property setting. The @ symbol causes the text from the field to be displayed; the second section causes the word "None" to appear when there is a zero-length string or Null value in the field.

Note You can use the Format function to return one value for a zero-length string and another for a Null value, and you can similarly use the Format property to automatically format fields in table Datasheet view or controls on a form or report.


Format Property - Text and Memo Data Types Example

Format Property — Text and Memo Data Types Example

The following are examples of text and memo custom formats.

Setting | Data | Display
@@@-@@-@@@@ | 465043799 | 465-04-3799
@@@@@@@@@ | 465-04-3799 465043799 | 465-04-3799 465043799
> | davolio DAVOLIO Davolio | DAVOLIO DAVOLIO DAVOLIO
< | davolio DAVOLIO Davolio | davolio davolio davolio
@;"Unknown" | Null value | Unknown
 | Zero-length string | Unknown
 | Any text | Same text as entered is displayed


Format Property Example

The following three examples set the Format property by using a predefined format:

Me!Date.Format = "Medium Date"
Me!Time.Format = "Long Time"
Me!Registered.Format = "Yes/No"

The next example sets the Format property by using a custom format. This format displays a date as: Jan 1995.

Forms!Employees!HireDate.Format = "mmm yyyy"

The following example demonstrates a Visual Basic function that formats numeric data by using the Currency format and formats text data entirely in capital letters. The function is called from the OnLostFocus event of an unbound control named TaxRefund.

Function FormatValue() As Integer
    Dim varEnteredValue As Variant

    varEnteredValue = Forms!Survey!TaxRefund.Value
    If IsNumeric(varEnteredValue) = True Then
        Forms!Survey!TaxRefund.Format = "Currency"
    Else
        Forms!Survey!TaxRefund.Format = ">"
    End If
End Function


 Format Property - Yes/No Data Type

Format Property — Yes/No Data Type

You can set the Format property to the Yes/No, True/False, or On/Off predefined formats or to a custom format for the Yes/No data type.

Setting

Microsoft Access uses a check box control as the default control for the Yes/No data type. Predefined and custom formats are ignored when a check box control is used. Therefore, these formats apply only to data that is displayed in a text box control.

Predefined Formats

The Format property provides the Yes/No, True/False, and On/Off predefined formats. Yes, True, and On are equivalent, as are No, False, and Off. If you specify one predefined format and then enter an equivalent value, the predefined format of equivalent value will be displayed. For example, if you enter True or On in a text box control with its Format property set to Yes/No, the value is automatically converted to Yes.

Custom Formats

The Yes/No data type can use custom formats containing up to three sections.

Section | Description
First | This section has no effect on the Yes/No data type. However, a semicolon (;) is required as a placeholder.
Second | The text to display in place of Yes, True, or On values.
Third | The text to display in place of No, False, or Off values.


Format Property - Yes/No Data Type Example

Format Property — Yes/No Data Type Example

The following example shows a custom yes/no format for a text box control. The control displays the word "Always" in blue text for Yes, True, or On, and the word "Never" in red text for No, False, or Off.

;"Always"[Blue];"Never"[Red]


Form, Report Properties Example

The following example uses the Form and Report properties to refer to a control on a subform and a subreport.

Dim curTotalAmount As Currency
Dim curTotalSales As Currency
curTotalAmount = Forms!Orders!OrderDetails.Form!TotalAmount
curTotalSales = Reports!Sales!Employees.Report!TotalSales


FrozenColumns Property Example

The following example uses the FrozenColumns property to determine how many columns are frozen in a table in Datasheet view. If more than three columns are frozen, the table size is maximized so you can see as many unfrozen columns as possible.

Sub CheckFrozen(strTableName As String)
    Dim dbs As Object
    Dim tdf As Object
    Dim prp As Variant
    Const DB_Integer As Integer = 3
    Const conPropertyNotFound = 3270  ' Property not found error.
    Set dbs = CurrentDb      ' Get current database.
    Set tdf = dbs.TableDefs(strTableName)      ' Get object for table.
    DoCmd.OpenTable strTableName, acNormal  ' Open table.
    tdf.Properties.Refresh
    On Error GoTo Frozen_Err
    If tdf.Properties("FrozenColumns") > 3 Then   ' Check property.
        DoCmd.Maximize
    End If
Frozen_Bye:
    Exit Sub
Frozen_Err:
    If Err = conPropertyNotFound Then      ' Property not in collection.
        Set prp = tdf.CreateProperty("FrozenColumns", DB_Integer, 1)
        tdf.Properties.Append prp
        Resume Frozen_Bye
    End If
End Sub


FullName Property Example

The following example interates through the AllDataAccessPages collection and returns the name of the link and the path of each data access page in the current project.

Sub PrintDAPLocationInfo()
    Dim dapObject As AccessObject
    For Each dapObject In CurrentProject.AllDataAccessPages
        Debug.Print "The '" & dapObject.Name & _
        "' is located at: "; dapObject.FullName
    Next dapObject
End Sub


FullPath, GUID, IsBroken, Major, Minor Properties Example

The following example prints the value of the FullPath, GUID, IsBroken, Major, and Minor properties for each Reference object in the References collection:

Sub ReferenceProperties()
    Dim ref As Reference

    ' Enumerate through References collection.
    For Each ref In References
        ' Check IsBroken property.
        If ref.IsBroken = False Then
            Debug.Print "Name: ", ref.Name
            Debug.Print "FullPath: ", ref.FullPath
            Debug.Print "Version: ", ref.Major & "." & ref.Minor
        Else
            Debug.Print "GUIDs of broken references:"
            Debug.Print ref.GUID
        EndIf
    Next ref
End Sub


Grouping Properties 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 = 2
End Sub


Height, Width Properties - Applies To

Height, Width Properties — Applies To

Height Property

Width Property


Height, Width Properties 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

HelpContextID, HelpFile Properties — Applies To

HelpContextID Property

HelpFile Property


 HelpContextId Property (Command Bars)

HelpContextId Property (Command Bars)

In Microsoft Access 2000, you can use the Toolbar Control Properties dialog box for command bar controls to set the HelpContextId property for a control on a command bar. Display the Customize dialog box by pointing to Toolbars on the View menu and clicking Customize. For menu bar and toolbar controls, display the menu bar or toolbar, and then right-click the control whose HelpContextId property you want to set. For shortcut menu controls, select the Shortcut Menus check box on the Toolbars tab of the Customize dialog box, then find the shortcut menu control you want on the menu bar that's displayed and right-click the control. Click the Properties command. Enter the context ID number of the Help topic you want in the Help ContextID box.


 HelpContext, HelpFile Properties

HelpContext, HelpFile Properties

The HelpContext and HelpFile properties apply to the Error object. You can access them only by using Visual Basic.

Note Don't confuse these properties with the Microsoft Access HelpContextID and HelpFile properties. These properties are similar, but they apply only to forms, reports, and controls. You can set them by using Visual Basic, a macro, or the property sheet within form Design view or report Design view.


 HelpFile Property

HelpFile Property

In Microsoft Access 2000, you can use the Toolbar Control Properties dialog box for command bar controls to set the HelpFile property for a control on a command bar. Display the Customize dialog box by pointing to Toolbars on the View menu and clicking Customize. For menu bar and toolbar controls, display the menu bar or toolbar, and then right-click the control whose HelpFile property you want to set. For shortcut menu controls, select the Shortcut Menus check box on the Toolbars tab of the Customize dialog box, then find the shortcut menu control you want on the menu bar that's displayed and right-click the control. Click the Properties command. Enter the name of the Help file you want in the Help File box.


HideDuplicates Property Example

The following example returns the HideDuplicates property setting for the CategoryName text box and assigns the value to the intCurVal variable.

Dim intCurVal As Integer
intCurVal = Me!CategoryName.HideDuplicates


HighPriorityTips Property

This property isn't available in Microsoft Access.


hWnd 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()
    Dim intWindowHandle As Long
    intWindowHandle = Screen.ActiveForm.hWnd
    If Not IsZoomed(intWindowHandle) Then
        DoCmd.Maximize
    End If
End Sub


Hyperlink 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!txtAddress
End 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 Select
End Sub


 Id Property

Id Property

The Id property can only be set when you create a new control. Set the Id argument of the Add method of the CommandBarControls collection to an Integer value that corresponds to a built-in command button or menu item, or to one of the equivalent intrinsic constants used with the RunCommand method in Microsoft Access. For a custom control, set the Id argument to 1 or leave it blank.

You can use the Id property to determine the Integer value corresponding to a built-in control. For example, to determine the Integer value corresponding to the Paste command on the Edit menu of the main menu bar, use the following reference:

CommandBars("Menu Bar").Controls("Edit").Controls("Paste").Id


ImageHeight, ImageWidth Properties Example

The following example prompts the user to enter the name of a bitmap and then assigns that bitmap to the Picture property of the Image1 image control. The ImageHeight and ImageWidth properties are used to resize the image control to fit the size of the bitmap.

Sub GetNewPicture(frm As Form)
    Dim ctlImage As Control
    Set ctlImage = frm!Image1
    ctlImage.Picture = InputBox("Enter path and " _
        & "file name for new bitmap")
    ctlImage.Height = ctlImage.ImageHeight
    ctlImage.Width = ctlImage.ImageWidth
End Sub


IMESentenceMode

IMESentenceMode Property

Language-specific information

You can use the IMESentenceMode property specify or determine the IME Sentence Mode of fields of a table or controls of a form that switch when the focus moves.

Setting

The IMESentenceMode property uses the following settings.

Setting | Description | Visual Basic
Normal | (Default) Set IME Sentence Mode to “Normal” mode. | 0
Plural | Set IME Sentence Mode to “Plural” mode. | 1
Speaking | Set IME Sentence Mode to “Speaking” mode. | 2
No Conversion | Doesn’t set IME Sentence Mode. | 3

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

Remarks

Normal mode

Use this mode when creating a literary Japanese document.

Plural mode

Use this mode when entering name or address data. In this mode, two additional dictionaries are available. The “Biographical/Geographical Dictionary” contains names not covered in the normal dictionary and the “Postal Code Dictionary”, useful in creating addresses. (Factory setting.)

Speaking mode

Use this mode when entering data that contains conversational language.

No Conversion

In this mode, inputted characters are settled without conversion.


Index Property Example

Index Property Example (MDB)

The following example sets the index for a table-type Recordset object to the primary key. "PrimaryKey" is the default name of an Index object if the index corresponds to the primary key set in table Design view. Next, the procedure asks the user for a value to search on and locates the record with a matching key field value. Note that the current index must be set before certain operations, such as the Seek method, can be performed on a table-type Recordset object.

Sub UsePrimaryKey()
    Dim dbs As Database, rst As Recordset
    Dim fld As Field, strInput As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create table-type Recordset object.
    Set rst = dbs.OpenRecordset("Orders", dbOpenTable)
    ' Set current index.
    rst.Index = "PrimaryKey"
    strInput = InputBox("Enter the OrderID on which to search.")
    ' Locate record.
    rst.Seek "=", strInput
    If Not rst.NoMatch Then
        For Each fld in rst.Fields
            Debug.Print fld.Name; "   "; fld.Value
        Next fld
    End If
    rst.Close
    Set dbs = Nothing
End Sub


 Inherited Property (MDB)

Inherited Property (MDB)

Microsoft Access defines a number of properties that apply to Data Access Objects. Because these properties are defined by Microsoft Access, the Microsoft Jet database engine doesn't recognize them automatically. To set one of these properties by using Visual Basic, you must first create the property by using the CreateProperty method and then append it to the Properties collection of the object. For more information, search the Help index for the Property object topic.

When you create an object based on another object, the derived object inherits the properties of the original object. You can use the Inherited property to determine whether one of these properties was created for the object it is applied to, or if the property was inherited from another object.

For example, suppose you want to set the Microsoft Access DatasheetFontName property for a TableDef object. If you are setting this property for the first time, you will need to create a corresponding Property object and append it to the Properties collection of the TableDef object. The Inherited property of the new Property object returns False (0).

If you then create a new QueryDef object based on the table corresponding to the TableDef object, the DatasheetFontName property will be included in the Properties collection of the QueryDef object. The Inherited property of a Property object corresponding to this property returns True (–1).


Inherited Property Example

Inherited Property Example (MDB)

The following example creates a Property object in the Properties collection of a TableDef object, and then creates a new QueryDef object based on the same table. The Property object automatically exists in the Properties collection of the new QueryDef object. Next, the procedure checks the Inherited property for the Property objects in the Properties collections of both the TableDef and the QueryDef objects.

In this example, the Microsoft Access DatasheetFontItalic property is created and appended to the Properties collection of the TableDef object. The DatasheetFontItalic property is defined by Microsoft Access rather than by the Microsoft Jet database engine. However, the property applies to DAO objects. Therefore, in order to set it from Visual Basic code, you must first create a Property object corresponding to that property and append it to the Properties collection of the DAO object. It's necessary to create the property only the first time you set it.

Sub CheckInherited()
    Dim dbs As Database, tdf As TableDef, qdf As QueryDef
    Dim strSQL As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Orders table.
    Set tdf = dbs.TableDefs!Orders
    ' Call SetAccessProperty function.
    If SetAccessProperty(tdf, "DatasheetFontItalic", _
            dbBoolean, True) = True Then
        ' Create QueryDef object based on Orders table.
        strSQL = "SELECT * FROM Orders WHERE ShipCountry = 'USA';"
        Set qdf = dbs.CreateQueryDef("USAOrders", strSQL)
        ' Return Property object pointing to property.
        Debug.Print "Value of Inherited, TableDef object:", _
            tdf.Properties!DatasheetFontItalic.Inherited
        Debug.Print "Value of inherited, QueryDef object:", _
            qdf.Properties!DatasheetFontItalic.Inherited
            ExitCheckInherited
    Else
        MsgBox "Property not set successfully."
        ExitCheckInherited
    End If

ExitCheckInherited:
    Set dbs = Nothing
    Exit Sub
End Sub

This procedure calls the following function, which sets the property, creating it in the Properties collection if necessary:

Function SetAccessProperty(obj As Object, strName As String, _
        intType As Integer, varSetting As Variant) As Boolean
    Dim prp As Property
    Const conPropNotFound As Integer = 3270

    On Error GoTo ErrorSetAccessProperty
    ' Explicitly refer to Properties collection.
    obj.Properties(strName) = varSetting
    obj.Properties.Refresh
    SetAccessProperty = True

ExitSetAccessProperty:
    Exit Function

ErrorSetAccessProperty:
    If Err = conPropNotFound Then
        ' Create property, denote type, and set initial value.
        Set prp = obj.CreateProperty(strName, intType, varSetting)
        ' Append Property object to Properties collection.
        obj.Properties.Append prp
        obj.Properties.Refresh
        SetAccessProperty = True
        Resume ExitSetAccessProperty
    Else
        MsgBox Err & ": " & vbCrLf & Err.Description
        SetAccessProperty = False
        Resume ExitSetAccessProperty
    End If
End Function


Inherit Property Example

Inherit Property Example (MDB)

The following example sets the Inherit property of the Forms Container object to True (–1), and then sets the Permissions property to give users full security access to all forms. All new Document objects of the Form type will inherit these permissions. The procedure then creates a new Form object and displays the permissions for that object.

Note that the Forms Container object is different from the Forms collection. The Forms Container object includes all Form Document objects in the database; the Forms collection contains only currently open forms.

Also note that the Or operator performs a bitwise comparison to determine what permissions are currently set.

Sub FormPermissions()
    Dim dbs As Database, ctrForms As Container
    Dim docForm As Document, frmNew As Form

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Forms container.
    Set ctrForms = dbs.Containers!Forms
    ' Set Inherit property.
    ctrForms.Inherit = True
    ' Set permissions to be inherited.
    ctrForms.Permissions = ctrForms.Permissions Or _
        acSecFrmRptWriteDef
    ' Create new form.
    Set frmNew = CreateForm()
    ' Save form.
    DoCmd.Save , "OrderForm"
    ' Return Document object associated with new form.
    Set docForm = ctrForms.Documents!OrderForm
    ' Compare permissions for Container and Document objects.
    If docForm.Permissions <> ctrForms.Permissions Then
        MsgBox "Error!"
    Else
        MsgBox "Permissions successfully inherited."
    End If
    Set dbs = Nothing
End Sub


InputMask Property Example - Useful Input Masks

InputMask Property Example — Useful Input Masks

The following table shows some useful input masks and the type of values you can enter 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
#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


InSelection Property 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 If
End Function


InsideHeight, InsideWidth Properties Example

The following example shows how to use the InsideHeight and InsideWidth properties to compare the inside height and width of a form with the height and width of the form's window. If the window's dimensions 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 If
End Sub


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

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

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 If
End Sub


ItemData 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

    ' 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 varItem
End Sub


ItemsSelected 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
    For Each varItm In ctl.ItemsSelected
        Debug.Print ctl.ItemData(varItm)
    Next varItm
End Sub

The next example uses the same list box control, but prints the values of each column for each selected row in the list box, instead of only the values in the bound column.

Sub AllSelectedData()
    Dim frm As Form, ctl As Control
    Dim varItm As Variant, intI As Integer

    Set frm = Forms!Contacts
    Set ctl = frm!Names
    For Each varItm In ctl.ItemsSelected
        For intI = 0 To ctl.ColumnCount - 1
            Debug.Print ctl.Column(intI, varItm)
        Next intI
        Debug.Print
    Next varItm
End Sub


KeepTogether Property - Sections Example

KeepTogether Property — Sections 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 Integer
intGetVal = Me.Section(acDetail).KeepTogether


KeyboardShortcutTips Property

This property isn't available in Microsoft Access.


KeyPreview Property 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 = True
End 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 Select
End Sub


LabelAlign, TextAlign Properties - Applies To

LabelAlign, TextAlign Properties — Applies To

LabelAlign Property

TextAlign Property


LabelAlign, TextAlign Properties

Language-specific information

Microsoft Access 2000 has modified the LabelAlign and TextAlign properties by adding context sensitive behavior to the General alignment choice.

Remarks

For general alignment, text in the control will be right aligned if the first character is a right-to-left language character, and left aligned if the first character is a left-to-right language character. In a combo box or list box, TextAlign determines alignment behavior for both the text box and list box components of the control.

For more information about right-to-left properties, see Learn more about right-to-left properties in Microsoft Access 2000.


LabelX, LabelY Properties

Language-specific information

Microsoft Access 2000 has modified the LabelX and LabelY property behavior for right-to-left controls.

Remarks

The LabelX and LabelY properties specify the placement of the label for a new control. If the orientation is left to right for a form or report, LabelX and LabelY behavior matches standard Microsoft Access left-to-right orientation. For more information about orientation, see the Orientation property.

If orientation is right to left, the origin of the coordinate system for LabelX and LabelY is the upper right corner of the attached control. A negative number for LabelX places the label to the right of the control. A negative number for LabelY places the label above the control.

For General and Right alignment when orientation is RTL, LabelX and LabelY specify the location of the upper-right corner of the label relative to the upper-right corner of the label’s attached control. For Left and Center alignment, LabelX and LabelY specify the location of the upper-left corner and top center, respectively, of the label relative to the upper-right corner of the label’s attached control.


LastModified Property Example

LastModified Property Example (MDB)

The following example determines the most recently modified record in a recordset and sets a bookmark for that record:

Sub LastChangedRecord()
    Dim dbs As Database, rst As Recordset, varBook As Variant

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create dynaset-type Recordset object.
    Set rst = dbs.OpenRecordset("SELECT * " _
        & "FROM Orders ORDER BY ShipCountry;")
    With rst
        .FindFirst "ShipCountry = 'UK'"
        ' Alter record and save changes.
        .Edit
        !ShipCountry = "USA"
        .Update
    End With
    ' Check to see if recordset supports bookmarks.
    If rst.Bookmarkable Then
        ' Set bookmark to most recently modified record.
        varBook = rst.LastModified
        ' Set currency to last modified record.
        rst.Bookmark = varBook
    End If
    rst.Close
    Set dbs = Nothing
End Sub


Left, Top Properties Example

The following example checks the Left property setting for the current report. If the value is less than the minimum margin setting, the 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.

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 If
End Sub


ListCount, ListRows Properties 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

    Set ListControl = Forms!Customers!CustomerList
    With ListControl
        If .ListCount < 8 Then
            .ListRows = .ListCount
        Else
            .ListRows = 8
        End If
    End With
End Sub


LocationOfComponents Property Example

This example sets the path where Office components are downloaded.

Application.DefaultWebOptions.LocationOfComponents = _
    Application.Path & Application.PathSeparator & "foo"


LockEdits Property Example

LockEdits Property Example (MDB)

The following example opens a dynaset-type Recordset object and sets its LockEdits property to False (0). This enables optimistic locking so other users can change the database records at any time. Microsoft Access triggers a trappable error if the data changes before you use the Update method.

Sub ShowLockStatus()
    Dim dbs As Database, rst As Recordset

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Open dynaset-type Recordset object.
    Set rst = dbs.OpenRecordset("Customers", dbOpenDynaset)
    rst.LockEdits = False
    On Error Goto ErrorLockEdits
    ' Enable editing.
    rst.Edit
    .                        ' Change records.
    .
    .
    rst.Update            ' Try to post changes.

ExitLockEdits:
    rst.Close
    Set dbs = Nothing
    Exit Sub

ErrorLockEdits:
        If Err.Number = 3197 Then
            MsgBox "Data changed by another user."
            Resume Next
        Else
            MsgBox "Some other error."
            Resume ExitLockEdits
        End If
End Sub


LoginTimeout Property Example

LoginTimeout Property Example (MDB)

The following example sets the LoginTimeout property to 120 seconds, then creates a query, and runs it on a database on an ODBC server:

Sub Login()
    Dim dbs As Database
    Dim qdf As QueryDef, rst As Recordset

    ' Set timeout to 120 seconds.
    DBEngine.LoginTimeout = 120
    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create new QueryDef object.
    Set qdf = dbs.CreateQueryDef("All Employees", _
        "SELECT * FROM Employees;")
    qdf.Connect = "ODBC;DSN=Human Resources; " _
        & "Database=HRSRVR; UID=Smith; PWD=Sesame"
    ' Log on to server and run query.
    Set rst = qdf.OpenRecordset()
    ' Perform operations with recordset.
    .
    .
    .
    rst.Close
    Set dbs = Nothing
End Sub


MDE Property Example

The following example uses the IsItMDE function to check the MDE property for the current database:

Dim dbs As Object
Set dbs = CurrentDb
If IsItMDE(dbs) <> True Then
    ' Process custom database code.
End If

Function IsItMDE(dbs as Object) 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 if
End Function


MenuBar 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 = ""


Me Property 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
    End If
End Sub


Module Property Example

The following example uses the Module property to insert the Beep method in a form's Open event.

Dim strFormOpenCode As String
Dim mdl As Module

Set mdl = Forms!MyForm.Module
strFormOpenCode = "Sub Form_Open(Cancel As Integer)" _
    & vbCrLf & "Beep" & vbCrLf & "End Sub"
    With mdl
        .InsertText strFormOpenCode
    End With


MouseTips Property

This property isn't available in Microsoft Access.


 Name Property (Command Bars)

Name Property (Command Bars)

In Microsoft Access 2000, you can use the Toolbar Properties dialog box to change the name of a custom menu bar, toolbar, or shortcut menu. Point to Toolbars on the View menu and click Customize, then click the Properties button in the Customize dialog box. Select the custom menu bar, toolbar, or shortcut menu you want in the Selected Toolbar box, and then enter the new name in the Toolbar Name box. You can't change the name of a built-in menu bar, toolbar, or shortcut menu.


NewRecord Property Example

The following example shows how to use the NewRecord property to determine if the current record is a new record. The NewRecordMark procedure sets the current record to the variable 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 If
End Sub


NewRowOrCol Property Example

The following example returns the NewRowOrCol property setting and assigns it to the intGetVal variable.

Dim intGetVal As Integer
intGetVal = 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.

  • Column Layout — Across, Then Down

    Head1

    1a 1b2a 2b3a 3b4a 4b

    5a 5b

    Head2

    1a 1b2a 2b3a 3b4a 4b

    Head3

    1a 1b2a 2b3a 3b

    Head4

    1a 1b2a 2b3a 3b4a 4b

    5a 5b6a 6b

  • Grid Settings — Number of Columns set to 4

  • NewRowOrCol property setting for group header section — Before & After
  • Column Layout — Down, Then Across

    Head1Head2Head3Head4

    1a 1b1a 1b1a 1b1a 1b

    2a 2b2a 2b2a 2b2a 2b

    3a 3b3a 3b3a 3b3a 3b

    4a 4b4a 4b4a 4b

    5a 5b5a 5b

    6a 6b

  • Grid Settings — Number of Columns set to 4

  • NewRowOrCol property setting for group header section — Before Section


NoMatch Property Example

NoMatch Property Example (MDB)

The following example uses the NoMatch property to determine whether a FindFirst method process has been successful:

Function FindCountry() As Integer
    Dim dbs As Database, rst As Recordset
    Dim strCountry As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create dynaset-type Recordset object.
    Set rst = dbs.OpenRecordset("Orders", dbOpenDynaset)
    strCountry = InputBox("Please enter country name.")
    rst.FindFirst "ShipCountry = '" & strCountry & "'"
    If rst.NoMatch Then
        FindCountry = False
    Else
        FindCountry = True
        Debug.Print rst!OrderID
    End If
    rst.Close
    Set dbs = Nothing
End Function


ObjectPalette, PaintPalette Properties Example

The following example sets the PaintPalette property of the Seascape form to the ObjectPalette property of the Ocean control on the DisplayPictures form. (Ocean can be a bound object frame, command button, chart, toggle button, or unbound object frame.)

Forms!Seascape.PaintPalette = _
     Forms!DisplayPictures!Ocean.ObjectPalette

The ObjectPalette and PaintPalette properties are useful for programmatically altering the color palette in use by an open form at run time. A common use of these properties is to set the current form'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.ObjectPalette
End Sub

Sub SunsetPicture_Enter()
    Me.PaintPalette = Me!SunsetPicture.ObjectPalette
End Sub


Object Properties Example

The following example uses the PrintObjectProperties subroutine to print the values of an object's Object properties to the Debug window. The subroutine requires the object type and object name as arguments.

Dim strObjectType As String
Dim strObjectName As String
Dim strMsg As String

strMsg = "Enter object type (e.g., Forms, 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
' 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
Next
End Sub


ObjectVerbs, ObjectVerbsCount Properties Example

The following example returns the verbs supported by the OLE object in the OLE1 control and displays each verb in a message box.

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


Object Property 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 = Nothing
End Sub


OldValue Property Example

The following example checks to determine if new data entered in a field is within 10 percent of the value of the original data. If the change is greater than 10 percent, the OldValue property is used to restore the original value. 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 If
End Sub


OLEType Property Example

The following example illustrates how to display the Insert Object dialog box and how to display an error message if the Cancel button in the Insert Object dialog box is clicked.

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 Next
End Sub


 OnAction Property

OnAction Property

In Microsoft Access 2000, you can use the Toolbar Control Properties dialog box for command bar controls to set the OnAction property for a control on a command bar. Display the Customize dialog box by pointing to Toolbars on the View menu and clicking Customize. For menu bar and toolbar controls, display the menu bar or toolbar, and then right-click the control whose OnAction property you want to set. For shortcut menu controls, select the Shortcut Menus check box on the Toolbars tab of the Customize dialog box, then find the shortcut menu control you want on the menu bar that's displayed and right-click the control. Click the Properties command. Enter the macro or Sub procedure you want to run in the On Action box.

You can use the OnAction property only to run a macro or a Sub procedure. To run a macro, select it from the drop-down list in the On Action box, or enter its name in the box. To run a Sub procedure, enter its name in the form =subname( ) in the box.

You can also set the OnAction property to an expression. The expression can contain a built-in or user-defined Sub procedure or combination of Sub procedures. When Microsoft Access evaluates an expression, it performs all of the operations in the expression. For example, the following is an expression that runs the user-defined Sub procedure "CustomControlProc":

=CustomControlProc()

In Visual Basic, the OnAction property takes a string, so to set it to an expression, you must pass it a string that contains the expression. In passing the string, be careful to enclose strings within the string in quotation marks ("). (Note that in the On Action box in the Toolbar Control Properties dialog box, an enclosed string in the expression should only have one set of quotation marks around it.) Also, make sure you include the equal sign (=) to specify that the string contains an expression. Your Sub procedure must contain no arguments, remember to include parentheses [( )] within the string. You can set the OnAction property to the previous expression with the following string:

"=CustomControlProc()"

Note that you must set the OnAction property to the name of a macro or Sub procedure; you can't set it to the name of a Function procedure.

For custom command bar controls, you must set this property in order for the control to perform any action. If you set this property for a built-in control, the OnAction property setting overrides the normal actions that the control performs; that is, you can force a built-in control to perform different actions from its default actions. The control becomes in effect a custom control.


OpenArgs Property 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 If
End Sub

The next example uses the FindFirst method to locate the employee named in the OpenArgs property.

Private Sub Form_Open(Cancel As Integer)
    If Not IsNull(Me.OpenArgs) Then
        Dim strEmployeeName As String
        strEmployeeName = Me.OpenArgs
        Dim RS As Recordset
        Set RS = Me.RecordsetClone
        RS.FindFirst "LastName = '" & strEmployeeName & "'"
        If Not RS.NoMatch Then
            Me.Bookmark = RS.Bookmark
        End If
    End If
End Sub


OrdinalPosition Property Example

OrdinalPosition Property Example (MDB)

The following example changes the setting of the OrdinalPosition property for the first field in a Products table. If you examine the table in Datasheet view before and after running this example, you'll see that it moves the ProductID field from the first column to the last column.

Sub SetPosition()
    Dim dbs As Database, tdf As TableDef
    Dim fldFirst As Field, fld As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Products table.
    Set tdf = dbs.TableDefs!Products
    ' Return reference to first field in table.
    Set fldFirst = tdf.Fields(0)
    ' Set OrdinalPosition property to last position in collection.
    fldFirst.OrdinalPosition = tdf.Fields.Count
    ' Refresh Fields collection.
    tdf.Fields.Refresh
    ' Enumerate all fields and print ordinal position.
    For Each fld In tdf.Fields
        Debug.Print fld.Name, fld.OrdinalPosition
    Next fld
    Set dbs = Nothing
End Sub


OrganizeInFolder Property Example

This example specifies that all image files are saved in the same folder when the document is saved as a Web page.

Application.DefaultWebOptions.OrganizeInFolder = False


OutputAllFields Property Example

The following example uses an asterisk in an SQL statement to select all the fields in the Shippers table. It then displays the fields in text boxes on a form by setting the ControlSource property for the text boxes to the names of the individual fields in the query.

Dim strGetSQL AS String
strGetSQL = "SELECT * FROM Shippers"
Forms!Form1.RecordSource = strGetSQL
Text1.ControlSource = "ShipperID"
Text2.ControlSource = "CompanyName"

In the output for the next SQL statement, the values in the CompanyName and ProductName fields are sorted in ascending order, and all the fields in the Suppliers and Products tables are displayed in the field lists and in Datasheet view. You enter this SQL statement in SQL view of the Query window.

SELECT * FROM Suppliers INNER JOIN Products
ON Suppliers.[SupplierID] = Products.[SupplierID]
ORDER BY Suppliers.[CompanyName], Products.[ProductName];


PageHeader, PageFooter Properties Example

The following example sets the PageHeader property for a report to Not With Rpt Hdr. To run this example, type the following line in the Debug window for a report named Report1.

Reports!Report1.PageHeader = 1


Page, Pages Properties Example

The following example displays a message that tells how many pages the report contains. For this example to work, the report must include a text box for which the ControlSource property is set to the expression =Pages. 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 String
intTotalPages = Me.Pages
strMsg = "This report contains " & intTotalPages & " pages."
MsgBox strMsg


Painting Property Example

The following example uses the Painting property to enable or disable form painting depending on whether the SetPainting variable is set to True (–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 If
End Function


 Parameter Property

Parameter Property

In Microsoft Access 2000, you can use the Toolbar Control Properties sheet for command bar controls to set the Parameter property for a control on a command bar. Display the Customize dialog box by pointing to Toolbars on the View menu and clicking Customize. For menu bar and toolbar controls, display the menu bar or toolbar, and then right-click the control whose Parameter property you want to set. For shortcut menu controls, select the Shortcut Menus check box on the Toolbars tab of the Customize dialog box, then find the shortcut menu control you want on the menu bar that's displayed and right-click the control. Click the Properties command. Enter the parameter information you want in the Parameter box.


Parent Property Example

The following example uses the Parent property to examine the parent of the Speedy Label label control, the Speedy check box control, and the ShipVia option group.

Dim frm As Form
Dim ctl As Control
Set frm = Forms!Orders
Set ctl = frm.[Speedy Label]
' Returns name of control attached to label.
MsgBox "The parent control is " & ctl.Parent.Name
Set ctl = frm.Speedy
' Returns name of control containing control.
MsgBox "The parent control is " & ctl.Parent.Name
Set ctl = frm.ShipVia
' Returns name of form containing option group control.
MsgBox "The parent control is " & ctl.Parent.Name

The next example also returns the name of the form containing the option group control.

MsgBox Forms!Orders! _
    [Speedy Label].Parent.Parent.Parent.Name


PercentPosition Property Example

PercentPosition Property Example (MDB)

The following example expresses the current position of a record in a recordset as a percent, then displays it in a message box:

Sub PercentOfRecords()
    Dim dbs As Database, rst As Recordset
    Dim strInput As String, strSQL As String

    strSQL = "SELECT * FROM Products ORDER BY ProductName;"
    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Open dynaset-type Recordset object.
    Set rst = dbs.OpenRecordset(strSQL, dbOpenDynaset)
    ' Move to end of recordset.
    rst.MoveLast
    ' Return to start of recordset.
    rst.MoveFirst
    ' Prompt user to input name of product.
    strInput = InputBox("Please enter the full product name.")
    ' Find first occurrence.
    rst.FindFirst "ProductName = '" & strInput & "'"
    ' Display current position as a percent.
    MsgBox("The current position in the Recordset is " _
        & rst.PercentPosition & "%.")
    rst.Close
    Set dbs = Nothing
End Sub


 Permissions Property (MDB)

Permissions Property (MDB)

Microsoft Access defines four types of Container objects in addition to those defined by the Microsoft Jet database engine. These include the Forms, Reports, Scripts, or Modules Container objects. Individual Form, Report, Script and Module Document objects belong to the Documents collections of these Container objects. For these Container and Document objects, you can also set the Permissions property to the following constants.

Constant | User or group can
acSecFrmRptReadDef | Open the form or report in Design view but not make any changes.
acSecFrmRptWriteDef | Modify or delete the form or report in Design view.
acSecFrmRptExecute | Open the form in Form view or Datasheet view; print or open the report in Sample Preview or Print Preview.
acSecMacReadDef | Open the Macro window and view a macro without making changes.
acSecMacWriteDef | Modify or delete the macro in the Macro window.
acSecModReadDef | Open the module but not make any changes.
acSecModWriteDef | Modify or delete the contents of a module.
acSecMacExecute | Run the macro.

Note acSecModReadDef and acSecModWriteDef are included for backward compatibility only. Since Module access is now controlled by the Protection property in the Visual Basic envronment, these constants are no longer valid parameters in Microsoft Access2000.


Permissions, UserName Properties Example

Permissions, UserName Properties Example (MDB)

The following example adds a new user account by creating a User object and appending it to the Users collection of the default workspace. It then sets permissions for the new user for all tables in the database. The procedure first sets the UserName property of a Tables Container object to the name of the new user, then sets the Permissions property to the appropriate permissions.

Note that the And operator performs a bitwise comparison to determine whether an attribute is currently set.

Note When programming security, you should avoid including actual password and PID information in your code. The following example is intended for demonstration purposes only.

Function SetPermissions(strName As String, strPID As String, _
        strPassword As String) As Boolean
    Dim dbs As Database, ctrTables As Container
    Dim wspDefault As Workspace, usrNew As User

    On Error GoTo ErrorSetPermissions
    ' Return reference to default workspace.
    Set wspDefault = DBEngine.Workspaces(0)
    ' Create User object, specifying name, PID, and password.
    Set usrNew = wspDefault.CreateUser(strName, _
            strPID, strPassword)
    ' Append to Users collection of default workspace.
    wspDefault.Users.Append usrNew
    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Tables container.
    Set ctrTables = dbs.Containers!Tables
    ctrTables.UserName = usrNew.Name
    ' Set new user's permissions for tables.
    ctrTables.Permissions = dbSecInsertData _
        And dbSecReplaceData And dbSecDeleteData
    SetPermissions = True

ExitSetPermissions
    Set dbs = Nothing
    Exit Function

ErrorSetPermissions
    MsgBox Err & ": " & Err.Description
    SetPermissions = False
    Resume ExitSetPermissions
End Function

The next procedure prompts the user to enter their name and a password and creates a PID value:

Sub NewUserPrompt()
    Dim strName As String, strPassword As String
    Dim intR As Integer, strPID As String
    Dim blnReturn As Boolean

    ' Prompt user for name and password.
    strName = InputBox("Enter your name.")
    strPassword = InputBox("Enter a password with " _
        & "up to 14 characters.")
    ' Seed random number generator.
    Randomize
    ' Generate PID string.
    For intR = 0 To 19
        strPID = strPID & Chr$(Int(256 * Rnd))
    Next intR
    ' Call SetPermissions function.
    blnReturn = SetPermissions(strName, strPID, strPassword)
End Sub


PictureData Property Example

The following example uses three image controls to animate a butterfly image across a form. The Hidden1 image control contains a picture of a butterfly with its wings up and the Hidden2 image control contains a picture of the same butterfly with its wings down. Both image controls have their Visible property set to False (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 + 200
End Sub


 Position Property

Position Property

You can't set the Position property to the intrinsic constant msoBarPopup. To create a shortcut menu, use the Position argument of the Add method of the CommandBars collection.


PostalAddress

PostalAddress Property

You can use the PostalAddress property to specify or determine the postal code and the Customer Barcode data corresponding to the address information displayed in a specified field/textbox. The PostalAddress wizard enables the setting of these properties.

Setting

For processing the conversion, correct settings are necessary for all properties of field/textbox that will contain postal code, address, Customer Barcode data.

For settings, use section 1 to 3, delimiting with semicolon (;).

Setting for field/textbox for Postal code

Specifies the type of postal code for the field/textbox.

Section | Description
1 | Specifies field/textbox for Prefecture names
2 | Specifies field/textbox for City/Ward/County
3 | Specifies field/textbox for Street/Town/Village

Setting for field/textbox for address

Specifies the field/textbox contains a postal code or Customer Barcode data.

Section | Description
1 | Specifies field/textbox for postal code
2 | Specifies field/textbox for Customer Barcode data

Note Two semicolons are required at the end of the value.

Setting for field/textbox for Customer Barcode data

Specifies the type of Customer Barcode data in the field/textbox. This setting is the same as the field/textbox for postal code.

Section | Description
1 | Specifies field/textbox for Prefecture names
2 | Specifies field/textbox for City/Ward/County
3 | Specifies field/textbox for Street/Town/Village

Remarks

The postal code consist of 3 address items; Prefecture, City/Ward/County, Street/Town/Village. Sections in PostalAddress property of field/textbox for a postal code can be omitted. The following table shows how to omit sections from the property setting.

Property Settings | Address input in field/textbox
 | Address1 | Address2 | Address3
Address1 | Prefecture+City/Ward/County+Street/Town/Village |  |
Address1; | Prefecture |  |
;Address1 | City/Ward/County+Street/Town/Village |  |
;Address1; | City/Ward/County |  |
;;Address1 | Street/Town/Village |  |
Address1;Address2 | Prefecture | City/Ward/County+Street/Town/Village |
Address1;Address1 | Prefecture+City/Ward/County+Street/Town/Village |  |
Address1;Address2; | Prefecture | City/Ward/County |
Address1;Address1; | Prefecture+City/Ward/County |  |
;Address1;Address2 | City/Ward/County | Street/Town/Village |
;Address1;Address1 | City/Ward/County+Street/Town/Village |  |
Address1;Address2;Address3 | Prefecture | City/Ward/County | Street/Town/Village
Address1;Address2;Address2 | Prefecture | City/Ward/County+Street/Town/Village |
Address1;Address1;Address2 | Prefecture+City/Ward/County | Street/Town/Village |
Address1;Address1;Address1 | Prefecture+City/Ward/County+Street/Town/Village |  |

The postal code converter program has been developed and licensed by Advanced Giken Corporation for Microsoft Corporation.


PreviousControl Property 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 If
Process_Bye:
    Exit Function
Process_Err:
    If Err = conNoPreviousControl Then
        Me!txtFinalEntry.SetFocus
        MsgBox "Please enter a value to process."
        ProcessData = False
    End If
    Resume Process_Bye
End Function


 PrimaryKey Property

PrimaryKey Property

In Microsoft Access, when you set a primary key for a table in table Design view, the primary key is automatically defined as the primarykey index.


 Primary Property (MDB)

Primary Property (MDB)

In Microsoft Access, when you set a primary key for a table in table Design view, the primary key is automatically defined as the primary index.


ProcOfLine Property 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.
    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 strMsg
End Function

You could call this function with a procedure such as the following:

Sub GetAllProcs()
    AllProcs "Utility Functions"
End Sub


ProcStartLine, ProcBodyLine, ProcCountLines Properties 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

    ' 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


Properties Property (Properties Collection) Example

The following example enumerates the Properties collection of the open Orders form and prints the name of each property and its value.

Sub CurrentPropSettings()
    Dim frm As Object, prp As Integer
    Set frm = Application.Forms("Orders")
    ' Enumerate Properties collection.
    For prp = 0 To frm.Properties.Count - 1
        ' Print name of property and value.
        Debug.Print frm.Properties(prp).Name & " = " _
            & frm.Properties(prp).Value
    Next prp
End Sub


Properties Property 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 Me
End Sub

Sub ListControlProps(frm As Form)
    Dim ctl As Control, prp As Property

    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 If
End Sub


 Protection Property

Protection Property

In Microsoft Access 2000, you can use the Toolbar Properties sheet to set the various options of the Protection property that prevent or allow user customization of a menu bar, toolbar, or custom shortcut menu. Point to Toolbars on the View menu and click Customize, then click the Properties button in the Customize dialog box. Select the menu bar, toolbar, or custom shortcut menu you want in the Selected Toolbar box, and then use the Docking combo box and the Allow Customizing, Allow Resizing, Allow Moving, and Allow Showing/Hiding check boxes to set the protection you want. For custom shortcut menus, the only option that's available is Allow Customizing.


PrtDevMode Property Example

The following example uses the PrtDevMode property to check the user-defined page size for a report:

Type str_DEVMODE
    RGB As String * 94
End Type

Type type_DEVMODE
    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 Long
End Type

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 If
End Sub

The following example shows how to change the orientation of the report. This example will switch the orientation from portrait to landscape or landscape to portrait depending on the report's current orientation.

Sub SwitchOrient(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
    ' Opens report in Design view.
    DoCmd.OpenReport strName, acDesign
    Set rpt = Reports(strName)
    If Not IsNull(rpt.PrtDevMode) Then
        strDevModeExtra = rpt.PrtDevMode
        DevString.RGB = strDevModeExtra
        LSet DM = DevString
        DM.lngFields = DM.lngFields Or _
             DM.intOrientation    ' Initialize fields.
        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 If
End Sub


PrtMip Property Example

The following PrtMip property example demonstrates how to set up the report with two horizontal columns.

Type str_PRTMIP
    strRGB As String * 28
End Type
Type type_PRTMIP
    xLeftMargin As Long
    yTopMargin As Long
    xRightMargin As Long
    yBotMargin As Long
    fDataOnly As Long
    xWidth As Long
    yHeight As Long
    fDefaultSize As Long
    cxColumns As Long
    yColumnSpacing As Long
    xRowSpacing As Long
    rItemLayout As Long
    fFastPrint As Long
    fDatasheet As Long
End 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
    ' Create two columns.
    PM.intColumns = 2
    ' Set 0.25 inch between rows.
    PM.intRowSpacing = 0.25 * 1440
    ' Set 0.5 inch between columns.
    PM.intColumnSpacing = 0.5 * 1440
    PM.intItemLayout = PM_HORIZONTALCOLS

    LSet PrtMipString = PM            ' Update property.
    rpt.PrtMip = PrtMipString.strRGB
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.strRGB
End Sub


QueryTimeout Property Example

QueryTimeout Property Example (MDB)

The following example sets the QueryTimeout property of the current database:

Sub SetTimeout()
    Dim dbs As Database

    ' Return reference to current database.
    Set dbs = CurrentDb
    dbs.QueryTimeout = 120
    Set dbs = Nothing
End Sub


Error Property, PageCount Property, SnapshotPath Property, and ReadyStateChange Event Examples

The following example uses a Select Case statement in a Snapshot control's ReadyStateChange event procedure to determine the status of the ReadyState property. If a snapshot file is successfully loaded into the control, a message box is displayed showing file path and page count information. If an error occurs loading the snapshot, a custom error handling procedure is called to display information about the error that occurred. At the beginning of the procedure, constants are defined for each of the possible values for the ReadyState property.

Private Sub Snapshot1_ReadyStateChange(ByVal ReadyState As Long)
    Const conSnpNotInitialized = 0
    Const conSnpLoading = 1
    Const conSnpStillDownloading = 2
    Const conSnpDownloadComplete = 4
    Select Case ReadyState
        Case conSnpNotInitialized
            ' Snapshot control is not initialized.
        Case conSnpLoading
            ' Snapshot control is loading.
        Case conSnpStillDownloading
            ' Snapshot control is loaded, but the snapshot
            ' file is still downloading.
        Case conSnpDownloadComplete
            ' Snapshot loading is complete.
        With Snapshot1
            If .Error = 0 Then
                ' Snapshot file successfully loaded into control.
                    Msgbox .SnapshotPath & _
                    " has been successfully loaded into the " _
                    & "Snapshot Viewer control." & vbCrLf & vbCrLf _
                    & "This snapshot file contains " & .PageCount _
                    & " pages."
            Else
                ' An error occurred loading the snapshot file.
                Call HandleSnapError(.SnapshotPath, .Error)
                Exit sub
            End If
        End With
    End Select
End Sub

Sub HandleSnapError(strFile As String, lngError As Long)
    Dim strError As String
    Select Case lngError
        Case 2500
            strError = "Error " & CStr(lngError) & ": Invalid value."
        Case 2501
            strError = "Error " & CStr(lngError) & ": Invalid page."
        Case 2502
            strError = "Error " & CStr(lngError) & _
                ": Missing or invalid snapshot file."
        Case 2503
            strError = "Error " & CStr(lngError) & _
                ": Property is read-only."
        Case 2504
            strError = "Error " & CStr(lngError) & _
                ": Operation canceled by user."
        Case 2505
            strError = "Error " & CStr(lngError) & _
                ": You need a newer version of the " _
                & "Snapshot Viewer control to view this snapshot file."
        Case 2506
            strError = "Error " & CStr(lngError) & _
                ": An error occurred while printing."
        Case 2507
            strError = "Error " & CStr(lngError) & _
                ": An error occurred while opening a snapshot file."
        Case 2508
            strError = "Error " & CStr(lngError) & ": Out of memory."
        Case 2509
            strError = "Error " & CStr(lngError) & _
                ": An error occurred writing to a " _
                & "temporary file while opening a snapshot file."
        Case 2510
            strError = "Error " & CStr(lngError) & _
                ": You have no printer installed, or no printer " _
                & "has been selected as the default."
        Case Else
            strError = "Error " & CStr(lngError) & _
                ": An unknown error occurred."
    End Select

    MsgBox strError & " File: " & strFile
End Sub


RecordCount Property Example

RecordCount Property Example (MDB)

The following example creates a Recordset object based on the Orders table and then determines the number of records in the Recordset object:

Sub CountRecords()
    Dim dbs As Database, rst As Recordset

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Open table-type Recordset object.
    Set rst = dbs.OpenRecordset("Orders")
    Debug.Print rst.RecordCount
    rst.Close
    Set dbs = Nothing
End Sub


RecordsAffected Property Example

RecordsAffected Property Example (MDB)

The following example prints the number of records updated by an action query:

Sub RecordsUpdated()
    Dim dbs As Database, qdf As QueryDef
    Dim strSQL As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    strSQL = "UPDATE Employees SET Title = " _
        & "'Senior Sales Representative' " _
        & "WHERE Title = 'Sales Representative';"
    ' Create new QueryDef object.
    Set qdf = dbs.CreateQueryDef("UpdateTitles", strSQL)
    ' Execute QueryDef object.
    qdf.Execute
    Debug.Print qdf.RecordsAffected
    Set dbs = Nothing
End Sub


RecordsetClone 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 Immediate 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
    Next
End Sub

The next example uses the RecordsetClone property and the Recordset object to synchronize a recordset's record with the form's current record. When a company name is selected from a combo box, the FindFirst method is used to locate the record for that company and the Recordset object's 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.Find "SupplierID = " & strSearchName
        If rst.NoMatch Then
            MsgBox "Record not found"
        Else
            Me.Bookmark = rst.Bookmark
        End If
    rst.Close
End Sub


RecordsetType Property Example

In the following example, only if the user ID is ADMIN can records be updated. This code sample sets the RecordsetType property to Snapshot if the 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 If
End Sub


Recordset Property Example

The following example uses the Recordset property to create a new copy of the Recordset object from the currently form and then prints the names of the fields in the Debug window.

Sub Print_Field_Names()
    Dim rst As DAO.Recordset, intI As Integer
    Dim fld As Field

    Set rst = Me.Recordset
    For Each fld in rst.Fields
        ' Print field names.
        Debug.Print fld.Name
    Next
End Sub

The next example uses the Recordset 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, causing the form to display the found record.

Sub SupplierID_AfterUpdate()
    Dim rst As DAO.Recordset
    Dim strSearchName As String

    Set rst = Me.Recordset
    strSearchName = Str(Me!SupplierID)
    rst.FindFirst "SupplierID = " & strSearchName
        If rst.NoMatch Then
            MsgBox "Record not found"
        End If
    rst.Close
End Sub

The following code helps to determine what type of recordset is returned by the Recordset property under different conditions.

Sub CheckRSType()
    Dim rs as Object

    Set rs=Forms(0).Recordset
    If TypeOf rs Is DAO.Recordset Then
    MsgBox "DAO Recordset"
    ElseIf TypeOf rs is ADODB.Recordset Then
    MsgBox "ADO Recordset"
    End If
End Sub


RecordSource Property Example

The following example sets a form's RecordSource property to the Customers table:

Forms!frmCustomers.RecordSource = "Customers"

The next example changes a form's record source to a single record in the Customers table, depending on the company name selected in the cmboCompanyName combo box control. The combo box is filled by an SQL statement that returns the customer ID (in the bound column) and the company name. 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 = strNewRecord
End Sub


ReplicationConflictFunction Property 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 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 = True

Exit_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 If
End 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 If
End Sub


ResyncCommand and UniqueTable Properties Example Scenario

There are two SQL Server tables involved in these scenarios, Patients and Doctors, with a one-to-many relationship from Doctors to Patients. Both tables have an identity column as a primary key.

Patients table

Column | Datatype | Attributes
ID | int | identity, Primary Key
LastName | varchar(30) | not null
FirstName | varchar(20) | not null
PrimaryDoc | int | null Foreign Key references Doctors(DocID)

Doctors table

Column | Datatype | Attributes
DocID | int | identity, Primary Key
DocName | varchar(30) | not null Unique
DocPhone | char(15) | not null

The user wants to create an updatable datasheet view of data on patients and their doctors. The user wants the grid to show the following:

ID | LastName | FirstName | PrimaryDoc | DocName | DocPhone
1 | Jones | Peter | 10 | Welby | (206) 882-8080
2 | Williams | Jay | 20 | McCoy | (206) 936-4321
3 | Roberts | George | 20 | McCoy | (206) 936-4321
4 | Crary | Dave | 10 | Welby | (206) 882-8080

The actual query underlying this form is logically:

SELECT P.ID, P.LastName, P.FirstName, P.PrimaryDoc, D.DocName, _
    D.DocPhone FROM Patients P JOIN Doctors D ON _
    ( P.PrimaryDoc = D.DocID)

User interface actions

  1. The user wants to change the assigned doctor for George Roberts to Dr. Gui (who is an existing doctor with no currently assigned patients). User types in Dr. GUI's DocID value of 30 in the PrimaryDoc column of the 3rd row. User now expects to see "Gui" under DocName and Dr. Gui's phone number in this row.

    Note Normally the Microsoft Access user would want a Lookup column defined on PrimaryDoc so the user could selecta name from a dropdown list and wouldn't have to know the ID for Dr. GUI. In this case there wouldn't likely be a separate column for the DocName-- it would show up in the place of the Primary Doc column. But the user would still expect Dr. Gui's correct phone to appear after the update was made.

  2. The user clicks on * row, wants to add a new patient and assign him to Dr. Welby. Since the ID column is an Identity column for the Patients table, the UI should display something like "(AutoNumber)" in that first cell and not allow the user to enter a value. The user enters in a new patient first name and last name and an existing DocID value in the PrimaryDoc column. A new record is inserted in the Patients table, the ID column should be updated with the newly generated value and displayed on the grid, and the Doctor name and phone columns should be looked up from existing data.

  3. The user wants to delete Peter Jones. The user selects the row and selects Delete. Peter Jones' record is deleted from the Patients table, the row is removed from the cursor, but the cursor does not attempt to delete Dr. Welby's record from the Doctors table (this would generate a server error if DRI was enforced, but even if not enforced by the database, deleting Dr. Welby's record would invalidate the data in row 4, so it should not be attempted by the cursor.)


RowHeight, ColumnWidth Properties Example

The following example changes the row height in Datasheet view of the Customers table to display two lines of data (450 twips) and sets the width of the Address column to 1.5 inches (2160 twips). These property settings will take effect the next time the Customers table is opened in Datasheet view.

To set the RowHeight and ColumnWidth properties, the example uses the SetTableProperty procedure, which is shown in the example for the DatasheetFontItalic and DatasheetFontUnderline properties, and the SetFieldProperty procedure, which is shown in the example for the ColumnHidden property.

Dim dbs As Object, tdfCustomers As Object
Const DB_Long As Long = 4
Const DB_Integer As Integer = 3
Set dbs = CurrentDb
Set tdfCustomers = dbs![Customers]
SetTableProperty tdfCustomers, "RowHeight", DB_Long, 450
SetFieldProperty tdfCustomers![Address], "ColumnWidth", DB_Integer, 2160

The next example takes effect in Datasheet view of the open Customers form. It sets the row height to 450 twips and sizes the column to fit the size of the visible text.

Forms![Customers].RowHeight = 450
Forms![Customers]![Address].ColumnWidth = -2


RowSourceType, RowSource Properties Example - Settings

RowSourceType, RowSource Properties Example — Settings

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 the RowSource and ColumnCount properties and an illustration of the resulting list.

RowSource setting | List
Mon;Tue;Wed (ColumnCount = 1) | One-column list with three rows
1;Monday;2;Tuesday;3;Wednesday;4;Thursday (ColumnCount = 2) | Two-column list with four rows
Country;Capital;China;Beijing;Brazil;Brasilia (ColumnCount = 2, ColumnHeads = Yes) | Two-column list with one row of column heads and two rows of data

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

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.


RowSourceType, RowSource Properties Example - Visual Basic

RowSourceType, RowSource Properties Example — Visual Basic

The following example sets the RowSourceType property for a combo box to Table/Query, and it sets the RowSource property to a query named EmployeeList.

Forms!Employees!cmboNames.RowSourceType = "Table/Query"
Forms!Employees!cmboNames.RowSource = "EmployeeList"


 RowSourceType Property (User-Defined Function) - Code Argument Values

RowSourceType Property (User-Defined Function) — Code Argument Values

The Visual Basic function you create must accept five arguments. The first argument must be declared as a control and the remaining arguments as Variants. The function itself must return a Variant.

Syntax

Function functionname(fld As Control, id As Variant, row As Variant, col As Variant, code As Variant) As Variant

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

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.

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

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 RowSourceType property user-defined functions.


RowSourceType Property (User-Defined Function) - Code Argument Values Example

RowSourceType Property (User-Defined Function) — Code Argument Values Example

The following user-defined function returns a list of the next four Mondays following today's date. To call this function from a list box control, enter ListMondays as the RowSourceType property setting and leave the RowSource property setting blank.

Function ListMondays(fld As Control,id As Variant, _
    row As Variant,col As Variant,code As Variant) _
     As Variant
    Dim intOffset As Integer
    Select Case code
        Case 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 Select
End 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.
            ' Generate unique ID for control.
            ReturnVal = Timer
        Case acLBGetRowCount            ' Get number of rows.
            ReturnVal = Entries
        Case acLBGetColumnCount    ' Get number of columns.
            ReturnVal = 1
        Case acLBGetColumnWidth    ' Column width.
            ' -1 forces use of default width.
            ReturnVal = -1
        Case acLBGetValue                    ' Get data.
            ReturnVal = dbs(row)
        Case acLBEnd                        ' End.
            Erase dbs
    End Select
    ListMDBs = ReturnVal
End Function


RunningSum Property Example - Sales Report

RunningSum Property Example — Sales Report

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 Food 100 | YTD Sales 100
Type of Food: Meat
03-Jan | 90 |  |
20-Jan | 60 |  |
January Meat | 150 | Jan Food 250 | YTD Sales 250
Month: February
Type of Food: Chocolates
05-Feb | 70 |  |
19-Feb | 80 |  |
February Chocolates | 150 | Feb Food 150 | YTD Sales 400
Type of Food: Meat
12-Feb | 150 |  |
22-Feb | 100 |  |
February Meat | 250 | Feb Food 400 | YTD Sales 650


RunningSum Property Example - Visual Basic

RunningSum Property Example — Visual Basic

The following example sets the RunningSum property for a text box named SalesTotal to 2 (Over All):

Reports!rptSales!SalesTotal.RunningSum = 2


RunPermissions Property Example

The following example is a select query based on the Categories table that enables all users to have the owner's permissions for the query. You enter this SQL statement in SQL view of the Query window.

SELECT Categories.CategoryID, Categories.CategoryName, Categories.Description
FROM Categories WITH OWNERACCESS OPTION;


Selected Property Example

The following example uses the Selected property to move selected items in the lstSource list box to the lstDestination list box. The lstDestination list box's RowSourceType property is set to Value List and the control's RowSource property is constructed from all the selected items in the lstSource control. The lstSource list box's MultiSelect property is set to Extended. The CopySelected( ) function is called from the cmdCopyItem command button.

Sub cmdCopyItem_Click()
    CopySelected Me
End Sub

Function CopySelected(frm As Form) As Integer
    Dim ctlSource As Control
    Dim ctlDest As Control
    Dim strItems As String
    Dim intCurrentRow As Integer
    Set ctlSource = frm!lstSource
    Set ctlDest = frm!lstDestination
    For intCurrentRow = 0 To ctlSource.Listcount - 1
        If ctlSource.Selected(intCurrentRow) Then
            strItems = strItems & ctlSource.Column(0, _
                 intCurrentRow) & ";"
        End If
    Next intCurrentRow
    ' Reset destination control's RowSource property.
    ctlDest.RowSource = ""
    ctlDest.RowSource = strItems
End Function


SelHeight, SelWidth, SelTop, and SelLeft Properties Example

The following example shows how to use the SelHeight, SelWidth, SelTop, and SelLeft properties to determine the position and size of a selection rectangle in datasheet view. The SetHeightWidth procedure assigns the height and width of the current selection rectangle to the variables 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 If
End Sub


SelLength, SelStart, SelText Properties 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 With
End Sub


ShortcutMenu Property Example

The following example disables the shortcut menus for the Invoice form and its controls:

Forms!Invoice.ShortcutMenu = False


 ShortcutText Property

ShortcutText Property

In Microsoft Access 2000, you can use the Toolbar Control Properties dialog box for command bar controls to set the shortcut text that's displayed to the right of a built-in button control on a menu, submenu, or shortcut menu. Display the Customize dialog box by pointing to Toolbars on the View menu and clicking Customize. For menu bar and toolbar controls, display the menu bar or toolbar, and then right-click the button control whose ShortcutText property you want to set. For shortcut menu controls, select the Shortcut Menus check box on the Toolbars tab of the Customize dialog box, then find the shortcut menu control you want on the menu bar that's displayed and right-click the control. Click the Properties command. Enter the shortcut text you want in the Shortcut Text box. You can set this property for any built-in button control in Microsoft Access, but not for custom button controls.

Setting this property in Microsoft Access just causes the shortcut text to be displayed next to the control. If you change or add shortcut text for a built-in control, typing this shortcut key or key combination doesn't run the command associated with this control. To run this command, you must assign the shortcut key or key combination in an AutoKeys macro. In the AutoKeys macro, assign the key or key combination to a macro that uses the RunCommand action to run the command.

For custom commands, you can't display the shortcut text next to the control, but you can use the AutoKeys macro to assign a shortcut key or key combination that will run the same set of actions as the macro or function that's the setting of the control's OnAction property. Assign the key or key combination to the desired set of macro actions, or use the RunMacro or RunCode action to run the macro or function you want this key or key combination to carry out.


 Size Property (MDB)

Size Property (MDB)

The Size property is equivalent to the FieldSize property in table Design view. You can't set the FieldSize property by using Visual Basic; you must use the Size property instead.

In Microsoft Access, the Memo data type field can contain up to 1.2 gigabytes of information. However, Microsoft Access only displays the first 32 kilobytes of data in a control on a form or report.


Size, Type Properties Example

Size, Type Properties Example (MDB)

The following example creates a new Field object and sets its Size and Type properties. The procedure then appends the new object to the Fields collection of the Employees table in the TableDefs collection of the database.

Sub NewField()
    Dim dbs As Database, tdf As TableDef
    Dim fld As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Return reference to Employees table.
    Set tdf = dbs.TableDefs!Employees
    ' Create Field object.
    Set fld = tdf.CreateField("DaysOfVacation")
    ' Set field properties.
    fld.Type = dbText
    fld.Size = 20
    ' Append fld to Fields collection.
    tdf.Fields.Append fld
    Set dbs = Nothing
End Sub

You can also use the CreateField method to set the Name, Type, and Size properties if you provide name, type, and size as arguments.

Set fld = tdfEmployees.CreateField("DaysOfVacation", dbText, 20)


OutputTo and SendObject Methods, Snapshot Object Type Examples

The following example outputs a snapshot file to disk or embedded in a mail message depending on the value supplied in the intOutputTO argument. There are two global constants defined in the declarations section of the module that are used to specify the type of output desired. If the intOutputTO argument contains the constant conSaveSnapshotToDisk, then the file is saved using the location and file name supplied in the strPath argument. If the intOutputTO argument contains the constant conSaveSnapshotToMail, then the file is embedded in a mail message addressed to the name supplied in the strRecipName argument. The strName argument is the name of a Report object in the current database. The strPath argument is the full path and file name representing the snapshot file to be saved to disk.

Const conSaveSnapshotToDisk As Integer = 1
Const conSaveSnapshotToMail As Integer = 2

Sub OutputSnapshotFile(intOutputTO As Integer, _
    strName As String, Optional strPath As String, _
    Optional strRecipName As String)

    Dim strOutputFormat As String
    DoCmd.Hourglass True
    strOutputFormat = "Snapshot Format"

    Select Case intOutputTO
        Case conSaveSnapshotToDisk
            If Len(strPath) > 0 Then
                DoCmd.OutputTo acOutputReport, _
                    strName, strOutputFormat, strPath
            Else
                DoCmd.Hourglass False
                Exit Sub
            End If
        Case conSaveSnapshotToMail
            If Len(strRecipName) > 0 Then
                DoCmd.SendObject acSendReport, _
                    strName, strOutputFormat, strRecipName
            Else
                DoCmd.Hourglass False
                Exit Sub
            End If
        Case Else
    End Select
    DoCmd.Hourglass False
End Sub


Sort Property Example

Sort Property Example (MDB)

The following example uses the Sort property to set the sort order of a dynaset-type Recordset object based on an Orders table. The records in the rstSorted recordset variable will be ordered alphabetically by ship country.

Note that you first create a dynaset-type Recordset object and set its Sort property, then open a second dynaset-type Recordset object based on the first. Setting the Sort property of the first Recordset object doesn't actually affect the order of the records that it contains, so you need to create a second Recordset object in order to see the effects of the sort.

Sub SortByCountry()
    Dim dbs As Database
    Dim rstOrders As Recordset, rstSorted As Recordset

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create dynaset-type Recordset object.
    Set rstOrders = dbs.OpenRecordset("Orders", dbOpenDynaset)
    ' Set sort order.
    rstOrders.Sort = "ShipCountry"
    ' Create second dynaset-type Recordset object.
    Set rstSorted = rstOrders.OpenRecordset()
    ' Perform operations with recordset.
    .
    .
    .
    rstOrders.Close
    rstSorted.Close
    Set dbs = Nothing
End Sub

Tip In most situations, it's more efficient to create the second Recordset object with the desired conditions in one step. When you know the data you want to select, it's generally more efficient to create a Recordset object with an SQL statement. The next example shows how you can create just one Recordset object and obtain the same results as in the preceding example:

Sub CreateRecordsetWithSQL()
    Dim dbs As Database, rst As Recordset
    Dim strSelect As String

    Set dbs = CurrentDb
    strSelect = "SELECT * FROM Orders ORDER BY ShipCountry;"
    Set rst = dbs.OpenRecordset(strSelect)
    rst.MoveLast
    MsgBox "Recordset contains " & rst.RecordCount & " records."
    rst.Close
End Sub


OLE Object Properties 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.
    ' Specify type of object.
    OLE1.OLETypeAllowed = acOLELinked
    ' Specify source file.
    OLE1.SourceDoc = "C:\Excel\Oletext.xls"
    ' Specify data to create link to.
    OLE1.SourceItem = "R1C1:R5C5"
    ' Create linked object.
    OLE1.Action = acOLECreateLink
    ' Adjust control size.
    OLE1.SizeMode = acOLESizeZoom
End Sub


SourceField, SourceTable Properties Example

SourceField, SourceTable Properties Example (MDB)

The following example creates a Recordset object by using an SQL statement that creates aliases for fields in two different tables in the database. The example then prints the name of the field, the original table, and the original field.

Sub SourceInfo()
    Dim dbs As Database, rst As Recordset, fld As Field
    Dim strSQL As String

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Construct SQL statement.
    strSQL = "SELECT ProductID As ProductCode, " _
        & "CategoryName As TypeOfProduct FROM Categories " _
        & "INNER JOIN Products ON Categories.CategoryID " _
        & " = Products.CategoryID;"
    ' Open dynaset-type Recordset object.
    Set rst = dbs.OpenRecordset(strSQL)
    For Each fld In rst.Fields
        ' Print field name.
        Debug.Print "Field Name: "; fld.Name
        ' Print original table name.
        Debug.Print "Source Table: "; fld.SourceTable
        ' Print original field name.
        Debug.Print "Source Field: "; fld.SourceField
        Debug.Print
    Next fld
    rst.Close
    Set dbs = Nothing
End Sub


SourceObject 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! _
    [Product List].SourceObject


 Source Property

Source Property

The Source property applies to the Error object and can be read only from Visual Basic.

Note Don't confuse this property with the Microsoft Access Source property, which applies to a query and specifies the source connection string and source database for the query's input table or query.


Source Property 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 String
strGetSQL = "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.PHONE
FROM Customer IN 'c:\dbdata'[dBASE IV;];


SQL Property Example

SQL Property Example (MDB)

The following example creates a parameter query based on an Orders table. The query selects all orders for which the order date falls between the dates entered by the user.

Sub RangeOfOrders()
    Dim dbs As Database, qdf As QueryDef, rst As Recordset

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create new query.
    Set qdf = dbs.CreateQueryDef("RangeOfOrders")
    ' Construct SQL statement including parameters.
    qdf.SQL = "PARAMETERS [Start] DATETIME, [End] DATETIME; " & _
        "SELECT * FROM Orders WHERE OrderDate BETWEEN " _
        & "[Start] AND [End];"
    qdf.Parameters("Start") = #1/1/96#
    qdf.Parameters("End") = #1/31/96#
    ' Create snapshot-type Recordset object from QueryDef object.
    Set rst = qdf.OpenRecordset(dbOpenSnapshot)
    ' Perform operations with recordset.
    .
    .
    .
    rst.Close
    Set dbs = Nothing
End Sub


Startup Properties 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. 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()
Const DB_Text As Long = 10
Const DB_Boolean As Long = 1
    ChangeProperty "StartupForm", DB_Text, "Customers"
    ChangeProperty "StartupShowDBWindow", DB_Boolean, False
    ChangeProperty "StartupShowStatusBar", DB_Boolean, False
    ChangeProperty "AllowBuiltinToolbars", DB_Boolean, False
    ChangeProperty "AllowFullMenus", DB_Boolean, True
    ChangeProperty "AllowBreakIntoCode", DB_Boolean, False
    ChangeProperty "AllowSpecialKeys", DB_Boolean, True
    ChangeProperty "AllowBypassKey", DB_Boolean, True
End Sub

Function ChangeProperty(strPropName As String, varPropType As Variant, varPropValue As Variant) As Integer
    Dim dbs As Object, prp As Variant
    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 If
End Function


 State Property

State Property

You can use the State property to place or remove a check beside a menu item or command button. This property replaces the functionality supplied by the SetMenuItem action and SetMenuItem method in Microsoft Access 95.


 Style Property

Style Property

In Microsoft Access 2000, you can use the Toolbar Control Properties dialog box for command bar controls to set the display style for a button control on a command bar. Display the Customize dialog box by pointing to Toolbars on the View menu and clicking Customize. For menu bar and toolbar controls, display the menu bar or toolbar, and then right-click the control whose Style property you want to set. For shortcut menu controls, select the Shortcut Menus check box on the Toolbars tab of the Customize dialog box, then find the shortcut menu control you want on the menu bar that's displayed and right-click the control. Click the Properties command. Select the style you want in the Style box.

The settings in the Style box correspond to the intrinsic constants used as the setting of the Style property in the following way.

Style box setting | Style property constant
Default Style | msoButtonAutomatic
Text Only (Always) | msoButtonCaption
Text Only (in Menus) | msoButtonIcon
Image and Text | msoButtonIconAndCaption
No Label | msoComboNormal
Show Label | msoComboLabel


TabIndex Property Example

The following example reverses the tab order of a command button and a text box. Because TextBox1 was created first, it has a TabIndex property setting of 0 and Command1 has a setting of 1.

Sub Form_Click()
    Me!Command1.TabIndex = 0
    Me!TextBox1.TabIndex = 1
End Sub


 Tag Property (Command Bars)

Tag Property (Command Bars)

In Microsoft Access 2000, you can use the Toolbar Control Properties dialog box for command bar controls to set the Tag property for a control on a command bar. Display the Customize dialog box by pointing to Toolbars on the View menu and clicking Customize. For menu bar and toolbar controls, display the menu bar or toolbar, and then right-click the control whose Tag property you want to set. For shortcut menu controls, select the Shortcut Menus check box on the Toolbars tab of the Customize dialog box, then find the shortcut menu control you want on the menu bar that's displayed and right-click the control. Click the Properties command. Enter the information you want in the Tag box.


Tag Property Example

The following example uses the Tag property to display custom messages about controls on a form. When a control has the focus, descriptive text is displayed in a label control called lblMessage. You specify the text for the message by setting the Tag property for each control to a short text string. When a control receives the focus, its Tag property is assigned to the label control's Caption property. 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 Sub

Sub txtDescription_GotFocus()
    Me!lblMessage.Caption = Me!txtDescription.Tag     ' Tag property setting as caption.
End Sub

Sub txtDescription_LostFocus()
    Me!lblMessage.Caption = ""
End Sub

Sub cmdButton_GotFocus()
    Me!lblMessage.Caption = Me!cmdButton.Tag         ' Tag property setting as caption.
End Sub

Sub cmdButton_LostFocus()
    Me.lblMessage.Caption = " "
End Sub


Text 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 & "")<>0
End Sub


TimerInterval Property Example

The following example shows how to create a flashing button on a form by displaying and hiding an icon on the button. The form's Load event procedure sets the form's TimerInterval property to 1000 so the icon display is toggled once every second.

Sub Form_Load()
    Me.TimerInterval = 1000
End Sub

Sub Form_Timer()
    Static intShowPicture As Integer
    If intShowPicture Then
        ' Show icon.
        Me!btnPicture.Picture = "C:\Icons\Flash.ico"
    Else
        ' Don't show icon.
        Me!btnPicture.Picture = ""
    End If
    intShowPicture = Not intShowPicture
End Sub


 TooltipText Property

TooltipText Property

In Microsoft Access 2000, you can use the Toolbar Control Properties dialog box for command bar controls to set the ToolTip (ScreenTip) for a control on a command bar. Display the Customize dialog box by pointing to Toolbars on the View menu and clicking Customize. For menu bar and toolbar controls, display the menu bar or toolbar, and then right-click the control whose TooltipText property you want to set. For shortcut menu controls, select the Shortcut Menus check box on the Toolbars tab of the Customize dialog box, then find the shortcut menu control you want on the menu bar that's displayed and right-click the control. Click the Properties command. Enter the text you want in the ToolTip box.


TopValues Property 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 String
strGetSQL = "SELECT TOP 10 Products.[ProductName] " _
    & "AS TenMostExpensiveProducts, Products.UnitPrice FROM Products " _
    & "ORDER BY Products.[UnitPrice] DESC;"
Me.RecordSource = strGetSQL


 Type Property

Type Property

In Microsoft Access, you can set the data type for a field in table Design view, and you can set the data type for a parameter in the Query Parameters dialog box. These actions are equivalent to setting the ADO Type property for a Field object or a Parameter object by using Visual Basic.

The following table lists the ADO Type property constants and the corresponding Microsoft Access settings for field and parameter data types if you are setting them from table Design view or the Query Parameters dialog box.

When creating a table field with data type Number, set the FieldSize property to specify which of the six numeric data types the field will be. By default this property is set to Long Integer. The other settings are Byte, Integer, Single, Double, and ReplicationID.

Constant | Table field setting | Query parameter setting
adBoolean | Yes/No | Yes/No
adUnsignedTinyInt | Number (FieldSize = Byte) | Byte
adCurrency | Currency | Currency
adDate | Date/Time | Date/Time
adDouble | Number (FieldSize = Double) | Double
adGUID | Number or AutoNumber (FieldSize = ReplicationID) | Not supported
adSmallInt | Number (FieldSize = Integer) | Integer
adInteger | Number (FieldSize = Long Integer) | Long Integer
adInteger | AutoNumber (FieldSize = Long Integer) | Not supported
adLongVarBinary | OLE Object | OLE Object
 | Not supported | Binary
adLongVarWChar | Memo | Memo
adSingle | Number (FieldSize = Single) | Single
adVarWChar | Text | Text
adDecimal | Number (FieldSize = Decimal) | Not Supported
adBinary | Not Supported | Binary
Not supported | Not supported | Value

Note In Access databases (.mdb) the parameter data type Value doesn't correspond to a data type defined by the Microsoft Jet database engine. It corresponds to the SQL reserved word VALUE, which can be used to create a parameter query. In Microsoft Access or SQL queries, VALUE can be considered a valid synonym for the Visual Basic Variant data type.


 Type Property (MDB)

Type Property (MDB)

In Microsoft Access, you can set the data type for a field in table Design view, and you can set the data type for a parameter in the Query Parameters dialog box. These actions are equivalent to setting the DAO Type property for a Field object or a Parameter object by using Visual Basic.

The following table lists the DAO Type property constants and the corresponding Microsoft Access settings for field and parameter data types if you are setting them from table Design view or the Query Parameters dialog box.

When creating a table field with data type Number, set the FieldSize property to specify which of the six numeric data types the field will be. By default this property is set to Long Integer. The other settings are Byte, Integer, Single, Double, and ReplicationID.

Constant | Table field setting | Query parameter setting
dbBoolean | Yes/No | Yes/No
dbByte | Number (FieldSize = Byte) | Byte
dbCurrency | Currency | Currency
dbDate | Date/Time | Date/Time
dbDouble | Number (FieldSize = Double) | Double
dbGUID | Number or AutoNumber (FieldSize = ReplicationID) | Not supported
dbInteger | Number (FieldSize = Integer) | Integer
dbLong | Number (FieldSize = Long Integer) | Long Integer
 | AutoNumber (FieldSize = Long Integer) | Not supported
dbLongBinary | OLE Object | OLE Object
 | Not supported | Binary
dbMemo | Memo | Memo
dbSingle | Number (FieldSize = Single) | Single
dbText | Text | Text
Not supported | Not supported | Value

Note: The parameter data type Value doesn't correspond to a data type defined by the Microsoft Jet database engine. It corresponds to the SQL reserved word VALUE, which can be used to create a parameter query. In Microsoft Access or SQL queries, VALUE can be considered a valid synonym for the Visual Basic Variant data type.


Type Property Example

The following example determines whether a Module object represents a standard module or a class module:

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 If
End Function


UniqueRecords Property Example

The query in this example returns a list of customers from the Customers table who have at least one order in the Orders table.

Customers Table

Company name | Customer ID
Ernst Handel | ERNSH
Familia Arquibaldo | FAMIA
FISSA Fabrica Inter. Salchichas S.A. | FISSA
Folies gourmandes | FOLIG

Orders Table

Customer ID | Order ID
ERNSH | 10698
FAMIA | 10512
FAMIA | 10725
FOLIG | 10763
FOLIG | 10408

The following SQL statement returns the customer names in the following table:

SELECT DISTINCTROW Customers.CompanyName, Customers.CustomerID
FROM Customers INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID;
Customers returned | Customer ID
Ernst Handel | ERNSH
Familia Arquibaldo | FAMIA
Folies gourmandes | FOLIG


UniqueValues Property Example

The SELECT statement in this example returns a list of the countries in which there are customers. Because there may be many customers in each country, many records could have the same country in the Customers table. However, each country is represented only once in the query results.

This example uses the Customers table, which contains the following data.

Country | Company name
Brazil | Familia Arquibaldo
Brazil | Gourmet Lanchonetes
Brazil | Hanari Carnes
France | Du monde entier
France | Folies gourmandes
Germany | Frankenversand
Ireland | Hungry Owl All-Night Grocers

This SQL statement returns the countries in the following table:

SELECT DISTINCT Customers.Country
FROM Customers;
Countries returned
Brazil
France
Germany
Ireland


Updatable Property Example

Updatable Property Example (MDB)

The following example adds a record to a Recordset object if the object's Updatable property setting is True (–1).

Sub UpdateData()
    Dim dbs As Database, rstUnknown As Recordset

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Open table-type Recordset object.
    Set rstUnknown = dbs.OpenRecordset("Unfamiliar Table")
    ' Check Updatable property before adding new record.
    If rstUnknown.Updatable = True Then
        With rstUnknown
            .AddNew
            !SomeField = "Some new data"
            .Update
        End With
    End If
    rstUnknown.Close
    Set dbs = Nothing
End Sub


UseLongFileNames Property Example

This example cancels the use of long file names as the global default for the application.

Application.DefaultWebOptions.UseLongFileNames = False


 ValidationRule Property (MDB)

ValidationRule Property (MDB)

Use the data access ValidationRule property to set validation rules for a Field, Recordset, or TableDef object by using Visual Basic.

You can also set validation rules for a field or control in the Microsoft Access user interface. Set the Microsoft Access ValidationRule property for a field or a table in table Design view. Set the ValidationRule property of a control by using the property sheet in form Design view.

In Microsoft Access, the string expression specified by the ValidationRule property of a Field object can't refer to user-defined functions, domain aggregate functions, SQL aggregate functions, the CurrentUser function, the Eval function, or queries.


ValidationRule, ValidationText Properties Example

The following example creates a validation rule for a field that allows only values over 65 to be entered. If a number less than 65 is entered, a message is displayed. The properties are set by using the SetFieldValidation function.

Dim strTblName As String, strFldName As String
Dim strValidRule As String
Dim strValidText As String, intX As Integer

strTblName = "Customers"
strFldName = "Age"
strValidRule = ">= 65"
strValidText = "Enter a number greater than or equal to 65."
intX = SetFieldValidation(strTblName, strFldName, _
    strValidRule, strValidText)

Function SetFieldValidation(strTblName As String, _
    strFldName As String, strValidRule As String, _
    strValidText As String) As Integer

    Dim 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 = strValidText
End Function

The next example uses the SetTableValidation function to set record-level validation to ensure that the value in the EndDate field comes after the value in the StartDate field.

Dim strTblName As String, strValidRule As String
Dim strValidText As String
Dim intX As Integer

strTblName = "Employees"
strValidRule = "EndDate > StartDate"
strValidText = "Enter an EndDate that is later than the StartDate."
intX = SetTableValidation(strTblName, strValidRule, strValidText)

Function SetTableValidation(strTblName As String, _
    strValidRule As String, strValidText As String) _
    As Integer

    Dim dbs As Database, tdf As TableDef

    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs(strTblName)
    tdf.ValidationRule = strValidRule
    tdf.ValidationText = strValidText
End Function


Value Property Example

The following example shows how you can call one of two procedures, depending whether the Credit check box on the Customers form is selected or cleared.

Sub PaymentType()
    If Forms!Customers!Credit.Value = False Then
        ProcessCash
    ElseIf Forms!Customers!Credit.Value = True Then
        ProcessCredit
    End If
End Sub


VBE Property Example

This example displays the number of references available for the active project.

MsgBox "Number of References = " & VBE.ActiveVBProject _
    .References.Count


 Version Property

Version Property (MDB)

The Version property of a Database object returns the version of the Microsoft Jet database engine that applies to that database. For databases created in or converted to Microsoft Access 2000, Version returns 4.0. For Access 97 and Access 95 databases, Version returns 3.0. If you need to distinguish between databases in Microsoft Access 2000 format and databases in Access 97 format, use the SysCmd function with the intrinsic constant acSysCmdAccessVer as the action argument to determine which version of Microsoft Access created the database. For an Microsoft Access 2000 database, the SysCmd function will return 9.0. For an Access 97 database, it will return 8.0.


 About the default working folder

About the default working folder

The first time you open the Open and File New Database dialog boxes in Microsoft Access, the My Documents folder is the default working (or active) folder. If you install the Office Shortcut Bar, the My Documents folder is also the default folder that opens from both the Open Office Document button [image] on the Office Shortcut Bar and the Open Office Document command on the Windows Start menu.

The My Documents folder is located at the root directory. The Personal directory is a subdirectory of the Windows NT Workstation directory. Either of these folders is a good place to store documents, workbooks, presentations, databases, and other files you're working on.

Return to Set the default working folder


 Consequences of changing a field's data type

Consequences of changing a field's data type

At some point, you may need to change data types for fields that already contain data. Perhaps you imported data, and Microsoft Access didn't set the data types as you intended. Or maybe the data type you set for a field is no longer appropriate.

Before converting from one data type to another, consider how the change will affect your entire database. Which queries, forms, and reports use the field that is being converted? You may need to change expressions that depend on the changed field.

The most common data type changes fall into the following four categories: converting to Text from other data types; converting from Text to Number, Currency, Date/Time, or Yes/No; converting between Currency and Number or between Text and Memo; and changing the FieldSize property setting for Number fields.

This topic provides reference information about:

Converting to Text from other data types

Converting from Text to Number, Currency, Date/Time, or Yes/No

Converting between Currency and Number or between Text and Memo

Changing the FieldSize property setting for Number fields

Converting to Text from other data types

While you should store numbers that will be used in calculations in a Number or Currency field, you may find that a field that was originally just numbers now requires the use of letters and other non-numeric characters. For example, suppose you have a Number field that stores code numbers. If you later find you need to include letters, hyphens, parentheses, or other non-numeric characters as part of the code, you'll need to change the field's data type to Text.

Microsoft Access converts number values to text using a General Number format, and date values to text using a General Date format. The converted values will not include any currency symbols or other special formatting characters you set for the field.

Return to top

Converting from Text to Number, Currency, Date/Time, or Yes/No

If you have data stored in a Text field and want to change the field to another data type, Microsoft Access can convert values that are appropriate for the new data type. For example, if you have numbers stored in a Text field and you want to do mathematical calculations on your data, you must convert the field to the Number or Currency data type. As long as all the data stored in the field consists of only numbers, you can change the data type without losing data.

For Text to Number data type conversions, decimal points and thousands separators are interpreted appropriately. Currency symbols are interpreted according to the regional settings specified by double-clicking Regional Settings in Windows Control Panel.

For Text to Date/Time conversions, most date and time formats are converted correctly. Date and time formats are interpreted according to the regional settings specified by double-clicking Regional Settings in Windows Control Panel.

For Text to Yes/No conversions, the words Yes, True, or On are converted to a Yes value, and No, False, or Off to a No value. To display Yes or No, you must click the Lookup tab in table Design view and set the DisplayControl property to Text Box. (You can also convert from Number to Yes/No data type: zero or Null values convert to No and nonzero values to Yes.)

Return to top

Converting between Currency and Number or between Text and Memo

You can always convert between the Currency and Number data types. You should always store monetary values using the Currency data type to ensure that calculations are correct. You should also use a Currency data type if you plan to perform many calculations on a field that contains numbers with one to four decimal places. Currency fields use a fixed-point calculation method that avoids rounding errors. You can always convert between the Text and Memo data types. For example, if you want to store longer text values than you originally intended, you can change a field to the Memo data type. However, if a field doesn't have to store more than 255 characters, you should use the Text data type.

Return to top

Changing the FieldSize property setting for Number fields

For fields with the Number data type, the FieldSize property setting determines the specific number type: Byte, Integer, Long Integer, Single, Double, Decimal, or Replication ID (GUID). If you convert a field to the Number type, consider whether you need to change the FieldSize setting for the values you store in the field. If you change the FieldSize setting from a larger size, such as Double, to a smaller value, such as Integer, you must make sure that the values stored in the field fit in the new field size. If you change to a FieldSize setting that doesn't allow the number of decimal places included in your current values, the numbers are rounded. For example, if you change a field from Double to Long Integer, decimal numbers are rounded to the nearest whole number. Additionally, if the values are too large to be stored in the new size, they will be deleted and replaced with Null values.

To view a summary of data type conversion results, click [image] .

For information on the range of values each field size can store, click [image] .

Return to top


Controlling international data display formats

Microsoft Access can display a wide range of international formats. To help ensure consistency among applications, Microsoft Access uses the regional settings specified by double-clicking Regional Settings in the Windows Control Panel for the predefined Number and Date/Time formats listed in the following table.

Microsoft Access gets the format for | From this tab in the Regional Settings Properties dialog box
Standard (and other number formats except Currency) | Number tab
Currency | Currency tab
Short Date | Date tab
Long Date | Date tab
Long Time | Time tab

If your data isn't displayed in the right format for your country, change the regional settings specified in the Control Panel.

Note Transferring data between computers with different regional settings can result in incorrect currency data. For example, when using the Currency format, a value of 5,47 kr on a computer set for Denmark converts to $5.47 on a computer set for the United States. To prevent such errors, define a custom format for the currency, such as #,## kr. The custom format overrides the regional settings specified in the Windows Control Panel. Similar problems won't occur when transferring standard number, date, or time data between computers with different regional settings.


 Microsoft Access database general specifications

Microsoft Access database general specifications

Attribute | Maximum
Microsoft Access database (.mdb) file size | 2 gigabytes. However, because your database can include linked tables in other files, its total size is limited only by available storage capacity.
Number of objects in a database | 32,768
Modules (including forms and reports with the HasModule property set to True) | 1,000
Number of characters in an object name | 64
Number of characters in a password | 14
Number of characters in a user name or group name | 20
Number of concurrent users | 255


Field data type conversion results

The following is a list of the results and considerations of common data type conversions when the table contains data.

From | To | Results | Considerations
All data types | AutoNumber | Prohibited by Microsoft Access | None.
Text | Number, Currency, Date/Time, Yes/No | Converts text to appropriate values | Make sure values fit in the new data type; inappropriate values are deleted.
Memo | Text | Simple conversion | Data longer than the FieldSize setting is truncated.
Number | Text | Converts values to text | Numbers adopt General Number format.
Number | Currency | Converts numbers to currency | Make sure values fit in the new data type; inappropriate values are deleted.
Date/Time | Text | Converts values to text | Dates or times adopt General Date format.
Currency | Text | Converts values to text | Text doesn't include currency symbols, such as $.
Currency | Number | Simple conversion | Make sure values fit in the new data type; inappropriate values are deleted.
AutoNumber | Text | Converts values to text | Values may be truncated depending on FieldSize setting.
AutoNumber | Number | Simple conversion | Values may be truncated depending on FieldSize setting.
Yes/No | Text | Converts values to text | None.


 About converting a previous-version Access database to Access 2000

About converting a previous-version Access database to Access 2000

This topic provides reference information about:

When to convert an Access database

Sharing an Access database with users of different versions of Microsoft Access

Creating and modifying objects

Changing database permissions

New toolbars and menu bars

Code compatibility

DoMenuItem replaced with RunCommand

When to convert an Access database

In most cases, you will want to convert a previous-version Microsoft Access database to Microsoft Access 2000. You can enable a previous-version Access database in Microsoft Access 2000 without converting it; however, you can't change the design of objects or take advantage of many of the new features in Microsoft Access 2000 until you convert the previous-version database. Once you've converted an Access database to Microsoft Access 2000, you can't open it in a previous version. You can't convert an Access 2000 database back to Access version 2.0 or 95; however, you can convert an Access 2000 database back to Access 97. For more information on enabling an Access database, click [image] .

Return to top

Sharing an Access database with users of different versions of Microsoft Access

If your Access database is a multiuser (shared) database, and all users can't upgrade to Microsoft Access 2000 at the same time, you can upgrade parts of your database to support new features, while maintaining the original Access database unaltered. For information on sharing a database with users of different versions of Microsoft Access, click [image] .

Return to top

Creating and modifying objects

When you're using Microsoft Access 2000 to work with an enabled previous-version Access database, you can use objects in the database to view and modify data. However, you can't save changes to database objects. To modify the design of an object or create a new object in the Access database, you must either open it in the previous version or convert the database to Microsoft Access 2000.

Return to top

Changing database permissions

In order to change or add permissions in a previous-version Access database, you must either open it in the previous version or convert the database to Microsoft Access 2000. To take advantage of all of the security features in Microsoft Access 2000, and to maintain the full security of your original database, you should recreate your user and group accounts and passwords using a Microsoft Access 2000 workgroup information file. Learn more about converting a secured Access database.

You can no longer protect your modules with user-level security; however, you can protect your modules by protecting the Visual Basic for Applications (VBA) code with a password.

Return to top

New toolbars and menu bars

Microsoft Access 97 or later supports a new style of toolbars and menu bars. When you convert a Microsoft Access version 2.0 or 95 database to Microsoft Access 2000, any custom toolbars, as well as built-in toolbars, are automatically converted to the new style of toolbar. Custom menu bars, created with the Microsoft Access 95 Menu Builder or with macros, are interpreted as the new-style menu bars when you open a converted Access database. However, they are not automatically converted, and therefore they can't be edited using the Customize dialog box. You can use the Create Menu From Macro and Create Shortcut Menu From Macro subcommands on the Macro command (Tools menu) to create the new style of menu bar from macros that use AddMenu actions. This enables you to use the Customize dialog box to edit them. Learn more about converting toolbars and menu bars.

Return to top

Code Compatibility

Microsoft Access 2000 does not support the DAO 2.5/3.x compatibility library. If you attempt to convert an Access database in which the code contains older versions of DAO objects, methods, and properties that depend on the DAO 2.5/3.x compatibility library, you receive a message that there were compilation errors during the conversion of the database. Before you convert an Access database, update the code so that it does not depend on the DAO 2.5/3.x compatibility library. If you still receive a message that there were compilation errors during conversion, open the converted database in Microsoft Access 2000, remove the reference to the missing DAO 2.5/3.x compatibility library, and then set a reference to the Microsoft DAO 3.6 Object Library.

If your Access database uses add-ins or library databases created in a previous version of Microsoft Access, you must convert them as well. For information about changes to methods, actions, properties, syntax, and other language elements, and information about code compatibility and conversion issues, click [image] .

Return to top

DoMenuItem replaced with RunCommand

The DoMenuItem action is replaced in Microsoft Access 2000 with the RunCommand action; DoMenuItem is still supported for backwards compatibility. When you convert a database, the DoMenuItem action is automatically converted to the RunCommand action.

For more information on the compatibility of Visual Basic for Applications (VBA) between Microsoft Access 95 and 97 and Microsoft Access 2000, click [image] .

Return to top


Example of a self-join

To display the managers' names in the ReportsTo field instead of the managers' IDs, follow these steps.

  1. In query Design view, add the Employees table to the query twice. How to rename the second table in the query.

  2. Create the join by dragging the ReportsTo field in the first table's field list to the EmployeeID field in the second table's field list.

  3. Add the LastName, FirstName, and Title fields from the first field list to the design grid.

  4. Add the LastName field from the second field list to the design grid. To display the field name as "Manager" instead of "LastName," set the Caption property in this field's property sheet. For information on changing the Caption property of a field, click [image] .


Examples of input masks

An input mask is used in fields (in tables and queries) and in text boxes and combo boxes (in forms) to format data and provide some control over what values can be entered. An input mask consists of literal characters (such as spaces, dots, dashes, and parentheses) that separate blanks to fill in. The InputMask property setting consists of literal characters along with special characters that determine the kind of value that can be entered into the blank in that position. Input masks are primarily used in Text and Date/Time fields, but can also be used in Number or Currency fields.

This topic provides reference information about:

Examples of input masks

Defining input masks

Valid input mask characters

Examples of input masks

The following table shows some useful input mask definitions and examples of values you can enter into them. Refer to the table at the end of this topic for details on the codes used to create input mask definitions.

Input mask definition | Examples of values
(000) 000-0000 | (206) 555-0248
(999) 999-9999! | (206) 555-0248
 | ( ) 555-0248
(000) AAA-AAAA | (206) 555-TELE
#999 | -20
 | 2000
>L????L?000L0 | GREENGR339M3
 | MAY R 452B7
>L0L 0L0 | T2F 8M4
00000-9999 | 98115-
 | 98115-3007
>L<?????????????? | Maria
 | Pierre
ISBN 0-&&&&&&&&&-0 | ISBN 1-55615-507-7
 | ISBN 0-13-964262-5
>LL00000-0000 | DB51392-0493

Return to top

Defining input masks

The input mask definition can contain up to three sections separated by semicolons; for example, (999) 000-0000!;0;" ".

Section | Meaning
First | The input mask itself.
Second | Determines whether to store the literal display characters. 0 = store literal characters with the value entered 1 or leave blank = store only characters entered in blanks
Third | Character that is displayed for blanks in the input mask. You can use any character; type " " (double quotation marks, space, double quotation marks) to display a space. If you leave this section blank, the underscore ( _ ) is used.

Return to top

Valid input mask characters

Microsoft Access interprets characters in the first part of the InputMask property definition as shown in the following table. To define a literal character, enter any character other than those shown in the table, including spaces and symbols. To define one of the following characters as a literal character, precede that character with a \.

Character | Description
0 | Digit (0 through 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; blank positions converted to spaces, plus and minus signs allowed).
L | Letter (A through Z, entry required).
? | Letter (A through 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 thousands, date, and time separators. (The actual character used depends on the regional settings specified by double-clicking Regional Settings in the Windows Control Panel.)
< | Causes all characters that follow to be converted to lowercase.
> | Causes all characters that follow 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 a literal character. Used to display any of the characters listed in this table as literal characters (for example, \A is displayed as just A).
Password | Setting the InputMask property to the word Password creates a password entry text box. Any character typed in the text box is stored as the character but is displayed as an asterisk (*).

Return to top

More information

Create an input mask


 Examples of default values in fields

Examples of default values in fields

Field | Expression | Default field value
Quantity | 1 | 1
Region | "MT" | MT
Region | "New York, N.Y." | New York, N.Y (note that you must enclose the value in quotes if it includes punctuation)
Fax | " " | A zero-length string to indicate that by default this field should be empty
Order Date | Date( ) | Today's date


 Examples of hyperlink addresses

Examples of hyperlink addresses

The following table shows examples of hyperlink addresses. Note that URLs use slash marks and UNC paths use backslashes.

Hyperlink address | Description
Microsoft Corporation#http://www.microsoft.com# | The Microsoft home page on the Web. Displayed as "Microsoft Corporation."
#http://www.microsoft.com# | The Microsoft home page on the Web.
#http://www.microsoft.com#sample# | The Name tag called "sample" in the .html document for the Microsoft home page.
#\\northwind\public\products.doc##List of discounted products | A Microsoft Word file called Products.doc in the public shared directory on the Northwind server. The ScreenTip is "List of discounted products."
Resume#c:\windows\personal \resume.doc# | A Word file called Resume.doc located in the \Windows\Personal folder. Displayed as "Resume."
#c:\windows\personal\resume.doc# | The Resume.doc file that is located in the \Windows\Personal folder. The path name will be displayed, because there’s no display text.
#c:\windows\personal\resume.doc#Qualifications | The bookmark called "Qualifications" in the Resume.doc file.
#c:\windows\personal\ northwind.mdb#Form Suppliers | The Suppliers form in the Northwind database, located in the \Windows\Personal folder.
Suppliers##Form Suppliers#Click to view and edit supplier information | The Suppliers form in the current database. Displayed as "Suppliers," with the ScreenTip "Click to view and edit supplier information."
#c:\windows\personal\1996 Sales.ppt#13 | Slide 13 in the 1996 Sales PowerPoint presentation in the \Windows\Personal folder.
#c:\windows\personal\budget. xls#Sheet1!A2 | Cell A2 in Sheet1 of the budget.xls Excel file, located in the \Windows\Personal folder.

To make it easier to enter a hyperlink address, Microsoft Access allows you to omit certain parts of an address. For example:

  • If you type http://example.microsoft.com, Microsoft Access recognizes the "http:" protocol and translates the address to #http://example.microsoft.com#. (You don't have to enter the number signs (#) yourself.)

  • If you want to point to a Microsoft Access object in the current database, you can specify just the object name that you want to link to — you don't have to specify a UNC path. If there are multiple objects with the same name, Microsoft Access uses the following order to determine which one to reference: forms, reports, queries, tables, data access pages, macros, modules, views, schemas, stored procedures, SQL linked tables, linked tables, and triggers. If, for example, there is both an Orders form and an Orders table, Microsoft Access assumes that the reference is to the Orders form. You can specify a particular object type by entering object type object name. So to refer to the Orders table instead of the Orders form, enter Table Orders as the subaddress. For object types with multiple words, omit the spaces between words; for example, enter dataaccesspage Orders.

  • If the text that you enter doesn't include a number sign (#), a protocol (such as "http:"), or a reference to an object in the current database, Microsoft Access assumes the text entered is display text and appends "http://" to the same text for the address. For example, if you type example.microsoft.com, Microsoft Access translates the address as example.microsoft.com#http://example.microsoft.com#.


 Examples of referring to values on data access pages

Examples of referring to values on data access pages

The following table lists examples of expressions that you can use in calculated controls on data access pages.

If you use this expression | The page displays
=Document.All("MSODSC").CurrentSection.ChildSection.HTMLContainer.Children("ProductID") | The value in the ProductID control in the section that is one group level below the current section.
=Document.All("MSODSC").CurrentSection.ParentSection.HTMLContainer.Children("CustomerID") | The value in the CustomerID control in the section that is one group level above the current section.
=Document.All("MSODSC").CurrentSection.Parent.Parent.HTMLContainer.Children("Country") | The value in the Country control in the section that is two group levels above the current section.
=Document.All("MySpreadsheet").Range("A1") | The values in the range A1 in the spreadsheet control.

The following table lists examples of referring to controls on a page from a spreadsheet control.

If you use this expression | The page displays
=document.Quantity.value*document.UnitPrice.value | The result of multiplying the value in the Quantity control by the value in the UnitPrice control.
=$C$1*document.UnitPrice.value | The result of multiplying the value in the UnitPrice control by a percentage rate that is stored in spreadsheet cell C1.


Examples of field validation rules in tables and controls on forms

ValidationRule setting | ValidationText setting
<>0 | Please enter a nonzero value.
0 Or >100 | Value must be either 0 or over 100.
Like "K???" | Value must be four characters beginning with the letter K.
<#1/1/96# | Enter a date before 1996.
>=#1/1/97# And <#1/1/98# | Date must be in 1997.
StrComp(UCase([LastName]), [LastName],0) = 0 | Data in the LastName field must be entered in uppercase letters.

Read about validation rules.

Note For an example of setting form-level validation with a macro or event procedure, click [image] .


Form and report specifications

Attribute | Maximum
Number of characters in a label | 2,048
Number of characters in a text box | 65,535
Form or report width | 22 in. (55.87 cm)
Section height | 22 in. (55.87 cm)
Height of all sections plus section headers (in Design view) | 200 in. (508 cm)
Number of levels of nested forms or reports | 3
Number of fields or expressions you can sort or group on in a report | 10
Number of headers and footers in a report | 1 report header/footer; 1 page header/footer; 10 group headers/footers
Number of printed pages in a report | 65,536
Number of controls and sections you can add over the lifetime of the form or report | 754


 Use global Microsoft Access shortcut keys

Use global Microsoft Access shortcut keys

Press | Displaying Help
F1 | To display the Office Assistant and Microsoft Access Help; context-sensitive Help about the selected property, control, macro action, or Visual Basic keyword; or alerts with a Help button
SHIFT+F1 | To display ScreenTips; after pressing SHIFT+F1, move the pointer to the menu command, toolbar button, or screen region, and then click the mouse
SHIFT+F1 | To display ScreenTips in a dialog box, after selecting the option by using the keyboard

Press | Opening databases
CTRL+N | To open a new database
CTRL+O | To open an existing database

Press | Printing and saving
CTRL+P | To print the current or selected object
CTRL+S or SHIFT+F12 or ALT+SHIFT+F2 | To save a database object
F12 or ALT+F2 | To open the Save As dialog box

Press | Using a combo box or list box
F4 or ALT+DOWN ARROW | To open a combo box
F9 | To refresh the contents of a Lookup field list box or combo box
DOWN ARROW | To move down one line
PAGE DOWN | To move down one page
UP ARROW | To move up one line
PAGE UP | To move up one page
TAB | To exit the combo box or list box

Press | Finding and replacing text or data
CTRL+F | To open the Find tab in the Find and Replace dialog box (Datasheet view and Form view only)
CTRL+H | To open the Replace tab in the Find and Replace dialog box (Datasheet view and Form view only)
SHIFT+F4 | To find the next occurrence of the text specified in the Find and Replace dialog box when the dialog box is closed (Datasheet view and Form view only)

Press | Working in Design view
F2 | To switch between Edit mode (with insertion point displayed) and Navigation mode
F5 | To switch to Form view from form Design view
F6 | To switch between the upper and lower portions of a window (Design view of tables, macros, and queries and the Advanced Filter/Sort window only)

Press | Editing controls in form and report Design view
SHIFT+ENTER | To add a control to a section How to place a text box or another control on a form or report by using the keyboard How to copy a text box or another control on a form or report by using the keyboard
CTRL+C | To copy the selected control to the Clipboard
CTRL+X | To cut the selected control and copy it to the Clipboard
CTRL+V | To paste the contents of the Clipboard in the upper-left corner of the selected section
CTRL+RIGHT ARROW | To move the selected control to the right
CTRL+LEFT ARROW | To move the selected control to the left
CTRL+UP ARROW | To move the selected control up
CTRL+DOWN ARROW | To move the selected control down
SHIFT+DOWN ARROW | To increase the height of the selected control
SHIFT+RIGHT ARROW | To increase the width of the selected control
SHIFT+UP ARROW | To reduce the height of the selected control
SHIFT+LEFT ARROW | To reduce the width of the selected control

Press | Window operations
F11 or ALT+F1 | To bring the Database window to the front
CTRL+F6 | To cycle between open windows
ENTER | To restore the selected minimized window when all windows are minimized
CTRL+F8 | To turn on Resize mode for the active window when it’s not maximized; press the arrow keys to resize the window
ALT+SPACEBAR | To display the Control menu
SHIFT+F10 | To display the shortcut menu
CTRL+W or CTRL+F4 | To close the active window
ALT+F11 | To switch between the Visual Basic Editor and the previous active window
ALT+SHIFT+F11 | To switch between the Microsoft Script Editor and the previous active window

Press | Miscellaneous
F2 | To display the complete hyperlink address for a selected hyperlink
F7 | To check spelling
SHIFT+F2 | To open the Zoom box to conveniently enter expressions and other text in small input areas
ALT+ENTER | To display a property sheet in Design view
ALT+F4 | To quit Microsoft Access, close a dialog box, or close a property sheet
CTRL+F2 | To invoke a Builder
CTRL+F11 | To toggle between a custom menu bar and a built-in menu bar


How do I get my built-in toolbars and menus back if they've disappeared?

If all the built-in toolbars and some of the built-in menus have disappeared from all views, you may need to change the settings in the Startup dialog box or temporarily bypass its settings.

To change the settings

Click Startup on the Tools menu, and then click Allow Built-in Toolbars to display all the built-in toolbars and click Allow Full Menus to display all the built-in menus. Close the database or Microsoft Access project, and then reopen it.

If you're still missing some menus, they may have been removed from the menu bar. You can re-add a specific built-in menu to the menu bar. For more information, click [image] .

To temporarily bypass the settings in the Startup dialog box

You can temporarily bypass all the settings specified in the Startup dialog box instead of resetting the options. Hold down the Bypass key (the SHIFT key) while you open the database.


Hyperlink subaddress syntax

To go to a location
in this type of file
Enter
Microsoft Access The object type and object name. For example, enter Table Customers to go to the Customers table.

Notes If you omit the object type, and there are multiple objects with the same name, Microsoft Access uses the following order to determine which one to reference: forms, reports, queries, tables, data access pages, macros, modules, views, schemas, stored procedures, SQL linked tables, linked tables, and triggers. For example, if there is both an Orders form and an Orders table, Access assumes the reference is to the Orders form. To specify the Orders table, you must enter Table Orders.

On a non-English system, Access recognizes the object type in English and in the local language; however, hyperlinks created by using the Insert Hyperlink dialog box all have the English-language string for an object type.
Microsoft Excel | A defined name or a sheet!range. For example, enter sheet1!A2 to go to the A2 cell in sheet 1.
Microsoft PowerPoint | A slide number
Microsoft Word | A bookmark name
HTML document | A bookmark name (defined by using the NAME attribute of the <A> tag)


Macro specifications

Attribute | Maximum
Number of actions in a macro | 999
Number of characters in a condition | 255
Number of characters in a comment | 255
Number of characters in an action argument | 255


 Tips for optimizing the performance of Microsoft Access and your system

Tips for optimizing the performance of Microsoft Access and your system

The following guidelines can help you optimize the performance of Microsoft Access on your computer:

  • If you're using databases that other users don't need to share, install Microsoft Access and all your databases on your hard disk drive rather than on a network server.

  • If you are the only person using a database, open the database for exclusive use; in the Open dialog box, click the arrow next to Open button, and then click Open Exclusive.

  • Make more memory available by closing applications that you aren't using.

  • Increase RAM on your computer. If you are running Microsoft Windows 95 or later, 24 MB of memory is recommended — 16 MB plus an additional 8 MB of memory for Microsoft Access. If you are running Windows NT 4.0 or later, 40 MB of memory is recommended — 32 MB of memory plus an additional 8 MB of memory for Microsoft Access.

  • Don't use any of your RAM for a RAM disk.

  • Periodically delete unnecessary files and empty your Recycle Bin, compact your databases, and then defragment your hard disk with the Microsoft Windows Disk Defragmenter. To run the Disk Defragmenter, click the Windows Start button, point to Programs, point to Accessories, point to System Tools, and then click Disk Defragmenter.

  • In most cases, the default virtual memory setting used by Windows should perform optimally. However, in some situations, adjusting virtual memory parameters can improve performance. If you've already tried deleting unnecessary files and you still have a performance problem, try changing the default virtual memory setting in the following cases:
    • You don't have much disk space available on the drive that is currently being used for virtual memory, and another local drive with space is available.

    • Another local drive is available that is faster than the current drive (unless that disk is heavily used).

    In these cases, you might get better performance by specifying a different drive for virtual memory.

    You also might get better performance by specifying that the disk space available for virtual memory be at least 25 MB minus available RAM. For example, if your computer has 12 MB of RAM, you should specify at least 13 MB of virtual memory. You may want to specify more if you are running several large applications.

    To change Windows virtual memory parameters, in Windows Control Panel, double-click the System icon, click the Performance tab, click Virtual Memory, and then click Let Me Specify My Own Virtual Memory Settings. Then specify a different hard disk, or enter a value in the Minimum box that is at least 25 minus your available RAM.

  • If you have a wallpaper (full-screen background) bitmap on your Windows desktop, replace it with a solid color or pattern bitmap, or no bitmap at all.

  • If you use a screen saver, use a blank screen saver or consider not using one at all.

  • Eliminate disk compression software, or consider moving your databases to an uncompressed drive.

For more information on optimizing the performance of your database, see Chapter 10, "Optimizing Your Application," in Building Applications with Forms and Reports.


 Tips for optimizing external SQL database performance

Tips for optimizing external SQL database performance

If the data in your front-end/back-end application consists only of Microsoft SQL Server tables, you can use either a Microsoft Access project or a Microsoft Access database as the front end of your application. However, if you want the data in your front-end/back-end application to consist of both Microsoft Access tables and Microsoft SQL server tables, you must use an Access database as the front end.

If you're connecting to an external SQL database table, you can achieve the best performance results by linking to the SQL tables instead of opening the tables directly. You can open external SQL tables directly only by using Visual Basic code. Linked tables are considerably faster, more powerful, and more efficient than directly opened tables.

Additional performance tips

  • Retrieve only the data you need. Design your queries to limit the number of records that you retrieve, and select only the fields you need, so that Microsoft Access can transfer as little data as possible over the network.

  • Don't use updatable result sets (dynasets) if you're not retrieving many records, are not updating the data, and don't need to see changes made by other users. To prevent result sets from being updated in a form, set the form's RecordSetType property to Snapshot. Snapshots are faster to open and scroll through than dynasets.

  • If you need to retrieve a large number of records, a dynaset is faster and more efficient than a snapshot. For example, moving to the end of a snapshot requires the entire result set to be downloaded to the local computer, but with a dynaset only the last screenful of data is downloaded to the local computer. In addition, the fastest way to add new records to a table, form, or query is to click Data Entry on the Records menu. (Data Entry isn't available if the RecordsetType property is set to Snapshot.)

  • Use cache memory. If you will reuse the most recent data from the server while the application is running, it's faster to retrieve a single large chunk of data (many rows) and store them in cache than to retrieve many individual rows. Microsoft Access forms and datasheets automatically use a cache. If you are retrieving data by using a Recordset object created in Microsoft Visual Basic, you can use the CacheSize property to specify how many records to retrieve at one time into local memory.

  • Avoid using queries that cause processing to be done on a local client computer. When accessing external data, the Jet database engine processes data locally only when the operation can't be performed by the external database server. Query operations performed locally (as defined by the SQL commands used to implement them) include:
    • JOIN operations between tables from different remote data sources. (Note that if the join involves a local table or query with few records and a remote table with many more records, and the remote table's join field is indexed, Access returns only the records that match the local table or query, thus greatly improving query performance.)

    • JOIN operations based on a query with the DISTINCT predicate or a GROUP BY clause.

    • Outer joins containing syntax not supported by the server.

    • DISTINCT predicates containing operations that can't be processed remotely.

    • The LIKE operator used with Text or Memo fields (may not be supported by some servers).

    • Multiple-level GROUP BY arguments and totals, such as those used in reports with multiple grouping levels.

    • GROUP BY arguments based on a query with a DISTINCT predicate or a GROUP BY clause.

    • Crosstab queries that have more than one aggregate, that have field, row, or column headings that contain aggregates, or that have a user-defined ORDER BY clause.

    • TOP n or TOP n PERCENT predicates.

    • User-defined functions, or operators or functions that aren't supported by the server.

    • Complex combinations of INNER JOIN, LEFT JOIN, or RIGHT JOIN operations in nested queries.
  • For bulk update queries against ODBC data sources, optimize performance on the server by setting the FailOnError property to Yes. For more information, click [image] .


 About aggregate functions and other options in the query design grid's Total row

About aggregate functions and other options in the query design grid's Total row

Nine of the 12 options in the query design grid's Total row are aggregate functions. All but the First and Last functions are explained in the following table. For special considerations when using the First and Last functions, click [image] The other three options in the list are explained in the second table.

Note The aggregate functions won't include records containing blank (Null) values in their calculations. For example, the Count function returns a count of all the records without Null values. There is a way to count Null values, and you can convert Null values to zeroes so they are included in a calculation. For more information, click [image] .

Select | To find the | Use with these field data types
Sum | Total of the values in a field. | Number, Date/Time, Currency, and AutoNumber
Avg | Average of the values in a field. | Number, Date/Time, Currency, and AutoNumber
Min | Lowest value in a field. | Text, Number, Date/Time, Currency, and AutoNumber
Max | Highest value in a field. | Text, Number, Date/Time, Currency, and AutoNumber
Count | Number of values in a field, not counting Null (blank) values. | Text, Memo, Number, Date/Time, Currency, AutoNumber, Yes/No, and OLE Object
StDev | Standard deviation of the values in a field. | Number, Date/Time, Currency, and AutoNumber
Var | Variance of the values in a field. | Number, Date/Time, Currency, and AutoNumber

Select | To
Group By | Define the groups you want to perform the calculations for. For example, to show total sales by category, select Group By for the CategoryName field.
Expression | Create a calculated field that includes an aggregate function in its expression. Usually, you create a calculated field when you want to use multiple functions in an expression.
Where | Specify criteria for a field you aren't using to define groupings. If you select this option for a field, Microsoft Access will hide the field in the query results by clearing the Show check box.


 Microsoft Access project general specifications

Microsoft Access project general specifications

Attribute | Maximum
Number of objects in a Microsoft Access project (.adp) | 32,768
Modules (including forms and reports with the HasModule property set to True) | 1,000
Number of characters in an object name | 64


Microsoft Access database query specifications

Attribute | Maximum
Number of enforced relationships | 32 per table minus the number of indexes that are on the table for fields or combinations of fields that are not involved in relationships
Number of tables in a query | 32
Number of fields in a recordset | 255
Recordset size | 1 gigabyte
Sort limit | 255 characters in one or more fields
Number of levels of nested queries | 50
Number of characters in a cell in the query design grid | 1,024
Number of characters for a parameter in a parameter query | 255
Number of ANDs in a WHERE or HAVING clause | 40
Number of characters in an SQL statement | approximately 64,000


 RepaintObject, ShowAllRecords, Requery, and Refresh Action/Method Comparison

RepaintObject, ShowAllRecords, Requery, and Refresh Action/Method Comparison

The following table provides a brief comparison of the RepaintObject action, RepaintObject method, Repaint method, ShowAllRecords action, ShowAllRecords method, Requery action, DoCmd.Requery method, Refresh method, and Requery method.

Action or Method | Description
RepaintObject action
DoCmd.RepaintObject Repaint method 		Use the RepaintObject action, RepaintObject method or Repaint method to repaint controls in the specified object. They don't requery the database or display new records.
ShowAllRecords action
ShowAllRecords method 		Use the ShowAllRecords action to requery and display the most recent records and remove any applied filters, which the Requery action doesn't do.
Requery action
DoCmd.Requery method 		Use the Requery action or method to requery the source of the object or one of its controls. The Requery action or method does one of the following:

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

Displays any new or changed records, and removes any deleted records from the table on which the control or object is based.
Refresh method | Use the Refresh method to immediately update 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. 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.
Requery method
  • Use the Requery method to update 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.

    If you want to requery a control that isn't on the active object, you must use this method, not the Requery action or its corresponding DoCmd.Requery method.


Ways to select values for a filter to affect what records are returned

You can select all or part of a value in a field. How you select the value determines what records the filter returns.

Selecting | Finds records in which | Example
The entire contents of a field (or placing the insertion point in a field without selecting anything) | The entire contents of that field matches the selection. | You select the value "Berlin" in the City field. The filter returns all records with Berlin as the city.
Part of a value starting with the first character in a field | The value in that field starts with the same characters you selected. | In the CompanyName field containing the value "France restauration," you select only "Fran." The filter returns all records that have a company name starting with "Fran," such as Franchi S.p.A. and Frankenversand.
Part of a value starting after the first character in a field | All or any part of the value in that field contains the same characters you selected. | In the CompanyName field containing the value "Old World Delicatessen," you select the letters "Del." The filter returns all records that have "del" anywhere in the CompanyName field, such as Ernst Handel, Galería del gastrónomo, and Que Delícia.


Microsoft SQL Server database technical specifications

Microsoft SQL Server technical specifications are documented in the SQL Server documentation. These specifications include the maximum sizes and values of SQL Server objects, minimum and maximum values of configuration options, and memory usage for various SQL Server objects. Learn about SQL Server documentation.


Microsoft Access database table specifications

Attribute | Maximum
Number of characters in a table name | 64
Number of characters in a field name | 64
Number of fields in a table | 255
Number of open tables | 2048. The actual number may be less because of tables open internally by Microsoft Access.
Table size | 1 gigabyte
Number of characters in a Text field | 255
Number of characters in a Memo field | 65,535 when entering data through the user interface; 1 gigabyte when entering data programmatically.
Size of an OLE Object field | 1 gigabyte
Number of indexes in a table | 32
Number of fields in an index | 10
Number of characters in a validation message | 255
Number of characters in a validation rule | 2,048
Number of characters in a table or field description | 255
Number of characters in a record (excluding Memo and OLE Object fields) | 2,000
Number of characters in a field property setting | 255


Types of queries you can create in Microsoft Access

What type of query do you want to learn more about?

Select queries

Parameter queries

Crosstab queries

Action queries (make-table, delete, update, append queries)

SQL queries (union, pass-through, data-definition, subquery)

Return to Create a query


 Users can't open my interactive data access page.

Users can't open my interactive data access page.

To use Microsoft Access interactive data on the data access page, your users must have Microsoft Office 2000 Professional, Premium, or Standard Edition installed, or a Microsoft Office 2000 site license and the Web Components installed.

To ensure that users on your intranet have the Web Components installed, you can specify that the Web components download to the user's machine when the user opens your data access page.

  1. Open the data access page in Design view.

  2. On the Tools menu, click Options, and then click the General tab.

  3. Click Web Options, and then click the Files tab.

  4. Select the Download Office Web Components check box.

  5. In the Location box, type the path for the file server, such as file:\\my server\my folder.

Note Users must have access to the file server. The Web Components cannot be downloaded through firewalls.


 Use shortcut keys in Page view

Use shortcut keys in Page view

Note To use the following keys, press the TAB key repeatedly until the expand indicator or record navigation toolbar has focus. If a PivotTable list or spreadsheet control currently has focus, press CTRL+TAB.

Press | To
SPACE or ENTER | Expand or collapse a group of records corresponding to the expand indicator in a grouped data access page.
LEFT ARROW or RIGHT ARROW | Select a button on the record navigation toolbar.
SPACE or ENTER | Activate the selected button on the record navigation toolbar.


 Use shortcut keys for the Open, File New Database and Export dialog boxes

Use shortcut keys for the Open, File New Database and Export dialog boxes

Press | To
ALT+1 | Go to the previous folder ( [image] )
ALT+2 | Open the folder up one level from the open folder (Up One Level button [image] )
ALT+3 | Close the dialog box, and open your World Wide Web search page (Search the Web button [image] )
ALT+4 | Delete the selected folder or file (Delete button [image] )
ALT+5 | Create a new subfolder in the open folder (Create New Folder button [image] )
ALT+6 | Switch between List, Details, Properties, and Preview views
ALT+7 | Show the Tools menu (Tools button)


Which wizards are installed

This topic provides reference information about:

Wizards installed when you select the "Typical Wizards" component in Setup

Wizards installed when you select the "Advanced Wizards" component in Setup

Wizards installed when you select the "Typical Wizards" component in Setup

AutoDialer | Link HTML
AutoForm | Link Spreadsheet
AutoFormat | Link Text
AutoPage | List Box
AutoReport | Lookup
Combo Box | Microsoft Word Mail Merge
Command Button | Page
Crosstab Query | Page Combo Box
Database | Page Command Button
Export | Page List Box
Field Builder | Picture Builder
Form | PivotTable
Import Exchange/Outlook | Print Relationships
Import HTML | Report
Import Spreadsheet | Simple Query
Import Text | Switchboard Manager
Label | Table
Link Exchange/Outlook |

Return to top

Wizards installed when you select the "Additional Wizards" component in Setup

Add-in Manager | ODBC Connect String Builder
Database Splitter | Option Group
Documenter | Partial Replica
Find Duplicates Query | Performance Analyzer
Find Unmatched Query | Security
Graph (Chart) | Subform/Subreport
Input Mask | Subform/Subreport Field Linker
Linked Table Manager | Table Analyzer
Macro To Module Converter | Upsizing
Microsoft SQL Server Database |

Return to top

Note The following wizards are always installed: Color Builder, Expression Builder, Query Builder.


Work with euro currency symbols

Microsoft Access 2000 provides full support for displaying, entering, and printing the euro currency symbol Euro currency symbol. If you use Microsoft Windows 95 or Microsoft Windows NT Workstation 4.0, you might need to add Microsoft euro currency support to your system.

Typing the euro currency symbol To enter the euro currency symbol [image], use the following keys:

Press | On
ALT+0128 (numeric pad) | U.S. keyboards
ALTGR+E | European keyboards
ALTGR+epsilon | Greek keyboards
ALTGR+5 | Greek Latin and U.S.-International keyboards
ALT+0136 (numeric pad) | Cyrillic keyboards

Displaying the euro currency symbol The fonts you need to display the euro currency symbol are installed when you install Access. Fonts that can display the euro currency symbol are as follows:

Operating system | Fonts
Microsoft Windows 95, Windows 98 | Arial, Courier, Tahoma, Times
Microsoft Windows NT or Windows 2000 | Arial, Courier, Lucida Console, MS Sans Serif, Tahoma, Times

Printing the euro currency symbol If your printer does not have the euro currency symbol in any of its resident fonts, a box will be printed instead of the euro currency symbol. Contact your printer vendor to find out how to get updated printer fonts that include the euro currency symbol.


 ALL, DISTINCT, DISTINCTROW, TOP Predicates

ALL, DISTINCT, DISTINCTROW, TOP Predicates

In Microsoft Access, the use of the DISTINCT reserved word is equivalent to setting the UniqueValues property to Yes on the query's property sheet in query Design view.

The use of the DISTINCTROW reserved word is equivalent to setting the UniqueRecords property to Yes (the default value) in the query's property sheet in query Design view.

The use of the TOP reserved word is equivalent to setting the TopValues property on the query's property sheet in query Design view, or entering a value in the Top Values box Top value, list box on the Query Design toolbar.

The use of the PERCENT reserved word is equivalent to using the percent sign (%) with the TopValues property on the query's property sheet, or in the Top Values box.


ALL, DISTINCT, DISTINCTROW, TOP Predicates Example (MDB)

To try the following examples in Microsoft Access, create two new tables like those shown below. Create a new query in the Northwind sample database and close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

Clients Table

FirstName | ClientID
Bob | 1
Adam | 2
Beverly | 3
Bob | 4

Invoices Table

ClientID | InvoiceID
1 | 1
1 | 2
2 | 3
2 | 4
2 | 5
4 | 6
4 | 7

The following example returns all of the records returned by an inner join on the two tables. The result set is updatable.

SELECT ALL FirstName FROM Clients INNER JOIN Invoices
ON Clients.ClientID = Invoices.ClientID;
Result | Updatable
Bob Bob Adam Adam Adam Bob Bob | Yes

The next example selects only records with unique values returned by an inner join on the two tables. The result set isn't updatable.

SELECT DISTINCT FirstName FROM Clients
    INNER JOIN Invoices
    ON Clients.ClientID = Invoices.ClientID;
Result | Updatable
Bob Adam | No

The following example selects only unique records returned by an inner join on the two tables. The result set is updatable.

SELECT DISTINCTROW FirstName FROM Clients
    INNER JOIN Invoices
    ON Clients.ClientID = Invoices.ClientID;
Result | Updatable
Bob Adam Bob | Yes

The next example selects the first five records returned by an inner join on the two tables. The result set is updatable.

SELECT TOP 5 FirstName FROM Clients
    INNER JOIN Invoices
    ON Clients.ClientID = Invoices.ClientID
    ORDER BY Invoices.InvoiceID;
Result | Updatable
Bob Bob Adam Adam Adam | Yes


ALTER TABLE Statement Example (MDB)

To try the following examples in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

Warning These examples makes changes to the Northwind sample database. Before beginning, you may wish to make a backup copy of the sample database.

The following example adds a Salary field with a data type of Currency to the Employees table:

ALTER TABLE Employees ADD COLUMN Salary CURRENCY;

    The next example removes the Salary field from the Employees table:

    ALTER TABLE Employees DROP COLUMN Salary;

      Once you've run the next two queries, click Relationships on the Tools menu to view the changed relationships.

      The following example removes the existing foreign key from the Orders table:

      ALTER TABLE Orders DROP CONSTRAINT EmployeesOrders;

        The next example adds the foreign key back to the Orders table:

        ALTER TABLE Orders ADD CONSTRAINT EmployeesOrders _
    FOREIGN KEY (EmployeeID) REFERENCES Employees _
    (EmployeeID);


 Avg Function

Avg Function

In Microsoft Access, you can use the Avg function in the query design grid, in an SQL statement in SQL view of the Query window, or in an SQL statement within Visual Basic code. You can also use the Avg function in a calculated control on a form or report.

The Avg function is most useful in totals queries and crosstab queries. It functions the same way whether you create the query in the query design grid or as an SQL statement in SQL view.

In the query design grid, you can create a new totals query by clicking Totals [image] on the Query Design toolbar. The Total row is then inserted in the grid. You can set the Total cell beneath a field to the aggregate function to perform on the data in that field.

For example, suppose you have an Orders table that has both a Freight field and a ShipCity field. You can create a query that displays the average freight cost for orders sent to each city to which your company ships. Create a new totals query, and drag the ShipCity field to the query design grid. The Total cell beneath the ShipCity field should be set to Group By. Drag the Freight field to the query design grid, and set the Total cell beneath it to Avg. When you run the query, it will display the average freight cost by city.

You can view the SQL statement for this query by switching to SQL view. In this example, Microsoft Access creates the following SQL statement:

SELECT ShipCity, Avg(Freight) AS AvgOfFreight
FROM Orders GROUP BY ShipCity;

You can also use an SQL statement within Visual Basic Code. For example, the following procedure creates a dynaset-type Recordset object from the preceding SQL statement:

Sub AvgFreight()
    Dim dbs As Database, rst As Recordset, strSQL _
        AS String
    Set dbs = CurrentDb
    strSQL = "SELECT ShipCity, Avg(Freight) _
        AS AvgOfFreight FROM Orders " _
        & "GROUP BY ShipCity;"
    Set rst = dbs.OpenRecordset(strSQL)
    rst.MoveLast
    Debug.Print rst.RecordCount
    Set dbs = Nothing
End Sub

To use the Avg function in a calculated control, set the control's ControlSource property to an expression containing the Avg function. For example, to display the average freight cost for a set of orders in a text box, enter the following expression in the ControlSource property of the text box:

=Avg([Freight])

If you use the Avg function in a calculated control, you can restrict the set of records against which the function is performed by setting the form's Filter property.


Avg Function Example

The following example assumes that you have an Orders table that contains a field called Freight. You can use the Avg function to calculate the average freight charges for orders with freight charges over $100. Enter the following expression in SQL view in the Query window:

SELECT Avg([Freight]) AS [AverageFreight] FROM Orders
WHERE [Freight] > 100;

The next example creates a calculated control that displays the average freight charges for all of the underlying records in a form based on the same Orders table. Open a new form and set its RecordSource property to Orders. Enter this expression in the ControlSource property of a text box on the form. To apply a condition that limits the calculation to only some records, such as those for orders greater than $100, set the form's Filter property.

=Avg([Freight])


 Between...And Operator

Between...And Operator

In Microsoft Access, you can use the Between...And operator in a query expression or in a calculated control on a form or report.

You can use the Between...And operator in the Criteria row in the query design grid to create a parameter query. The Between...And operator enables you to prompt the user to enter a range of values by which the query is restricted. The expression supplied for the value1 argument serves as the prompt for the beginning of the range, and the expression supplied for the value2 argument serves as the prompt for the end of the range.

For example, suppose you have an Orders table that has an OrderDate field. Create a new query in the query design grid and drag the OrderDate field to the first Field cell in the grid. In the Criteria cell, enter the following statement:

Between [Enter beginning date:] And [Enter _
    ending date:]

    When you run the query, you will first be prompted with a dialog box that says "Enter beginning date:". Once you enter a value in that dialog and click OK, you will be prompted by a second dialog box that says "Enter ending date:". Assuming you enter valid dates, your results will include all the values in the OrderDate field that either match or fall between the dates you specified as parameters.

    You can also use the Between...And operator in a calculated control to determine whether the value of the control falls within a specified numeric range. The following example determines whether an order was shipped to a location within a range of postal codes. If the ShipPostalCode field is between 98101 and 98199, the IIf function returns "Local". Otherwise, it returns "Nonlocal".

    = IIf([ShipPostalCode] Between "98101" And "98199", _
     "Local", "Nonlocal")

    If any of the arguments supplied for the Between...And operator expression is Null, the Between...And operator returns a Null.


 Count Function

Count Function

In Microsoft Access, you can use the Count function in the query design grid, in an SQL statement in SQL view of the Query window, or in an SQL statement within Visual Basic code. You can also use the Count function in a calculated control on a form or report.

The Count function is most useful in totals queries and crosstab queries. It functions the same way whether you create the query in the query design grid or as an SQL statement in SQL view.

In the query design grid, you can create a new totals query by clicking Totals [image] on the Query Design toolbar. The Total row is then inserted in the grid. You can set the Total cell beneath a field to the aggregate function to perform on the data in that field.

The fastest way to count all the records in a query is to use the Count(*) function, which you can use in a calculated field in a query.

For example, suppose you have an Orders table that has both an OrderID field and a ShipCity field. You can create a query that displays the number of orders sent to each city. Create a new totals query, and drag the ShipCity field to the query design grid. Set the Total cell beneath the ShipCity field to Group By.

Next, create a calculated field by typing the following expression into a new Field cell:

CountOfOrders: Count(*)

Then, set the Total cell beneath this field to Expression. When you run the query, it will display the number of orders sent to each city.

You can view the SQL statement for this query by switching to SQL view. In this example, Microsoft Access creates the following SQL statement:

SELECT ShipCity, Count(*) AS CountOfOrders
FROM Orders GROUP BY ShipCity;

You can achieve the same results by dragging the OrderID field to the query design grid, and clicking Count in the Total cell beneath it. This query will be slightly slower than the one that uses the Count(*) function. Note how the following differs from the preceding SQL statement:

SELECT ShipCity, Count(OrderID) AS CountOfOrders
FROM Orders GROUP BY ShipCity;

You can also use an SQL statement within Visual Basic code. For example, the following procedure creates a dynaset-type Recordset object from the faster of the two preceding SQL statements:

Sub CountOrders()
    Dim dbs As Database, rst As Recordset, strSQL AS String
    Set dbs = CurrentDb
    strSQL = "SELECT ShipCity, Count(*) _
        AS CountOfOrders FROM Orders " _
        & "GROUP BY ShipCity;"
    Set rst = dbs.OpenRecordset(strSQL)
    rst.MoveLast
    Debug.Print rst.RecordCount
    Set dbs = Nothing
End Sub

To use the Count function in a calculated control, set the control's ControlSource property to an expression containing the Count function. For example, to display the number of orders in a set of orders in a text box, enter the following expression in the ControlSource property of the text box.

=Count([OrderID])

If you use the Count function in a calculated control, you can restrict the set of records against which the function is performed by setting the form's Filter property.


Count Function Example

The following example assumes that you have an Orders table that contains a field called ShipCountry. You can use the Count function to calculate the number of orders shipped to the United Kingdom. Enter the following expression in SQL view in the Query window:

SELECT Count([ShipCountry]) AS [UKOrders] FROM Orders
WHERE [ShipCountry] = 'UK';

The next example creates a calculated control that displays the number of orders in the same Orders table. Open a new form and set its RecordSource property to Orders. Enter the following expression in the ControlSource property of a text box on the form. To apply a condition that limits the count to only some records, such as those for orders shipped to the United Kingdom, set the form's Filter property.

=Count([ShipCountry])


CREATE INDEX Statement Example (MDB)

To try the following examples in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

Warning These examples makes changes to the Northwind sample database. Before beginning, you may wish to make a backup copy of the sample database.

The next example creates an index consisting of the fields HomePhone and Extension in the Employees table:

CREATE INDEX NewIndex ON Employees (HomePhone, _
    Extension);

The following example creates an index on the Customers table with the CustomerID field. No two records can have the same data in the CustomerID field, and no Null values are allowed.

CREATE UNIQUE INDEX CustID ON Customers (CustomerID) _
    WITH DISALLOW NULL;

To delete the index created in the preceding example, you must use the DROP statement. You can't delete the index from table Design view unless you also delete the relationship on the Customers table. The following statement deletes the new index by using the DROP statement:

DROP INDEX CustID ON Customers;

The following example creates an index on an ODBC linked table. The table's remote database is unaware of and unaffected by the new index. The following example won't work if you simply paste it into Microsoft Access; you first need to create an ODBC linked table called OrderDetailsODBC.

CREATE UNIQUE INDEX OrderID ON OrderDetailsODBC _
    (OrderID);


CREATE TABLE Statement, CONSTRAINT Clause Example (MDB)

To try the following examples in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

Warning These examples makes changes to the Northwind sample database. Before beginning, you may wish to make a backup copy of the sample database.

The following example creates a new table with two Text fields:

CREATE TABLE FirstTable (FirstName TEXT, _
    LastName TEXT);

The next example creates a new table with two Text fields, a Date/Time field, and a unique index made up of all three fields:

CREATE TABLE SecondTable (FirstName TEXT, _
    LastName TEXT, DateOfBirth DATETIME, _
    CONSTRAINT MyTableConstraint UNIQUE (FirstName, _
    LastName, DateOfBirth));

The following example creates a new table with two Text fields and an Integer Number field. The SSN field is the primary key.

CREATE TABLE ThirdTable (FirstName TEXT, _
    LastName TEXT, SSN INTEGER
CONSTRAINT MyFieldConstraint PRIMARY KEY);


 DELETE Statement

DELETE Statement

In Microsoft Access, no query result set or datasheet is produced when you use the DELETE statement. If you want to know which records will be deleted, first view the datasheet of a select query that uses the same criteria, and then run a delete query.


DELETE Statement Example (MDB)

To try the following example, add a few records to the Employees table with the Title value of "Trainee".

This example deletes all records for employees whose title is Trainee. When the FROM clause includes only one table, you don't have to list the table name in the DELETE statement.

DELETE * FROM Employees WHERE Title = 'Trainee';


DROP Statement Example (MDB)

To try the following example, create an index called MyIndex on the Employees table in the Northwind database, by using any field. Then create a new table called Trainees. Create a new query in the Northwind sample database and close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

Warning These examples makes changes to the Northwind sample database. Before beginning, you may wish to make a backup copy of the sample database.

The following example deletes the index MyIndex from the Employees table:

DROP INDEX MyIndex ON Employees;

The next example deletes the Trainees table from the database:

DROP TABLE Trainees;


 SQL Expressions

SQL Expressions

Many Visual Basic functions can be used in SQL strings. You can use Visual Basic functions in SQL strings included in Visual Basic code, in SQL view of the Query window, or in the query design grid. You can also write your own Visual Basic functions and use them in SQL strings.

Functions that can be included in SQL strings must return a value that is either a string or a Variant. Also, whatever operation is performed by the function can be performed only once. You can't include a function that must be performed on every record in the data set, because the SQL statement is only passed to the Microsoft Jet database engine once. For example, you can't create a function that takes a field value as an argument.

You can include Visual Basic functions in an SQL statement that you use to define a QueryDef object, or a dynaset-type or snapshot-type Recordset object in code. In the Microsoft Access query design grid, you can include Visual Basic functions in an SQL statement, in criteria expressions, or in calculated field expressions.


SQL Expressions Example

The following example creates a dynaset-type Recordset object from an SQL statement. The SQL statement includes the Year function in a WHERE clause to return only records for orders placed in 1995.

Sub Orders96()
    Dim dbs As Database, rst As Recordset, strSQL _
        AS String
    Dim fld As Field

    Set dbs = CurrentDb
    strSQL = "SELECT DISTINCTROW OrderID, OrderDate " _
        & "FROM Orders " _
        & "WHERE ((Year([OrderDate])=1996));"
    Set rst = dbs.OpenRecordset(strSQL, dbOpenDynaset)
    rst.MoveLast
    Debug.Print rst.RecordCount
End Sub

The next example shows how you can include a Visual Basic function in an SQL statement in SQL view in the Query window. The following SQL statement defines a query that displays the ShipName field from an Orders table, calculates the number of characters in that field for each record by using the Len function, and displays that calculation in another column.

SELECT DISTINCTROW ShipName, Len([ShipName]) _
    AS LengthOfShipName
FROM Orders;

You can create the same query in the query design grid. Create a new query and add the Orders table. Drag the ShipName field onto the Field cell in the first column in the grid. In another Field cell, create a calculated field expression by entering the following expression.

LengthOfShipName: Len([ShipName])


 First, Last Functions

First, Last Functions

In Microsoft Access, you can use the First and Last functions in the query design grid, in an SQL statement in SQL view of the Query window, or in an SQL statement within Visual Basic code. You can also use the First and Last functions in a calculated control on a form or report.

The First and Last functions are most useful in calculated controls on a report. For example, if you have an Order report that is grouped on a ShipCountry field and sorted on an OrderDate field, you can use the First and Last functions in calculated controls to show the range of earliest to latest order dates for each grouping. To group on the ShipCountry field, click Sorting And Grouping [image] on the Report Design toolbar. Choose ShipCountry in the Field/Expression column, and set the GroupHeader and GroupFooter properties to Yes. In Design view, create two new text boxes in the ShipCountry footer, and set the ControlSource property for both to the following expressions:

=First([OrderDate])
=Last([OrderDate])

When you switch to Print Preview, you will see the first and last order dates for each group of orders.

Notes If you want to return the first or last record in a set of records in Access 2000, you should create a query sorted as either ascending or descending and set the TopValues property to 1. For more information, see the TopValues property topic. From Visual Basic, you can also create a sorted result set of the query, and use the DAO MoveFirst or MoveLast method to return the first or last record in a set of records.

In Access projects (.adp), the First and Last functions operate as if the underlyng information is not sorted. The function will return the first entry that matches the criteria listed in the function which may not be the first or last matching entry in the underlying information.


 FROM Clause

FROM Clause

If you include a query or table name in the FROM clause of an SQL statement, that query or table will be automatically added to the Query window.

Conversely, any table or query that you add to the Query window will be included in the FROM clause of the corresponding SQL statement.


 GROUP BY Clause

GROUP BY Clause

Including a GROUP BY clause in an SQL statement is equivalent to creating a totals query in the Query window and setting the Total cell to Group By for the appropriate field.


GROUP BY Clause Example (MDB)

To try the following examples in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

The following example finds the average of the unit price for all products from each supplier and groups the list of prices by supplier:

SELECT SupplierID, Avg(UnitPrice) AS AvgOfUnitPrice
FROM Products GROUP BY SupplierID;

The next example finds the maximum unit price for a product in each category:

SELECT CategoryID, Max(UnitPrice) AS MaxOfUnitPrice
FROM Products GROUP BY CategoryID;

The following example counts the number of orders attributed to each employee in the database:

SELECT EmployeeID, Count(OrderID) AS CountOfOrderID
FROM Orders GROUP BY EmployeeID;


HAVING Clause Example (MDB)

To try the following examples in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

The following example finds the suppliers whose products have an average unit price over $25:

SELECT SupplierID, Avg(UnitPrice) AS AvgOfUnitPrice
FROM Products GROUP BY SupplierID
HAVING (Avg(UnitPrice)>25);

The next example selects employees who have sold more than 100 orders:

SELECT EmployeeID, Count(OrderID) AS CountOfOrderID
FROM Orders GROUP BY EmployeeID
HAVING Count(OrderID) > 100;


INNER JOIN Operation Example (MDB)

To try the following example in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste the example into the SQL window, and run the query.

The following example creates two equi-joins: one between the Order Details and Orders tables and another between the Orders and Employees tables. Both joins are necessary because the Employees table doesn't contain sales data, and the Order Details table doesn't contain employee data. The query produces a list of employees and their total sales.

SELECT DISTINCTROW Sum(UnitPrice * Quantity)
    AS Sales, FirstName & " " & LastName
    AS Name FROM Employees
    INNER JOIN(Orders INNER JOIN [Order Details]
    ON Orders.OrderID = [Order Details].OrderID)
    ON Employees.EmployeeID = Orders.EmployeeID
    GROUP BY FirstName & " " & LastName;


In Operator Example (MDB)

To try the following example in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste the example into the SQL window, and run the query.

This example creates a query on the Orders table that includes orders shipped to Colchester, Hedge End, and London:

SELECT * FROM Orders WHERE ShipCity _
    In ('Colchester','Hedge End','London');


 In Operator

In Operator

In Microsoft Access, you can use the In operator in a query expression or in a calculated control on a form or report.

You can use the In operator in a query expression when you need to set a number of criteria. For example, suppose you have an Orders table with both a ShipCountry field and an OrderID field, and you want to create a query to show all orders sent to the United States, Canada, or the United Kingdom. Create a new query in the Query window and add the Orders table. Drag the OrderID field and the ShipCountry field to the query design grid. Enter the following expression in the Criteria cell below the ShipCountry field:

In('USA', 'Canada', 'UK')

When you run the query, you will see all orders shipped to one of these three countries.

You can achieve the same result by entering the following expression in the Criteria cell:

"USA" Or "Canada" Or "UK"

With a long list of criteria, it may be more convenient to use the In operator than the Or operator. In addition, the SQL statement for the expression containing the In operator is shorter.

You can use the In operator in a calculated control to determine whether the value of a field in the current record is within a set of values. For example, you might use the In operator with the IIf function to determine whether the value of a control is among a set of specified values. In the following example, if the ShipRegion is WA, OR, or ID, the IIf function returns "Local". Otherwise, it returns "Nonlocal".

=IIf([ShipRegion] In ('WA','OR','ID'), "Local", _
     "Nonlocal")


 INSERT INTO Statement

INSERT INTO Statement

If you create an INSERT INTO...VALUES query in SQL view, save and close the query, and then reopen it, you'll see that Microsoft Access has converted the VALUES clause to a SELECT clause. This doesn't alter the results of the query.

The use of the INSERT INTO statement is equivalent to setting the DestinationTable property in the query's property sheet of an append query in query Design view.


INSERT INTO Statement Example (MDB)

Warning These examples makes changes to the Northwind sample database. Before beginning, you may wish to make a backup copy of the sample database.

To try the following example, create a copy of the Customers table and name it NewCustomers. This example selects all records in the New Customers table and adds them to the Customers table. When individual columns aren't designated, the SELECT table column names must match exactly those in the INSERT INTO table.

INSERT INTO Customers SELECT * FROM NewCustomers;

The next example creates a new record in the Employees table:

INSERT INTO Employees (FirstName,LastName, Title)
    VALUES ('Harry', 'Washington', 'Trainee');

The following example selects all trainees from an assumed Trainees table who were hired more than 30 days ago and adds their records to the Employees table.

INSERT INTO Employees SELECT Trainees.* FROM Trainees
    WHERE HireDate < Now() - 30;

You can use the INSERT INTO clause to back up information in your database before it is changed. For example, you can back up information in an Employees table immediately before a user makes any changes to the data in that table.

To try the following example, in the Database window copy the Employees table to a new table called EmployeeHistory by clicking the table, clicking Copy on the toolbar, then clicking Paste . Under Paste Options in the Paste Table As dialog box, click Structure Only. This will copy the structure of the table only, without any data. Next paste the following SQL statement into a new query and save the query as BackUpQuery:

INSERT INTO EmployeesHistory (FirstName, LastName, Title)
    VALUES (Forms!Employees!FirstName, _
        Forms!Employees!Lastname,Forms!Employees!Title);

Open the Employees form in form Design view and set the form's BeforeUpdate property to [Event Procedure]. In the BeforeUpdate event procedure, enter the following code:

DoCmd.OpenQuery "BackUpQuery"

Now the existing data in the Employees table will be copied to the backup table each time a user changes it.


IN Clause Example (MDB)

The following table shows how you can use the IN clause to retrieve data from an external database. Each example assumes the Customers table is stored in an external database.

Note The SQL IN clause is different than the SQL In operator, which is used to determine whether the value of an expression is equal to any of several values in a specified list.

External database SQL statement
Microsoft Jet database.

JetData.mdb is the name of the Jet database that contains the Customers table.

 SELECT CustomerID
FROM Customers
IN 'C:\My Documents\JetData.mdb'
WHERE CustomerID Like 'A*';
Microsoft Excel workbook (.xls file).

XLData.xls is a Microsoft Excel workbook that contains a worksheet called Customers. CustomersRange is a named range in that worksheet. Note that to denote the entire worksheet as the table, you must append a dollar sign ($) and enclose the name in brackets.

 SELECT CustomerID, CompanyName
FROM [Customers$]
IN 'C:\My Documents\XLData.xls' 'EXCEL 5.0;'
WHERE CustomerID Like 'A*';

– or –

SELECT CustomerID, CompanyName
FROM CustomersRange
IN 'C:\My Documents\XLData.xls' 'EXCEL 5.0;'
WHERE CustomerID Like 'A*';
dBASE III or IV.

To retrieve data from a dBASE III table, substitute dBASE III for dBASE IV.

 SELECT CustomerID
FROM Customers
IN C:\DBASE\DATA\SALES dBASE IV;
WHERE CustomerID Like A*;
dBASE III or IV (by using DATABASE syntax).

To retrieve data from a dBASE III table, substitute dBASE III for dBASE IV.

 SELECT CustomerID
FROM Customers
IN [dBASE IV;DATABASE=C:\DBASE\DATA\SALES;]
WHERE CustomerID Like A*;
Paradox 3.x or 4.x.

To retrieve data from a Paradox version 3.x table, substitute Paradox 3.x for Paradox 4.x.

 SELECT CustomerID
FROM Customers
IN C:\PARADOX\DATA\SALES Paradox 4.x;
WHERE CustomerID Like A*;
Paradox 3.x or 4.x (by using DATABASE syntax).

To retrieve data from a Paradox version 3.x table, substitute Paradox 3.x for Paradox 4.x.

 SELECT CustomerID
FROM Customers
IN [Paradox 4.x;DATABASE=C:\PARADOX\DATA\SALES;]
WHERE CustomerID Like A*;


LEFT JOIN, RIGHT JOIN Operations Example (MDB)

To try the following examples in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

The following example selects all customers, including those without orders:

SELECT Customers.CustomerID, CompanyName, OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
ORDER BY OrderID;

The next example selects all suppliers, including those without products. Before you try this example, run the following query to add a record to the Suppliers table:

INSERT INTO Suppliers (CompanyName, ContactName, _
    ContactTitle)
VALUES ('Acme Supply Co.', 'That Coyote', _
    'Sales Manager');

Next create a new query, paste the following SQL statement into the SQL window, and run the query.

SELECT Suppliers.SupplierID, Suppliers.CompanyName, _
    Products.ProductID, Products.ProductName
    FROM Products RIGHT JOIN Suppliers
    ON Products.SupplierID = Suppliers.SupplierID
    ORDER BY Products.SupplierID;

To delete the additional record you created in the Suppliers table, you can run the following query:

DELETE * FROM Suppliers
WHERE CompanyName = 'Acme Supply Co.';


 SQL Like Operator

SQL Like Operator

In Microsoft Access, you can use the Like operator in a query expression or in a calculated control on a form or report.

You can use the Like operator to specify inexact criteria in the query design grid. For example, if you type Like "C*" in the Criteria row of the query design grid, the query returns all field values beginning with the letter C.

In a parameter query, you can use the Like operator to prompt the user for a pattern to search for. For example, suppose you have an Employees table that includes a LastName field. In the Query window, create a new query by adding the Employees table and dragging the LastName field to the grid. Enter the following expression in the Criteria cell:

Like [Enter first few letters of name:]&"*"

When the query is run, a dialog box prompts the user with "Enter first few letters of name:". If the user types Sm in the dialog box, the query looks for the pattern Sm* — that is, all names beginning with the letters Sm.

You can use the Like operator in an expression as a setting for the ValidationRule property. For example, you can restrict data entered in a text box control to an inexact specification. In the ValidationRule property of the text box, enter the following expression:

Like "P[A-F]###"

Data entered in this text box must now begin with the letter P, followed by any letter between A and F and three digits.


Like Operator Example (MDB)

The following example returns a list of employees whose names begin with the letters A through D. To try this example in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste the example into the SQL window, and run the query.

SELECT * FROM Employees WHERE LastName Like '[A-D]*';


 Min, Max Functions

Min, Max Functions

In Microsoft Access, you can use the Min and Max functions in the query design grid, in an SQL statement in SQL view of the Query window, or in an SQL statement within Visual Basic code. You can also use the Min and Max functions in a calculated control on a form or report.

The Min and Max functions are most useful in totals queries and crosstab queries. They function the same way whether you create the query in the query design grid or as an SQL statement in SQL view.

In the query design grid, you can create a new totals query by clicking Totals [image] on the Query Design toolbar. The Total row is then inserted in the grid. You can set the Total cell beneath a field to the aggregate function to perform on the data in that field.

For example, suppose you have an Orders table that has both a Freight field and a ShipCity field. You can create a query that displays the minimum freight cost for orders sent to each city. Create a new totals query, and drag the ShipCity field to the query design grid. The Total cell beneath the ShipCity field should be set to Group By. Drag the Freight field to the query design grid, and set the Total cell beneath it to Min. When you run the query, it will display the minimum freight cost for orders sent to each city.

You can view the SQL statement for this query by switching to SQL view. In this example, Microsoft Access creates the following SQL statement:

SELECT ShipCity, Min(Freight) AS MinOfFreight
FROM Orders GROUP BY ShipCity;

You can also use an SQL statement within Visual Basic code. For example, the following code creates a dynaset-type Recordset object from the preceding SQL statement:

Sub MinFreight()
    Dim dbs As Database, rst As Recordset, strSQL_
        AS String

    Set dbs = CurrentDb
    strSQL = "SELECT ShipCity, Min(Freight) _
        AS MinOfFreight FROM Orders " _
        & "GROUP BY ShipCity;"
    Set rst = dbs.OpenRecordset(strSQL)
    rst.MoveLast
    Debug.Print rst.RecordCount
    Set dbs = Nothing
End Sub

To use the Min and Max functions in a calculated control, set the control's ControlSource property to an expression containing either of these functions. For example, to display the minimum freight cost for a set of orders in a text box, enter the following expression in the ControlSource property of the text box:

=Min([Freight])

If you use the Min or Max function in a calculated control, you can restrict the set of records against which the function is performed by setting the form's Filter property.


Min, Max Functions Example

The following example assumes that you have an Orders table that contains fields called Freight and ShipCountry. You can use the Min and Max functions to return the lowest and highest freight charges for orders shipped to the United Kingdom. Enter the following expressions in SQL view in the Query window:

SELECT Min([Freight]) AS [LowFreight] FROM Orders
WHERE [ShipCountry] = 'UK';

SELECT Max([Freight]) AS [HighFreight] FROM Orders
WHERE [ShipCountry] = 'UK';

The next example creates a calculated control that displays the lowest freight charge for all records in the same Orders table. Open a new form and set its RecordSource property to Orders. Enter the following expression in the ControlSource property of a text box on the form. To apply a condition that limits the search to only some records, such as those for orders shipped to the United Kingdom, set the form's Filter property.

=Min([Freight])


 ORDER BY Clause

ORDER BY Clause

In Microsoft Access, an ORDER BY clause sorts the displayed data on a specified field or fields in ascending or descending order. The use of an ORDER BY clause is equivalent to clicking Ascending or Descending in a Sort cell in the query design grid.


ORDER BY Clause Example (MDB)

To try the following examples in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

The following SQL statements use the ORDER BY clause to sort records alphabetically and then by category.

This example sorts the records by last name in descending order (Z to A):

SELECT LastName, FirstName FROM Employees
    ORDER BY LastName DESC;

The next example sorts by category ID first, and then by product name:

SELECT CategoryID, ProductName, UnitPrice
    FROM Products ORDER BY CategoryID, ProductName;


 PARAMETERS Declaration

PARAMETERS Declaration

With a parameter query, Microsoft Access prompts you for the criteria when the query is run. This enables you to design a query that returns records based on criteria supplied by the user.

The name argument that you supply with the PARAMETERS declaration provides the text that is displayed in a dialog box when you run the query. Microsoft Access automatically creates this dialog box for you.

The use of the PARAMETERS declaration in SQL view is equivalent to defining parameters in the Criteria cell of the query design grid.


PARAMETERS Declaration Example (MDB)

To try the following examples in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

The following example prompts the user to provide an employee's last name and then uses that entry as the criteria for the query:

PARAMETERS [Enter a Last Name:] Text;
SELECT *
FROM Employees
WHERE LastName = [Enter a Last Name:];

The next example prompts the user to provide a category ID and then uses that entry as the criteria for the query:

PARAMETERS [Enter a Category ID:] Value;
SELECT CategoryID, ProductName, _
    Count([Order Details].OrderID) AS Tally
FROM Products
INNER JOIN [Order Details] ON Products.ProductID = _
    [Order Details].ProductID
GROUP BY CategoryID, ProductName
HAVING CategoryID = [Enter a Category ID:];


 PROCEDURE Clause

PROCEDURE Clause

When you copy a PROCEDURE clause into SQL view, Microsoft Access removes the clause from the SQL statement when you switch to another view. Removing the PROCEDURE clause doesn't affect the results of the query. If the PROCEDURE clause includes parameters, Microsoft Access replaces the PROCEDURE reserved word and the name argument with the PARAMETERS reserved word. The defined parameters aren't removed.


SELECT...INTO Statement Example (MDB)

To try the following examples in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

The following example selects all records in the Employees table and copies them into a new table named Employees Backup:

SELECT * INTO [Employees Backup] FROM Employees;

The next example creates a new table called Sales Representatives that contains only employee records that have the title Sales Representative:

SELECT Employees.FirstName, LastName _
    INTO [Sales Representatives]
FROM Employees
WHERE Title = 'Sales Representative';

The following example makes a copy of the Employees table and places the new table in the assumed database Backup.mdb:

SELECT Employees.* INTO Employees IN Backup.mdb
FROM Employees;

The next example assumes a Payroll table with two fields: EmployeeID and Salary. This example creates a new table that contains employee and payroll data for all trainees. The Employees and Payroll tables have a one-to-one relationship. The new table contains all of the data from the Employees table plus the Salary field from the Payroll table.

SELECT Employees.*, Salary INTO Trainees
FROM Employees
INNER JOIN Payroll ON Employees.EmployeeID = _
    Payroll.EmployeeID
WHERE Title = 'Trainee';


 SELECT Statement

SELECT Statement

In Microsoft Access, if you are working in SQL view in the Query window, field names (field1, field2) are used as column headings in Datasheet view. To display a different column heading for a column in the datasheet, use the AS reserved word. If you use the AS reserved word, then the alias1, alias2 arguments provide the column names to use in displaying the retrieved data in Datasheet view. The use of the AS clause is equivalent to setting the Alias property in the field list property sheet in query Design view.

The following example uses the title "Birthday" to head the column in the resulting datasheet:

SELECT [BirthDate] AS Birthday FROM Employees;

When you use aggregate functions or queries that return ambiguous or duplicate field names, you must also use the AS clause to provide an alternate name for the field. The following example creates the column heading "Head Count" in Datasheet view:

SELECT COUNT([EmployeeID])
AS [Head Count] FROM Employees;

If you are working with Data Access Objects (DAO) in Visual Basic code, the field1, field2 arguments are used to name the Field objects in the Recordset object returned by the query. If you include the AS reserved word, then the alias1, alias2 arguments provide the column headings to return as Field object names in the resulting Recordset object.


SELECT Statement, FROM Clause Example (MDB)

To try the following examples in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

The following example selects the LastName and FirstName fields of all records in the Employees table:

SELECT LastName, FirstName FROM Employees;

The next example selects all fields from the Employees table:

SELECT * FROM Employees;

The following example counts the number of records that have an entry in the PostalCode field and names the returned field Tally:

SELECT Count(PostalCode) AS Tally FROM Customers;

The next example shows what product unit prices would be if each were increased by 10 percent. It doesn't change the existing unit prices in the database.

SELECT ProductName, UnitPrice AS Current, _
    UnitPrice * 1.1 AS ProposedNewPrices
FROM Products;

The following example calculates the number of products in the database and the average and maximum unit prices:

SELECT Count(*) AS [Total Products], Avg(UnitPrice)
    AS [Average Unit Price], Max(UnitPrice)
    AS [Maximum Unit Price] FROM Products;

The next example displays the ProductName and UnitPrice for each record in the Products table. The string "has a unit price of" separates the two fields in the result set.

SELECT ProductName, 'has a unit price of', _
    UnitPrice FROM Products;


 StDev, StDevP Functions

StDev, StDevP Functions

In Microsoft Access, you can use the StDev and StDevP functions in the query design grid, in an SQL statement in SQL view of the Query window, or in an SQL statement within Visual Basic code. You can also use the StDev and StDevP functions in a calculated control on a form or report.

The StDev and StDevP functions are most useful in totals queries and crosstab queries. They function the same way whether you create the query in the query design grid or as an SQL statement in SQL view.

In the query design grid, you can create a new totals query by clicking Totals [image] on the Query Design toolbar. The Total row is then inserted in the grid. You can set the Total cell beneath a field to the aggregate function to perform on the data in that field.

For example, suppose you have an Orders table that has both a Freight field and a ShipCity field. You can create a query that displays the standard deviation of freight cost for orders sent to each city. Create a new totals query, and drag the ShipCity field to the query design grid. The Total cell beneath the ShipCity field should be set to Group By. Drag the Freight field to the query design grid, and set the Total cell beneath it to StDev. When you run the query, it will display the standard deviation of freight cost for orders sent to each city.

You can view the SQL statement for this query by switching to SQL view. In this example, Microsoft Access creates the following SQL statement:

SELECT ShipCity, StDev(Freight) AS StDevOfFreight
FROM Orders GROUP BY ShipCity;

You can also use an SQL statement within Visual Basic code. For example, the following code creates a dynaset-type Recordset object from the preceding SQL statement:

Sub StDevFreight()
    Dim dbs As Database, rst As Recordset, strSQL _
        AS String

    Set dbs = CurrentDb
    strSQL = "SELECT ShipCity, StDev(Freight) " _
    & "AS StDevOfFreight, ShipCity FROM Orders " _
    & "GROUP BY ShipCity;"
    Set rst = dbs.OpenRecordset(strSQL)
    rst.MoveLast
    Debug.Print rst.RecordCount
    Set dbs = Nothing
End Sub

To use the StDev and StDevP functions in a calculated control, set the control's ControlSource property to an expression containing either of these functions. For example, to display the standard deviation of freight costs for a set of orders in a text box, enter the following expression in the ControlSource property of the text box:

=StDev([Freight])

If you use the StDev or StDevP function in a calculated control, you can restrict the set of records against which the function is performed by setting the form's Filter property.


StDev, StDevP Functions Example

The following example assumes that you have an Orders table that contains fields called Freight and ShipCountry. You can use the StDev and StDevP functions to return the standard deviation of freight charges for orders shipped to the United Kingdom. Enter the following expressions in SQL view in the Query window:

SELECT StDev([Freight]) AS [FreightDev] FROM Orders
WHERE [ShipCountry] = 'UK';

SELECT StDevP([Freight]) AS [FreightDevP] FROM Orders
WHERE [ShipCountry] = 'UK';

The next example creates a calculated control that displays the standard deviation of freight charges for all records in the same Orders table. Open a new form and set its RecordSource property to Orders. Enter the following expression in the ControlSource property of a text box on the form. To apply a condition that limits the search to only some records, such as those for orders shipped to the United Kingdom, set the form's Filter property.

=StDev([Freight])


SQL Subqueries Example (MDB)

To try the following examples in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

The following example shows all non-discounted orders whose total is higher than the average order value:

SELECT OrderID, (UnitPrice * Quantity) _
    AS OrderTotal FROM [Order Details]
WHERE Discount = 0 AND (UnitPrice * Quantity) > _
    ALL(SELECT Avg(UnitPrice * Quantity)
    FROM [Order Details]);

The next example lists the name and unit price of every product whose unit price is the same as that of Aniseed Syrup:

SELECT ProductName, UnitPrice FROM Products
WHERE UnitPrice = (SELECT UnitPrice FROM [Products]
WHERE ProductName = 'Aniseed Syrup');

The following example lists the company and contact of every customer who placed an order in the second quarter of 1995:

SELECT ContactName, CompanyName, ContactTitle, Phone
    FROM Customers
WHERE CustomerID IN (SELECT CustomerID FROM Orders
WHERE OrderDate
BETWEEN #04/1/95# AND #06/30/95#);

The next example selects the name of every employee who has booked at least one order. This could also be done with an INNER JOIN.

SELECT FirstName, LastName FROM Employees
WHERE EXISTS (SELECT OrderID FROM Orders
WHERE Orders.EmployeeID = Employees.EmployeeID);


 Sum Function

Sum Function

In Microsoft Access, you can use the Sum function in the query design grid, in an SQL statement in SQL view of the Query window, or in an SQL statement within Visual Basic code. You can also use the Sum function in a calculated control on a form or report.

The Sum function is most useful in totals queries and crosstab queries. It functions the same way whether you create the query in the query design grid or as an SQL statement in SQL view.

In the query design grid, you can create a new totals query by clicking Totals [image] on the Query Design toolbar. The Total row is then inserted in the grid. You can set the Total cell beneath a field to the aggregate function to perform on the data in that field.

For example, suppose you have an Orders table that has both a Freight field and a ShipCity field. You can create a query that displays the sum of freight costs for orders sent to each city. Create a new totals query, and drag the ShipCity field to the query design grid. The Total cell beneath the ShipCity field should be set to Group By. Drag the Freight field to the query design grid, and set the Total cell beneath it to Sum. When you run the query, it will display the sum of freight costs by city.

You can view the SQL statement for this query by switching to SQL view. In this example, Microsoft Access creates the following SQL statement:

SELECT ShipCity, Sum(Freight) AS SumOfFreight
FROM Orders GROUP BY ShipCity;

You can also use an SQL statement within Visual Basic code. For example, the following code creates a dynaset-type Recordset object from the preceding SQL statement:

Sub SumFreight()
    Dim dbs As Database, rst As Recordset, strSQL _
        AS String

    Set dbs = CurrentDb
    strSQL = "SELECT ShipCity, Sum(Freight) _
        AS SumOfFreight FROM Orders " _
        & "GROUP BY ShipCity;"
    Set rst = dbs.OpenRecordset(strSQL)
    rst.MoveLast
    Debug.Print rst.RecordCount
    Set dbs = Nothing
End Sub

To use the Sum function in a calculated control, set the control's ControlSource property to an expression containing the Sum function. For example, to display the sum of freight costs for a set of orders in a text box, enter the following expression in the ControlSource property of the text box:

=Sum([Freight])

If you use the Sum function in a calculated control, you can restrict the set of records against which the function is performed by setting the form's Filter property.


Sum Function Example

The following example assumes that you have an Orders table that contains fields called OrderID and ShipCountry, and an Order Details table that contain fields called UnitPrice and Quantity. You can use the Sum function to calculate the total sales for orders shipped to the United Kingdom. Enter the following expression in SQL view in the Query window:

SELECT Sum([UnitPrice]*[Quantity]) AS [TotalUKSales]
FROM Orders INNER JOIN [Order Details]
ON Orders.[OrderID] = [Order Details].[OrderID]
WHERE ([ShipCountry] = 'UK');

The next example creates a calculated control that displays the total sales for records in the Order Details table. Open a new form and set its RecordSource property to Order Details. Enter the following expression in the ControlSource property of a text box on the form. To apply a condition that limits the search to only some records, such as those for orders shipped to the United Kingdom, set the form's Filter property.

=Sum([UnitPrice]*[Quantity])


TRANSFORM Statement Example (MDB)

To try the following examples in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

The following example creates a crosstab query that shows product sales by month for a user-specified year. The months are returned from left to right (pivoted) as columns, and the product names are returned from top to bottom as rows.

PARAMETERS [Sales for which year?] LONG;
TRANSFORM Sum([Order Details].Quantity * _
    ([Order Details].UnitPrice - _
    ([Order Details].Discount / 100) * _
    [Order Details].UnitPrice)) AS Sales
SELECT ProductName FROM Orders
INNER JOIN (Products INNER JOIN [Order Details]
ON Products.ProductID = [Order Details].ProductID)
ON Orders.OrderID = [Order Details].OrderID
WHERE DatePart("yyyy", OrderDate) = _
    [Sales for which year?]
GROUP BY ProductName
ORDER BY ProductName
PIVOT DatePart("m", OrderDate);

The next example creates a crosstab query that returns product sales by quarter for each supplier for a user-specified year. The quarters are returned from left to right (pivoted) as columns, and the supplier names are returned from top to bottom as rows.

PARAMETERS [Sales for which year?] LONG;
TRANSFORM Sum([Order Details].Quantity * _
    ([Order Details].UnitPrice - _
    ([Order Details].Discount / 100) * _
    [Order Details].UnitPrice)) AS Sales
SELECT CompanyName FROM Orders
INNER JOIN ((Suppliers INNER JOIN Products
ON Suppliers.SupplierID = Products.SupplierID)
INNER JOIN [Order Details] ON Products.ProductID = _
    [Order Details].ProductID)
ON Orders.OrderID = [Order Details].OrderID
WHERE DatePart("yyyy", OrderDate) = _
    [Sales for which year?]
GROUP BY CompanyName
ORDER BY CompanyName
PIVOT "Qtr " & DatePart("q", OrderDate) _
    In ('Qtr 1', 'Qtr 2', 'Qtr 3', 'Qtr 4');


 UNION Operation

UNION Operation

In Microsoft Access, the arguments for the UNION operation (query1, query2,...queryn) can be a SELECT statement, the name of a stored Microsoft Access query, or the name of a stored Microsoft Access table preceded by the TABLE reserved word.

You can view a union query only in SQL view, not in the query design grid.


UNION Operation Example (MDB)

To try the following examples in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

The following example retrieves the names and cities of all suppliers and customers in Brazil:

SELECT CompanyName, City FROM Suppliers
WHERE Country = 'Brazil'
UNION SELECT CompanyName, City FROM Customers
WHERE Country = 'Brazil';

The next example retrieves the names and cities of all suppliers and customers located in Brazil:

SELECT CompanyName, City, 'Supplier' AS Source
FROM Suppliers
WHERE Country = 'Brazil'
UNION SELECT CompanyName, City, 'Customer'
FROM Customers
WHERE Country = 'Brazil'
ORDER BY City, Source;

The following example retrieves the names and IDs of all suppliers and customers. This union assumes that there are the same number of columns in each table.

TABLE Customers UNION TABLE Suppliers;


 UPDATE Statement

UPDATE Statement

Since the UPDATE statement doesn't generate a result set, there is no query datasheet for Microsoft Access to display when you use this statement.

If you want to confirm each change, you can use the Replace command on the Edit menu of the form or datasheet rather than an update query.


UPDATE Statement Example (MDB)

To try the following examples in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

Warning These examples makes changes to the Northwind sample database. Before beginning, you may wish to make a backup copy of the sample database.

The following example changes values in the ReportsTo field to 5 for all employee records that currently have ReportsTo values of 2:

UPDATE Employees SET ReportsTo = 5 WHERE ReportsTo = _
    2;

The next example increases the UnitPrice for all non-discontinued products from supplier #8 by 10 percent:

UPDATE Products SET UnitPrice = UnitPrice * 1.1
WHERE SupplierID = 8 AND Discontinued = No;

The following example reduces the UnitPrice for all non-discontinued products supplied by Tokyo Traders by 5 percent. The Products and Suppliers tables have a many-to-one relationship.

UPDATE Suppliers INNER JOIN Products
ON Suppliers.SupplierID = Products.SupplierID SET UnitPrice = UnitPrice * .95
WHERE CompanyName = 'Tokyo Traders' _
    AND Discontinued = No;


 Var, VarP Functions

Var, VarP Functions

In Microsoft Access, you can use the Var and VarP functions in the query design grid, in an SQL statement in SQL view of the Query window, or in an SQL statement within Visual Basic code. You can also use the Var and VarP functions in a calculated control on a form or report.

The Var and VarP functions are most useful in totals queries and crosstab queries. They function the same way whether you create the query in the query design grid or as an SQL statement in SQL view.

In the query design grid, you can create a new totals query by clicking Totals [image] on the Query Design toolbar. The Total row is then inserted in the grid. You can set the Total cell beneath a field to the aggregate function to perform on the data in that field.

For example, suppose you have an Orders table that has both a Freight field and a ShipCity field. You can create a query that displays the variance of freight cost for orders sent to each city. Create a new totals query, and drag the ShipCity field to the query design grid. The Total cell beneath the ShipCity field should be set to Group By. Drag the Freight field to the query design grid, and set the Total cell beneath it to Var. When you run the query, it will display the variance of freight cost for orders sent to each city.

You can view the SQL statement for this query by switching to SQL view. In this example, Microsoft Access creates the following SQL statement:

SELECT ShipCity, Var(Freight) AS VarOfFreight
FROM Orders GROUP BY ShipCity;

You can also use an SQL statement within Visual Basic code. For example, the following code creates a dynaset-type Recordset object from the preceding SQL statement:

Sub VarFreight()
    Dim dbs As Database, rst As Recordset, strSQL _
        AS String

    Set dbs = CurrentDb
    strSQL = "SELECT ShipCity, Var(Freight) _
        AS VarOfFreight FROM Orders" _
        & "GROUP BY ShipCity;"
    Set rst = dbs.OpenRecordset(strSQL)
    rst.MoveLast
    Debug.Print rst.RecordCount
    Set dbs = Nothing
End Sub

To use the Var and VarP functions in a calculated control, set the control's ControlSource property to an expression containing either of these functions. For example, to display the variance across freight costs in a text box, enter the following expression in the ControlSource property of the text box:

=Var([Freight])

If you use the Var or VarP function in a calculated control, you can restrict the set of records against which the function is performed by setting the form's Filter property.


Var, VarP Functions Example

Var, VarP Functions Examples

The following example assumes that you have an Orders table that contains a field called Freight. You can use the Var and VarP functions to estimate the variance of freight costs for orders shipped to the United Kingdom. Enter the following expressions in SQL view in the Query window:

SELECT Var([Freight]) AS [UKFreightVariance]
FROM Orders WHERE [ShipCountry] = 'UK';

SELECT VarP([Freight]) AS [UKFreightVarianceP]
FROM Orders WHERE [ShipCountry] = 'UK';

The next example creates a calculated control that displays the estimated variance for freight costs for records in the same Orders table. Open a new form and set its RecordSource property to Orders. Enter the following expression in the ControlSource property of a text box on the form. To apply a condition that limits the search to only some records, such as those for orders shipped to the United Kingdom, set the form's Filter property.

=Var([Freight])


 WHERE Clause

WHERE Clause

In Microsoft Access, the conditions that you establish in a WHERE clause in SQL view are the same as those you might enter in the Criteria cell in the query design grid. If you enter criteria in the query design grid, you can change to SQL view to see the WHERE clause.

Conversely, if you enter a WHERE clause in an SQL statement in SQL view, you can change to Design view to see the criteria in the query design grid, unless you are creating a union query. Union queries can only be viewed in SQL view.


WHERE Clause Example (MDB)

To try the following examples in Microsoft Access, first create a new query in the Northwind sample database. Close the Show Table dialog box without specifying a table or query. Switch to SQL view, paste an individual example into the SQL window, and run the query.

The following example selects the LastName and FirstName fields of each record in which the last name is King:

SELECT LastName, FirstName FROM Employees
WHERE LastName = 'King';

The next example selects the LastName and FirstName fields for employees whose last names begin with the letter S:

SELECT LastName, FirstName FROM Employees
WHERE LastName Like 'S*';

The following example selects products whose unit prices are between $20 and $50, inclusive:

SELECT ProductName, UnitPrice FROM Products
WHERE (UnitPrice >=20.00 And UnitPrice <= 50.00);

The next example selects all products whose names fall in alphabetic order between "Cha" and "Out", inclusive. It doesn't retrieve "Outback Lager" because "Outback Lager" follows "Out" and therefore is outside the specified range.

SELECT ProductName, UnitPrice FROM Products
WHERE ProductName Between 'Cha' And 'Out';

The following example selects orders placed during the first half of 1995:

SELECT OrderID, OrderDate FROM Orders
WHERE OrderDate Between #1-1-95# And #6-30-95#;

The next example selects orders shipped to Idaho, Oregon, or Washington:

SELECT OrderID, ShipRegion FROM Orders
WHERE ShipRegion In ('ID', 'OR', 'WA');


 WITH OWNERACCESS OPTION Declaration

WITH OWNERACCESS OPTION Declaration

You can include the WITH OWNERACCESS OPTION declaration in an SQL statement to allow users to run a query and view the results even if they don't have security permissions on the underlying tables. When this option is set, a user is granted the same permissions as the owner of the query.

For example, the owner of a query on an Employees table can include the WITH OWNERACCESS OPTION declaration in the definition of the query that returns all fields except those that give employees' addresses. A user who does not have read permissions on the Employees table can then run the query and view only those fields included in the query. In effect, the user now has restricted read access to the table.

The use of this declaration is equivalent to setting the RunPermissions property to Owner's in the query's property sheet in query Design view. Omitting the WITH OWNERACCESS OPTION declaration is equivalent to setting the RunPermissions property to User's, which is the default setting.


 Const Statement

Const Statement

A constant in a Microsoft Access standard module is private by default. If you precede a constant with the keyword Public, however, it is then available to other modules in the current database. It is also available to modules that reference the current database.

A constant defined in a class module is always private to that module, and can't be made public by using the Public keyword.


 Const Statement Example

Const Statement Example

In Microsoft Access, you cannot declare public constants in the Declarations section of a class module. Constants in a class module must be private. You can declare both public and private constants in the Declarations section of a standard module.

' In class module.
Const conCommission As Single = .08

' In standard module.
Const conErrorNumber As Integer = 91
Public Const conAddress As String = _
    "8421 58th Avenue, College Park, MD"


Dynamic Data Exchange (DDE) 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)]"
    ' Terminate all links.
    DDETerminateAll
End Sub


 Declare Statement

Declare Statement

In Microsoft Access, Declare statements are public by default. In a standard module, a public Declare statement is available to all procedures in the current database and in any referencing databases. You can preface a Declare statement with the Private keyword to ensure that it is not available outside of the current module.

To use a Declare statement in a class module, you must precede the statement with the Private keyword. If you fail to include the Private keyword, Microsoft Access generates a compile-time error.


Declare Statement Example

In Microsoft Access, you can use the Declare statement at the module level of a standard module to declare a reference to an external procedure in a dynamic-link library (DLL). A Declare statement is public by default. In order to include a Declare statement in a class module, precede it with the Private keyword.

The following example references a procedure in a DLL, then calls that procedure from Visual Basic.

' In standard module.
Declare Sub MessageBeep Lib "User32" (ByVal intN As _
    Integer)

' In class module.
Private Declare Sub MessageBeep Lib "User32" (ByVal _
    intN As Integer)

' Once you have referenced procedure in DLL with Declare
' statement, you can call that procedure normally from code.
Sub SystemBeep(intBeeps As Integer, sngPause As Single)
    Dim intI As Integer
    Dim sngStart As Single

    For intI = 1 To intBeeps
        ' Call system function.
        Call MessageBeep(intBeeps)
        ' Get start time.
        sngStart = Timer
        ' Pause between beeps.
        Do While Timer < sngStart + sngPause
            ' Return control to operating system.
            DoEvents
        Loop
    Next intI
End Sub


DeleteControl, DeleteReportControl Methods 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.
    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 If
End Sub


 Dim Statement

Dim Statement

You can use the New keyword with the Dim statement to declare an object variable of a specific type. If you include the New keyword in your variable declaration, you automatically create a new object and point the object variable to it. If you declare an object variable by using the New keyword, you don't need to use the Set statement.

By using the New keyword, you can create an object variable to point to any type of object. The New keyword is used most frequently to create a new instance of a class or to create a new Collection object, as shown in the following example.

' Create object variable and point it to new object.
Dim colInstances As New Collection

The following example shows how to use the New keyword to create a new instance of a class.

' Create new instance of class module.
Dim obj As New Class1

You can use the New keyword to create a new Microsoft Access object from some components that support Automation, formerly called OLE Automation. Check the component's documentation to determine whether or not it supports this syntax.

For example, from another component, assuming you have established a reference to the Microsoft Access type library, you can create a new Microsoft Access Application object with the following code.

Dim appAccess As New Access.Application


 Function Statement

Function Statement

In Microsoft Access, a public Function procedure is available to all other procedures in the current database and in referencing Microsoft Access databases. However, it is not available to any other applications.

If you declare a Function procedure as private in any module by preceding it with the Private keyword, that procedure is available only to other procedures in the same module.

If a Function procedure is declared as public within a private module, such as a class module, then the procedure is available to all other procedures in that database, but is not available to other Microsoft Access databases.


 Option Compare Statement

Option Compare Statement

In Microsoft Access, all modules by default contain the Option Compare Database statement in the Declarations section. This statement sets the string comparison method for the module to the one specified for the entire database.

You can change the string comparison method for all new databases by clicking Options on the Tools menu and changing the value in the New Database Sort Order box on the General tab of the Options dialog box. By default this value is set to General, which specifies a case-insensitive sort order based on the English alphabet.

Changing the New Database Sort Order option doesn't affect the string comparison method for the current database. It only affects databases that are created after the option has been set.

To specify a string comparison method for an individual module that is different from the one specified for the database, change Option Compare Database to Option Compare Binary or Option Compare Text. The Option Compare Binary statement compares strings by evaluating the ASCII values corresponding to the characters they contain, so the statement is case-sensitive. Option Compare Text is case-insensitive.

Note If you are using the Bookmark property of a Recordset object, you must include an Option Compare Binary statement in the Declarations section of the module. The setting and return value for the Bookmark property is a Variant array of Byte data. If you use a case-insensitive string comparison method, the Bookmark property may point you to the wrong record.


 Option Explicit Statement

Option Explicit Statement

In Microsoft Access, you can ensure that all new modules will automatically include the Option Explicit statement. Click Options on the Tool menu, click the Module tab, and select the Require Variable Declaration option.

Once you select this option, it will automatically be set for all other databases which you create or open with Microsoft Access.

Note When you select this option, only new modules will have the Option Explicit setting. You must enter the Option Explicit statement into the Declarations section of any existing modules. Or, when the module is open, click Options on the Tools menu, click the Module tab, and select the Require Variable Declaration option.


 Option Private Statement

Option Private Statement

When you include the Option Private statement in a standard module in Microsoft Access, any public variables or procedures in the module are still available to all other procedures in the current database. However, they are not available to procedures in other databases.

Since class modules are private by default, including the Option Private statement in a class module generates an error.


 Property Get Statement

Property Get Statement

You can use the Property Get statement to define a property procedure that returns the value of a property. You will probably want to use the Property Get and Property Let statements together to create a property in a class module. For example, you could define a Property Let procedure in a class module to set a new property, and a Property Get procedure to return the value of that setting. When you create a new instance of this class, the property procedures behave like custom properties for the new object. For more information about class modules, search the help index for "class modules".

Property procedures in a class module are public by default, and will be available to procedures in other modules in the current database, unless you preface them with the Private keyword.


 Property Let Statement

Property Let Statement

You can use the Property Let statement to define a property procedure that assigns the value of a property. You will probably want to use the Property Let and Property Get statements together to create a property in a class module. For example, you could define a Property Let procedure in a class module to set a new property, and a Property Get procedure to return the value of that setting. When you create a new instance of this class, the property procedures behave like custom properties for the new object. For more information about class modules, search the help index for "class modules".

Property procedures in a class module are public by default, and will be available to procedures in other modules in the current database, unless you preface them with the Private keyword.


 Public Statement

Public Statement

By default, module-level variables are private to that module. You must explicitly declare a public variable with the Public statement.

Module-level variables declared in standard modules with the Public statement are available to all other procedures in all modules in the current database and in referencing Microsoft Access databases. However, they are not available to any applications other than Microsoft Access.

If a public variable is declared in a module that contains the Option Private statement or in a class module, the variable is available to all procedures in the current database, but not to procedures in other databases.

Note The Public statement can't be used in a class module to declare a constant, a fixed-length string, or an array. In addition, if you include a Declare statement in a class module, you must precede it with the Private keyword. For more information about the Declare statement, search the help index for "Declare statement".


 Sub Statement

Sub Statement

In Microsoft Access, a public Sub procedure in a standard module is available to all other procedures in the current database and in referencing Microsoft Access databases. However, it is not available to any other applications.

If you declare a Sub procedure as private in any module, that procedure is available only to other procedures within the same module.

If a Sub procedure is declared as public within a private module, such as a class module, then the procedure is available to all other procedures in that database, but is not available to other Microsoft Access databases.

When you create an event procedure for a form or report, Microsoft Access automatically inserts a code stub for a Sub procedure and precedes it with the Private keyword. For example, create a command button on a new form, set its OnClick property to [Event Procedure], and click the Build button [image] to view the form's module. Microsoft Access inserts the following code for you in the module.

Private Sub Command0_Click

End Sub

You can then enter the code that you want to execute when that button's Click event occurs.


Type Statement

In Microsoft Access, user-defined types are public by default. You cannot define a public user-defined type within a class module. To declare a user-defined type within a class module, precede the Type statement with the Private keyword. If you fail to include the Private keyword, Microsoft Access generates a compile-time error.


 I can't open or create a report snapshot.

I can't open or create a report snapshot.

  • You might not have permission to open the file or folder that contains the file. Check the permissions on the file or folder, or contact your system administrator.

  • The report snapshot is too big, and you don't have enough disk space. Reclaim more disk space so that the complete report snapshot can be saved to your disk.

  • The file is not a report snapshot. A snapshot file has a file extension of .snp and must be in snapshot format. Verify that the file has the correct extension and is in report snapshot format (in Windows Explorer, right-click the file and select Properties; the type should be "Snapshot File.")

  • You don't have Snapshot Viewer installed. If necessary, Snapshot Viewer is automatically installed by Microsoft Access 2000 the first time you create a report snapshot, but you might not have created the report snapshot. You can also install Snapshot Viewer from the Setup program, or from a World Wide Web software download page located on the Microsoft Access Developer's Web site.

  • If you are attempting to open the report snapshot from a Web page, you might experience a connection or timeout problem while the report snapshot is being downloaded. Redisplay the Web page, or restart your Web browser to see whether that fixes the problem.


 The euro symbol isn't displayed for a Currency field on a data access page.

The euro symbol isn't displayed for a Currency field on a data access page.

On a data access page, when you display a field that has a Currency data type (Microsoft Access database), or money data type (Microsoft Access project), the page uses the currency symbol specified in Regional Settings in Windows Control Panel of the computer on which the page is displayed. The field doesn't inherit any format, including the currency and euro formats, specified for that field in the underlying record source.

To display the euro symbol ( [image]) with the currency values on a data access page, use an expression. For example, if a field called EuroValue contains currency values, you can use the following expression in the ControlSource property of a calculated control:

IIf(EuroValue>=0, Format(EuroValue," [image] #,##0.00"), Format((EuroValue*-1),"( [image] #,##0.00)"))


An identifier causes an error.

Microsoft Access 97 or later supports some new Visual Basic keywords, so you can no longer use these keywords as identifiers. These keywords are: AddressOf, Decimal, DefDec, Enum, Event, Friend, Implements, RaiseEvent, WithEvents. When you convert a previous-version Access database to Microsoft Access 2000, existing identifiers that are the same as a new Visual Basic keyword will cause a compile error. To fix this problem, change existing identifiers so they are not keywords.


 A procedure causes an error.

A procedure causes an error.

In Microsoft Access version 2.0, you could specify a name for a procedure that was the same as a module name. However, in Microsoft Access 95 or later, a procedure and a module can't have the same name. To fix this problem, rename the procedure or rename the module. Alternatively, you can avoid this error by using a fully qualified name for the procedure in your Visual Basic for Applications (VBA) code.


 The conditional formatting I applied to a control doesn't change when I thought it would.

The conditional formatting I applied to a control doesn't change when I thought it would.

If you have applied conditional formatting to a control, then Microsoft Access applies the formatting depending on whether the control value or other evaluated data meets a condition that you specified.

  • If you base the formatting condition on the text contained in the selected control by choosing Field Value Is in the Conditional Formatting dialog, then formatting such as bold or font color may change as the text in the control changes.

  • Conditional formatting has priority over formatting that you apply directly to a control by using a Formatting toolbar button. If a specified condition is true, the formatting for that condition overrides the default formatting.


Access isn't applying conditional formatting correctly to a control on my form or report.

  • Check for multiple conditions If you specify multiple conditions and a value meets more than one condition, Microsoft Access applies only the formatting for the first true condition.

  • See whether conditions overlap If you specify conditions that overlap, Access applies only the format of the first true condition. For example, if you specify a condition that applies a yellow background to control values between 100 and 200 inclusive, and then you specify a second condition that applies a red background to control values below 120, the control values of 100 through 119 will have a yellow background. Try to avoid overlapping conditions.

  • Check control references If you used an expression as the formatting criteria, the control references in the formula may not be correct. Learn about creating an expression.


 I can't send a report snapshot in e-mail.

I can't send a report snapshot in e-mail.

  • If the Mail Recipient (as Attachment) subcommand on the Send To command in the File menu isn't available, your mail program might not be properly installed, or it might not support Messaging Application Programming Interface (MAPI). Check your program's documentation to confirm that it supports MAPI, and if so, try to reinstall the mail program to make the Send To command available.

  • Depending on how your e-mail program was set up, you might not be able to send a report snapshot programmatically if the e-mail program requires you to log on and enter information. For example, Microsoft Outlook can be installed to prompt you for a user profile when you log on. Therefore, you might need to modify your e-mail program.


 I get the Web page instead of the report when I print a report snapshot.

I get the Web page instead of the report when I print a report snapshot.

If you are viewing a report snapshot from a Web page, don't use the Print command from the File menu. That Print command prints only the contents of the Web page, not each page of the report snapshot. Instead, use the Print button [image] to the right of the navigation controls at the bottom of the window, or right-click the report snapshot, and then select Print.


I can't find or replace text in a field with an input mask. Why?

If you add an input mask to a table that already contains data, the Find or Replace dialog box may not find the text when the field's data does not meet the criteria of the input mask. To resolve this, you can remove the input mask, use the Find or Replace dialog box, and then add the input mask back. Alternatively, you can modify the data in the field with the input mask to meet the criteria of the input mask.


 I can't find or replace text that I know exists. Why?

I can't find or replace text that I know exists. Why?

  • If the Find or Replace dialog box doesn't find records that meet the criteria you specified, and you know the records exist, check whether the field you're searching in is a Lookup field. A Lookup field looks up values from another table and stores the references to values in the current table. If it is a Lookup field, you need to select the Search Fields As Formatted check box in order for Microsoft Access to find the records.

  • When you try to find or replace data in a Microsoft Access project, Access performs the operation only on the data that is stored on the client. If your datasheet or form has reached its maximum record limit, there is more data on the server. To find or replace all the data on the server, set the maximum record limit to no limit by using the maximum record limit button to the right of the navigation buttons.


 I can't locate the HTML file corresponding to my data access page

I can't locate the HTML file corresponding to my data access page

The HTML file associated with the data access page has been renamed, moved, or deleted.

Although a data access page is a database object, most of the information about a page is stored in a corresponding HTML file. You specify the name and location of this HTML file the first time you create a data access page. Microsoft Access keeps a shortcut in the Database window to the corresponding HTML file's location in your file system. You can see the HTML file's location in the Database window by resting the pointer on the name of the page.

If the HTML file has been renamed or moved, you can either restore the HTML file's original name, move the HTML file back to its original location, or change the shortcut maintained by Microsoft Access to the new name or location (Click Locate in the message box displayed when Microsoft Access cannot locate the HTML file).

Caution It's possible to have two or more pages in the same or different Microsoft Access databases or Microsoft Access projects pointing to the same HTML file. For example, you may have copied or imported the page. Although you may want to do this, it's a good idea to modify the page in page Design view in only one Access database or Access project at a time to avoid problems sharing and possibly losing design changes.

Warning If the HTML file is deleted, you cannot recover the page unless you can retrieve the HTML file from a backup copy. Learn about securing a page.


 I can't open the property sheet in Form view or Datasheet view.

I can't open the property sheet in Form view or Datasheet view.

To be able to open the property sheet when a form is open in Form view or Datasheet view, the AllowDesignChanges property of the form must be set to All Views.


 I get the message, "Couldn't find file '<file name>'." when I try to open a linked table. Why?

I get the message, "Couldn't find file '<file name>'." when I try to open a linked table. Why?

The file that contains the table you are connecting to may have moved or been renamed, or you might have lost the network connection. Verify that you can still connect to the network by contacting your system administrator or help desk. If the file has been moved or renamed, use the Linked Table Manager command that is available from the Add-ins submenu of the Tools menu to re-establish the link to the file.

If you defined the link by using a drive letter for a mapped network drive in Windows Explorer, that drive letter may have changed or may not be mapped in your current session. Redefine the link by using a universal naming convention (UNC) path, which is a reliable and consistent way for Microsoft Access to locate the data source that contains the linked table.


 I created a filter on a subdatasheet, but the filter didn't have any effect on the datasheet that displays the subdatasheet.

I created a filter on a subdatasheet, but the filter didn't have any effect on the datasheet that displays the subdatasheet.

The filter behaved correctly. When you create a filter on a subdatasheet, it only applies to the subdatasheet. To filter the records on the datasheet that displays the subdatasheet, click in that datasheet, and then create the filter.


I get the message "Wizards are not available at this time."

  • The Command Button Wizard is not available on a stand-alone data access page; that is, a page that you open without having a database open. This wizard is also not available if the page isn't bound to a table or query.

  • The List box/Drop-down List box Wizard isn't available on a stand-alone data access page. It is also not available when the page is connected to a database other than the one that's currently open.


 I get the message "The setting you entered isn't valid for this property."

I get the message "The setting you entered isn't valid for this property."

If you are entering a value in a property that has a drop-down list, select a value from the list. For information on valid values for properties that don't have a drop-down list, press F1 in the property box.

If you are entering an expression in the ControlSource property, make sure:

  • You precede the expression with an equal sign (=) or an alias for the expression. For example, both of the following are valid settings:

    =Quantity*UnitPrice

    ExtendedPrice: Quantity*UnitPrice

  • The data access page is bound to a table, query, or other record source before you attempt to enter the expression. You can't use expressions on a data access page that isn't bound.

  • The ID property of a calculated control is set to a unique name. Don't use the name of one of the fields you used in the expression or the ID of another control on the data access page.


I get an "Invalid argument" message when I type what I think is a valid value for a property.

In Windows Control Panel, the Regional Settings property is set to a region that uses a character other than a period (.) as a decimal separator. The settings for properties in data access pages require that the decimal separator be a period for all languages.


 I'm getting an error message about s_Generation.

I'm getting an error message about s_Generation.

You can get this message in a replicated database when running an append query that contains the asterisk (*) in the Field row in the design grid to select all the fields from one of the underlying tables. To avoid this problem, remove the asterisk from the design grid, and then add each field from the table's field list to the design grid.


 I'm having problems viewing a data access page in my Web browser.

I'm having problems viewing a data access page in my Web browser.

  • You may not have the correct Web browser.

    To view or interact with a data access page, you must have Microsoft Internet Explorer 5 or later installed on your computer. A page can also contain additional controls including spreadsheets, PivotTable lists, and charts.

  • Another user may have exclusive access to the Microsoft Access database or Microsoft SQL Server database that the page is connected to.

    This situation can occur when a database administrator is maintaining an Access database or SQL Server database and needs to temporarily prevent users from accessing the database, or when someone is designing objects in a shared Access database. Wait a few minutes and try to view the page again, or contact your database administrator.

  • The page, or a PivotTable list on the page, is connected to an unsupported OLE DB data source.

    An Access database or Microsoft SQL Server database is the only OLE DB data source you can connect to from a page. Either you or the author of the page needs to change the OLE DB connection to the page. To do so, in page Design view, right-click the database icon in the field list, and then click Connection.


I'm having trouble either pasting or resetting an icon image on a menu or toolbar.

The command may be set to a style that doesn't allow images. To complete the operation you were trying to perform, first change the command's style.

  1. On the View menu, point to Toolbars, and then click Customize.

  2. If it isn't already displayed, show the toolbar or menu containing the command whose style you want to change.

    How?

  3. Leave the Customize dialog box open. On the toolbar or menu, right-click the command whose style you want to change.

  4. On the shortcut menu, click Default Style or Image And Text.

Note On a menu, the Default Style setting displays a command's text and associated icon image (if it has one). On a toolbar or menu bar, the Default Style setting displays just the icon image.


 I'm having problems saving design changes to a shared Access database.

I'm having problems saving design changes to a shared Access database.

If you are sharing a Microsoft Access database in a multiuser environment, the way Access saves changes is different than if you are the only user of the Access database. More information on saving changes to a shared Access database.


 I receive an error that a table exceeds the limit of 32 indexes.

I receive an error that a table exceeds the limit of 32 indexes.

If your Microsoft Access version 2.0 database contains a table with 32 or more indexes and relationships combined, you may receive an error when you convert to Microsoft Access 2000. To resolve this error, open your database in Microsoft Access version 2.0 and modify your table design to reduce the number of relationships for the primary key table, or remove some indexes from the foreign key table. Then try to convert again.


 I receive an out-of-memory error when converting a large database.

I receive an out-of-memory error when converting a large database.

Visual Basic for Applications (VBA) has a limit of 1,082 modules per Microsoft Access database, which includes forms and reports with the HasModule property set to Yes. To fix this memory problem, reduce the number of objects in your Access database. Consider dividing your application into multiple databases. If you have modules with a large amount of code, consider using library databases to store the code.


 I sent a data access page as an e-mail message but the recipient can't read it.

I sent a data access page as an e-mail message but the recipient can't read it.

To view a data access page sent as an e-mail message, a mail recipient must read the e-mail message by using one of the following:

  • Microsoft Outlook 2000

  • Outlook Express Version 5.0

  • The combination of Microsoft Outlook 98 and Microsoft Internet Explorer 5 or later

  • The combination of Outlook Express and Microsoft Internet Explorer 5 or later

Mail recipients can contact their system administrator for more information about installing or upgrading this software.


My 16-bit API calls do not convert.

If a Microsoft Access version or 2.0 module contains 16-bit API calls, you may receive an error message when you convert the database to Microsoft Access 2000. You must change the API Declare statements in the converted database to their 32-bit equivalents.

Learn more about converting code that calls a DLL.


 My code can't compile.

My code can't compile.

When you convert a Microsoft Access version 2.0 database to Microsoft Access 2000, the conversion utility converts Access Basic code to Visual Basic for Applications (VBA) code. If any code doesn't successfully compile, you may receive an error message after you convert to Microsoft Access 2000.

In the converted Access database, open a module in Design view and click Compile All Modules on the Debug menu. As Microsoft Access compiles, it stops at any line of code that contains an error. You can then modify the syntax to resolve the compile error.

In rare instances, the conversion utility may fail to convert some syntax. For example, it may fail to modify a DoCmd statement into a DoCmd method. You may also receive compile error messages if your Microsoft Access version 2.0 database contains syntax errors. For this reason, it is a good idea to compile all of your previous-version database modules before you convert them to Microsoft Access 2000.

Microsoft Access 2000 does not support the DAO 2.5/3.x compatibility library. If you attempt to convert a database in which the code contains older versions of DAO objects, methods, and properties that depend on the DAO 2.5/3.x compatibility library, you receive a message that there were compilation errors during the conversion of the database. Before you convert the database, update the code so that it does not depend on the DAO 2.5/3.x compatibility library. If you still receive a message that there were compilation errors during conversion, open the converted database in Microsoft Access 2000, remove the reference to the missing DAO 2.5/3.x compatibility library, and then set a reference to the Microsoft DAO 3.6 Object Library. For information about changes to methods, actions, properties, syntax, and other language elements, and information about code compatibility and conversion issues, click [image] .


 My converted Microsoft Access version 2.0 report has different margins.

My converted Microsoft Access version 2.0 report has different margins.

You may encounter problems when trying to print or preview a Microsoft Access 2000 report that has been converted from Microsoft Access version 2.0, if the report has some margins set to 0. When you convert a version 2.0 report, margins are not set to 0; they are instead set to the minimum margin that is valid for the default printer. This is to prevent the report from printing data in the nonprinting region for the printer.

To resolve this problem, reduce the column width, column spacing, or number of columns in the report, so the width of the columns plus the width of the default margins is less than the width of your paper.


 My ActiveX (OLE custom) controls do not convert.

My ActiveX (OLE custom) controls do not convert.

When you convert a Microsoft Access database containing an ActiveX control to Microsoft Access 2000, you may receive an error. Microsoft Access versions 2.0 supports 16-bit ActiveX controls, whereas Microsoft Access 95 or later supports 32-bit ActiveX controls. Microsoft Access can automatically update a 16-bit control to its 32-bit version only if a 32-bit version exists and is registered on your computer.


 I'm having problems editing data in a field in Page view.

I'm having problems editing data in a field in Page view.

There are several kinds of fields that you can't edit in Page view. The following fields may display values just as regular fields do, but if you try to enter data into them, nothing happens:

  • AutoNumber fields If a field has an AutoNumber data type in a Microsoft Access database or a numeric data type with the Identity property set in a Microsoft Access project, Access automatically assigns a number to this field for each record you add. This type of field is often used as a record ID number or primary key. Access automatically fills in the field's value for you.

  • Calculated fields In an Access database, a calculated field displays values that Access calculates. They are usually based on other fields in your tables, but calculated fields are not stored in tables.

  • Locked or disabled fields If a control on a form has the Locked property set to Yes or the Enabled property set to No, it is locked or disabled for data entry.

  • Fields in a locked record If you use an Access database in a multiuser environment and a record is locked by another user, you can't edit the data in the record until the other user is finished editing the record.

  • Field in a read-only form or a locked database If the form you're using has the AllowEdits property set to No or if the underlying data is read-only or locked.

  • Fields in a grouped data access page A grouped data access page is only intended to display data.

  • PivotTable list fields A PivotTable list is only intended to display data, not to edit data. You can't edit any fields in a PivotTable list.

You may be having problems entering dates in a field with the Date/Time data type. If you are entering dates by using the slash mark (/) format, don't enter a trailing slash mark. For example, 1/3 is valid, but 1/3/ is not valid.


 The filter returns too many records.

The filter returns too many records.

If the filter is returning too many records, try the solution that best applies to your situation.

Filter By Form

  • Enter a value or expression, or pick a value from the list in other fields on the Look For tab.

  • Delete some of the alternative criteria that records can meet by deleting one or more Or tabs.

Filter By Selection

  • Select another value that you want the records to contain, and then click Filter By Selection [image] on the toolbar. Repeat this until you have just the records you want to see.

Filter Excluding Selection

  • Make sure you haven't selected values in more than one row at a time. Although you can do this, Microsoft Access interprets the filter criteria as follows: "exclude the first selected value OR the second selected value," instead of "exclude the first selected value AND the second selected value."

    Instead, select the first value you want to exclude, right-click, and then select Filter Excluding Selection. Select the next value you want to exclude, and then repeat the previous step.

  • Change the filter by pointing to Filter on the Records menu, and then clicking Advanced Filter/Sort. In the Criteria row of the design grid, change Or to And.

Filter For Input

  • Specify another value in the Filter For box, and then press ENTER. Repeat until you have the records you want.

Advanced Filter/Sort window

  • Add more fields to the design grid, and then specify criteria for them in the Criteria row.

  • Delete one or more extra rows of criteria (the Or rows) and use expressions with And instead of Or.


 The filter returns the wrong records.

The filter returns the wrong records.

If the filter is returning the wrong records, make sure you're using the correct field or fields to specify the value you're searching for or to specify other criteria, and make sure you've entered the correct value or criteria. If you're filtering on fields from linked tables, the values you use in criteria for those fields are case-sensitive — they must match the case of the values in the underlying table.

  • If you're using expressions in the Filter By Form window or Advanced Filter/Sort window, verify you're using the correct operators.

  • If you're specifying multiple criteria in the Advanced Filter/Sort window, verify you've entered it in the correct rows and columns in the design grid.


The records in my data access page aren't sorted the way that I want.

Set the DefaultSort property correctly for the group record source.


 Time or date values in my query criteria return different results.

Time or date values in my query criteria return different results.

When you convert a Microsoft Access version 2.0 database to Microsoft Access 2000, queries that contain criteria based on specific time values in Date/Time fields may return different results than they do in earlier versions. This behavior may also occur if you link tables from a Microsoft Access version 2.0 database to a Microsoft Access 2000 database. Only the time portion of Date/Time fields is affected.

Queries that contain criteria specifying dates between 1900 and 1929 may also return different results. For example, a date criteria of #01/01/15# in Microsoft Access 2.0 and 95 represents January 1, 1915; the same date criteria in Microsoft Access 97 or later represents January 1, 2015. To work around this difference, modify the data in your criteria to specify the century — for example, #01/01/1915#.


 I have defined a relationship between two tables in an Access database but I don't see a subdatasheet.

I have defined a relationship between two tables in an Access database but I don't see a subdatasheet.

When the SubdatasheetName property of a table is set to Auto and the table is on the "one" side of a one-to-many relationship or is in a one-to-one relationship, Microsoft Access automatically creates a subdatasheet. However, the value of the SubdatasheetName property can be set to a specific table or query in the database; or it can be set to None, in which case no subdatasheet will be created. To return to the default behavior, set the value of the SubdatasheetName property to Auto.


The fields on the data access page are blank.

Possible reasons include:

  • The data access page you are displaying may be a data-entry form. You can enter your data in the blank fields.

  • The data access page contains a drop-down list that determines which records to display. From the drop-down list, select a group whose records you want to see on the page.


 I can't group text boxes or other controls.

I can't group text boxes or other controls.

You must select more than one text box or other control at a time in order to create a control group.

  • Select two or more controls, and then on the Format menu, click Group. How to select adjacent controls. How to select nonadjacent or overlapping controls.


I can't ungroup selected text boxes or other controls.

You can ungroup selected text boxes or other controls only when one group at a time is selected on the form or report.

  • Click any control in the group to select the group, and then on the Format menu, click Ungroup.


 I can't see the foreign key or matching field(s) in my subdatasheet.

I can't see the foreign key or matching field(s) in my subdatasheet.

By default, Microsoft Access does not display the foreign key or matching field(s) in the subdatasheet of a table or query in a Microsoft Access database. You can temporarily show the foreign key or matching field(s) by using the Unhide Columns command (Format menu), but the next time you open the datasheet containing the subdatasheet, the column(s) will be hidden again. Hiding or showing these fields changes only the appearance of the subdatasheet; it does not modify any relationship.

In a form, you can permanently display the foreign key or matching field(s) in a subdatasheet corresponding to a subform if the subform's source object is a form.


 The Link Master Fields box is empty when I add a subdatasheet to a query in a Microsoft Access database.

The Link Master Fields box is empty when I add a subdatasheet to a query in a Microsoft Access database.

If you have just created the query, you must save it first, and then add the subdatasheet to see the fields from the query in the Link Master Fields box.


 My subdatasheet displays the same data for each row of the datasheet.

My subdatasheet displays the same data for each row of the datasheet.

In a table or query of a Microsoft Access database, you need to specify the matching field(s) between the datasheet and subdatasheet in the List Child Fields and Link Master Fields boxes in the Insert Subdatasheet dialog box (click Subdatasheet on the Insert menu). These boxes correspond to the LinkChildFields and LinkMasterFields properties of the datasheet containing the subdatasheet.

In a form, you need to specify the matching field(s) between the main form and the subform in the LinkChildFields and LinkMasterFields properties of the subform control on the main form.


 My datasheet containing a subdatasheet looks different from when I last saved it.

My datasheet containing a subdatasheet looks different from when I last saved it.

The SubdatasheetExpanded property controls the state of a subdatasheet in a table or query, or the subform control in a form. You can set the property to Yes (all rows expanded) by clicking Expand All on the Subdatasheet submenu on the Format menu or No (all rows collapsed) by clicking Collapse All on the Subdatasheet submenu on the Format menu. Clicking one or more expand indicators to show subdatasheets for one or more rows in the datasheet doesn't change the SubdatasheetExpanded property; even if you click all expand indicators to show all subdatasheets, the property is still set to No (all rows collapsed).


Hide duplicate values that appear in the same group

Set the HideDuplicates property to Yes for the text box that displays the values you want to hide.

How?


Print the group header on the same line as the first detail record

You can design a report that uses a block layout in one of the following ways:

  • For a new report, use the Report Wizard to create the report and choose Block as the layout.

    How?

  • For an existing report, modify the report's design by hiding duplicate data.

    How?


Print records in a report in the same order as in its underlying record source

Set the sort order for a report in the Sorting And Grouping box.

How?


The records in the groups on my report aren't sorted

You must specify a sort order for the records in a group in the Sorting And Grouping box in report Design view. For example, if you want to sort the orders that were shipped each day by Order ID, group on Shipped Date and sort on Order ID.

How?


 My report prompts me for unexpected parameters.

My report prompts me for unexpected parameters.

Make sure that all field names used in the following areas of the report's design are spelled correctly and match field names in the underlying table or query:

  • ControlSource property of any bound controls

  • Field/Expression column in the Sorting And Grouping box

  • Expressions in controls or in the Sorting And Grouping box

    Also, make sure that any aggregate functions reference field names in the underlying table or query, not control names. For more information, click [image] .


 Sort records correctly for my language

Sort records correctly for my language

In a Microsoft Access database (.mdb), set the sort order for the database to the correct language in the Options dialog box.

How?


 I get the message "The expression is not valid."

I get the message "The expression is not valid."

You attempted to type an expression that includes the name of a field that is not in the data definition of the page. Any fields that you reference in an expression on a data access page must be in that page's data definition. To add a field to the page's data definition, drag the field from the field list to the data access page. If you don't want to show the values in the field on the page, you can hide or delete the control bound to the field. However, even if you delete the control, a field referenced in an expression remains part of the page's data definition.


I get the message "Undefined function in an expression."

You've bound a control on a data access page to a calculated field that uses a function that isn't supported on data access pages. See a list of functions that you can use in controls on data access pages and in the queries underlying them.


 I get the message "The DefaultSort property is invalid."

I get the message "The DefaultSort property is invalid."

In the DefaultSort property box, type the name of the field or fields you want to sort on. Separate the names with a comma. You can follow each name with a space and the keyword ASC or DESC. For example, type OrderDate DESC, OrderID ASC. If you don't specify the order, Microsoft Access sorts in ascending order.

If the control you want to sort on is bound to an expression, you must type the alias of the control as displayed in its ControlSource property. For example, if the ControlSource property of the control you want to sort on is set to GroupOfExtendedPrice: ExtendedPrice, type GroupOfExtendedPrice in the DefaultSort property.


 I want to open an HTML file in Access, but it opens in another Office program.

I want to open an HTML file in Access, but it opens in another Office program.

In the Open dialog box (File menu), when you select a Hypertext Markup Language (HTML) file (also called a Web page) and click Open or double-click the file, the file opens in the program that created the file. For example, if you attempt to open an HTML format file that was created in Microsoft Word, the file opens in Word — not in Microsoft Access 2000 as a data access page. To open an HTML file that was created in another Office program as a data access page, right-click the file in the Open dialog box, and then click Open in Microsoft Access on the shortcut menu.


The New Database Sort Order box in the Options dialog box no longer lists a language setting.

Some languages are now included in the General sort order setting, although they used to be listed separately in the New Database Sort Order box on the General tab in the Options dialog box (Tools menu). The general sort order includes the following languages: Afrikaans, Albanian, Arabic, Basque, Bulgarian, Byelorussian, Catalan, Dutch, English, Faeroese, Farsi, German - Standard, Greek, Hebrew, Hindi, Indonesian, Italian, Malay, Portuguese, Russian, Serbian, Swahili, and Urdu.


 The Open dialog box doesn't list the file I'm looking for.

The Open dialog box doesn't list the file I'm looking for.

  • In the Open dialog box, type the name of the file in the File name box, click Tools, and then click Find. Select the Search subfolders check box, and then click Find Now.

  • In the Open dialog box, make sure you have the correct file type selected in the Files of type box.

  • Make sure the entries in the Find dialog box under Define more criteria are appropriate for the files you're searching for. To clear all current search criteria except the file location and to reset to the default file type, click New Search.

  • Make sure you're looking on the correct drive and in the correct folder.

  • If you don't know the folder name, you can search all folders and subfolders on the specified drive. In the Open dialog box, click Tools, click Find, and then select the Search subfolders check box.

  • In the Open dialog box, you can search multiple paths by typing the paths in the File name box. Separate each path with a semicolon for example, type c:\House finances;c:\My work documents.

  • If you're looking for a file on the network and the network drive doesn't appear in the Look in box in the Open dialog box, click Tools, and then click Map Network Drive. In the Drive box, click the drive letter you want to use to connect to the network. In the Path box, enter the path where the file is located on the network. You can also look for files on a network drive if your network supports the UNC. Just type the UNC path in the File name box in the Open dialog box for example, type \\plans\documents.


The password I typed to open a file doesn't work.

  • Passwords are case-sensitive (uppercase and lowercase letters must match exactly). Check to see whether CAPS LOCK is turned on.

  • You might have misspelled the password. Try to type it again.


Buttons are missing from the record navigation toolbar.

The designer of the data access page removed the buttons for that page or group.


Add a matching record in the other table

You need to open the table that the wizard checked for unmatched records (the second table you specified in the wizard), and then add a matching record.

How?


All of my records show up in my subform -- they don't change when I move from record to record in the main form.

All of my records show up in my subform — they don't change when I move from record to record in the main form.

You need to link your main form and subform using the LinkChildFields and LinkMasterFields properties. For information on linking a main form and a subform, click [image] .

If you've already set the LinkChildFields and LinkMasterFields properties and the subform still doesn't work, make sure that you aren't using fields that have been renamed or deleted. Also make sure that you've spelled the field names correctly and that you're using the actual field names, not the control names specified in the Name property.

Note Under certain circumstances, Microsoft Access will automatically link a main form and a subform when you use a wizard to create the subform. For more information, click [image] .


 The append query appended data to or from the wrong fields.

The append query appended data to or from the wrong fields.

To select the fields whose data you want to append:

Add the following fields to the query design grid for your append query:

  • The fields you want to append.

  • The fields you want to specify criteria for.

  • The field corresponding to the primary key field of the table you're appending records to.

To select the fields to which you want to append data:

  • In the Append To cell of the fields whose data you want to append, click the name of the field you want to add the data to.

Note If you added the asterisk (*) in the Field cell, select the asterisk in the Append To cell. All the field names in both tables must be exactly the same. You can't specify criteria for selecting records in the column that contains the asterisk, but you can specify criteria in a separate column.


 My form is blank. Why can't I see my data?

My form is blank. Why can't I see my data?

A form may appear blank for any of the following reasons:

  • The form may not be bound to an underlying record source. To bind a form to an underlying record source, open the form in Design view, and then double-click the form selector to open the property sheet. In the RecordSource property box, click a record source in the list or, if the record source is a query, click the Build button [image] to open the Query Builder.

  • The form may be bound to an underlying record source that doesn't have any data. Check the underlying record source to make sure that it has data.

  • The form may be based on a query that doesn't return any data. To see if the query returns data, double-click the form selector to open the form's property sheet, click the Build button next to the RecordSource property box to open the Query Builder, and then click View View object in the Query Builder.

  • The form may be open in Data Entry mode. When a form is open in Data Entry mode, it displays a blank record so that you can add data. To show all the records, click the Remove Filter/Sort command on the Records menu.

  • The form header or form footer may be so large that there's no room for the detail section.


 Why isn't a value that I type in the combo box on a form added to the list?

Why isn't a value that I type in the combo box on a form added to the list?

To automatically add a value to the list on a form, you need to write an event procedure and attach it to the combo box's OnNotInList property.

Note You must set the LimitToList property to Yes to use the NotInList event.


I'm getting the message "Can't bind name name."

You may encounter this message if you didn't explicitly declare in the Query Parameters dialog box the parameters used for a crosstab query or a query that a crosstab query or chart is based on. To solve the problem, do the following:

  1. In the query that contains the parameter, specify the parameter and its data type in the Query Parameters dialog box. For more information, click [image] .

  2. In the same query, set the ColumnHeadings property. For more information, click [image] .


 I can't change the format of the labels on the chart in my form or report.

I can't change the format of the labels on the chart in my form or report.

If you use Microsoft Graph to change the format of labels on your chart's axes, the changes are overwritten when the chart is updated. To make these changes permanent, you must modify the query specified by the chart's RowSource property.

  1. Open the form in form Design view or report in report Design view.

  2. Make sure the chart is selected, and then click Properties [image] .

  3. Click Build [image] to the right of the RowSource property box.

  4. In the query, replace the name of the field you want to format with the field name and the Format function.

    For example in a Microsoft Access database, you can change it to Format([OrderDate],"YY") to change how the date appears on your chart. For more information about the Format function, click [image] .

  5. Close the query and save the changes.

  6. Switch to Form view or Print Preview to view the changes.

Note Not all Microsoft Access custom formats work with Microsoft Graph.


 Why can't I display form headers and form footers in my subform datasheet?

Why can't I display form headers and form footers in my subform datasheet?

A form or subform viewed in Datasheet view doesn't display a form header and footer even if you've included them in Design view. You can display a form header and footer in a subform and make it look like a datasheet by sizing the detail section of the form to the size of a single row and setting the DefaultView property of the subform to Continuous Forms. For more information, click [image] .


 Why can't I edit data in my form?

Why can't I edit data in my form?

You may not be able to edit data in a form for any of the following reasons:

  • The form was created as a read-only form. If the AllowDeletions, AllowAdditions, and AllowEdits properties of the form are set to No, you won't be able to make changes to the underlying data.

  • The Locked property for one or more controls may be set to Yes.

  • Someone else may be using the form at the same time, and the RecordLocks property for the form is set to All Records or Edited Record. You'll see the locked recorder indicator [image] in the record selector if this is the case. Wait awhile, and try again.

  • You may be trying to edit data in a calculated control. A calculated control displays the result of an expression. The data displayed in a calculated control isn't stored, so it can't be edited.

  • The underlying query or SQL statement for the form may not be updatable. For more information on which types of queries are updatable in a Microsoft Access database (.mdb), click [image] . For information on which types are updatable in a Microsoft Access project (.adp), click [image] .


When I double-click a linked or embedded object, I get a message saying the file can't be opened.

Microsoft Access displays this message when it can't open the source file for an OLE object. Check to make sure that:

  • The application needed to edit the file is installed on your computer.

  • You have enough memory to run the source application. Close other applications to free up memory.

  • If the application that you're trying to open is already running, make sure that it doesn't have any open dialog boxes.

  • If it's a linked object, make sure that someone else doesn't already have it open.

  • If it's a linked object on a form, make sure that the name of the source file hasn't changed or that the source file hasn't been moved. To see the name of the original file, click the object, and then click OLE/DDE Links on the Edit menu. The original file name appears in the Links box. If the file has been renamed or moved, click the link in the Links box, and then click Change Source to reconnect the link.


 I can't open or update a linked Microsoft Visual FoxPro or dBASE table. Why?

I can't open or update a linked Microsoft Visual FoxPro or dBASE table. Why?

  • If you link a .dbf file and associate an index (.idx, .cdx, .ndx, or .mdx) file, then Microsoft Access needs the index file to open the linked table. If you delete or move Microsoft Visual FoxPro or dBASE index files or the information (.inf) file Microsoft Access creates, you won't be able to open the linked table.

  • If you link a Visual FoxPro or dBASE table with a memo field, then Microsoft Access needs the associated memo (.dbt) file to open the linked table. If you delete or move this file, you won't be able to open the linked table.

  • When you use Microsoft Access to update the data in your .dbf file, it updates the index files to reflect your changes. If you use Visual FoxPro or dBASE to update data, you must update the associated indexes within Visual FoxPro or dBASE as well. Microsoft Access can't use a linked table if the indexes you specified aren't current.

  • You can't update a Visual FoxPro or dBASE table if its data (.dbf) or index (.idx, .cdx, .ndx, or .mdx) files are set to read-only. To check this, use My Computer or Windows Explorer to display the folder where the files are located, right-click a file, click Properties, and then click the General tab. If the Read-only check box is selected, clear it and then click OK.

  • If your Visual FoxPro or dBASE tables are stored on a read-only drive or CD-ROM, Microsoft Access can't create an .inf file in the same folder as the .dbf files, and you won't be able to link the tables. To link a table on a read-only drive, you must specify the path to a read/write drive where you want Microsoft Access to create the .inf file in the Windows Registry. For more information, click [image] .

  • To link (read/write) a dBASE 7 table, you must have the Borland Database Engine (BDE) version 4.x or later installed on your computer. If you do not have BDE 4.x or later installed, you can obtain it by installing dBASE 7 or Delphi. If you have an older version of the BDE that does not support dBASE 7 file format then you can upgrade your engine from the Borland World Wide Web site. Alternatively, if you do not have the BDE installed on your computer, you can still link to dBASE III, IV and 5.0 file format.


 I can't open or update a linked Paradox table. Why?

I can't open or update a linked Paradox table. Why?

  • If you link a Paradox table that has a primary key, then Microsoft Access needs the associated index (.px) file in order to open the linked table. If you link a Paradox table with a Memo field, then Microsoft Access needs the associated memo (.mb) file in order to open the linked table. If you delete or move these files, then you won't be able to open the linked table.

  • If you link a Paradox table that doesn't have a primary key, then you won't be able to update data in the table using Microsoft Access. If you want the table to be updatable, define a primary key for the table in Paradox.

  • OLE objects stored in a linked or imported Paradox table can't be opened from within Microsoft Access.

  • You can't update a table if its data (.dbf) or index (.idx, .cdx, .ndx, or .mdx) files are set to read-only. To check this, use My Computer or Windows Explorer to display the folder where the files are located, right-click a file, click Properties, and then click the General tab. If the Read-only check box is selected, clear it and then click OK.

  • You can't update a Paradox table if its data (.db) or index file (.px) is set to read-only. To check this, use My Computer or Windows Explorer to display the folder where the files are located, right-click a file, click Properties, and then click the General tab. If the Read-only check box is selected, clear it and then click OK.

  • To link (read/write) a Paradox 8.0 table, you must have the Borland Database Engine (BDE) version 4.x or later installed on your computer. If you do not have BDE 4.x or later installed, you can obtain it by installing Paradox 8.0 or Delphi. If you have an older version of the BDE that does not support Paradox 8 file format then you can upgrade your engine from the Borland World Wide Web site. Alternatively, if you do not have the BDE installed on your computer, you can still link (read-only) to Paradox 3.x, 4.x, and 5.0 tables.

  • When you link a Paradox table that resides on a server and is shared by multiple users, you must set the ParadoxNetPath key in the Windows Registry to the path to the Paradox.net or Pdoxusrs.net file. Additionally, if you use Paradox version 4.x for sharing data in your workgroup, you must set the ParadoxNetStyle key to "4.x." For more information on making these settings, click [image] .

  • If you are using Microsoft Access to link Paradox data on a network while users of Paradox are using the data, you must be sure to define all three ParadoxUserName, ParadoxNetPath, and ParadoxNetStyle settings in the registry. Use the ParadoxUserName setting to specify a unique user name for accessing the shared Paradox data. Use the ParadoxNetPath setting to specify the full path to the folder containing the Paradox.net file (for Paradox 3.x) or the Pdoxusrs.net file (for Paradox 4.x and 5.0). The ParadoxNetPath setting (including the drive letter) must be consistent for all users sharing a particular database. Use the ParadoxNetStyle setting to specify the network locking style to use when accessing Paradox data. Possible values are "3.x" for Paradox 3.x and "4.x" for Paradox 4.x and 5.0. For more information, see the Paradox Network Administrator's Guide. For more information on making these settings, click [image] .


 I can't open or update a linked SQL table. Why?

I can't open or update a linked SQL table. Why?

  • Microsoft Access requires a unique index to update, delete, or insert data in a linked SQL table or view. When you link a Microsoft SQL Server updatable view, or an SQL database table that doesn't have a unique index, Microsoft Access asks you to select one or more fields to generate a unique index. However, Microsoft Access doesn't test to make sure that the field or fields you selected uniquely identify each record. If there are duplicates in the index Microsoft Access builds, you won't be able to update those records.

    If you think that the field or fields you selected did not create a unique index, delete the link to the table, link it again, and then select the appropriate field or fields to establish a unique index.

    Alternatively, you can create an index within Microsoft Access by creating a data-definition query, by using the Create Index statement. Again, be sure to select a field or combination of fields that will uniquely identify each record. If the index that is generated contains any duplicate values, all updates to the table will fail. To delete the index, use another data-definition query. For more information on creating such a data-definition query, click [image] .

  • If you link an SQL table that has its own unique index, and that index is defined for a field that is a floating-point number, the table might not be updatable. Because servers vary in how precisely they handle floating-point data, precision loss can sometimes occur. The actual difference is usually slight enough to be inconsequential, but if the data forms part of the SQL table's bookmark, affected records might appear to Microsoft Access to be deleted.

  • If you encounter other errors while importing, linking, or using an SQL database table, there might be a problem with your account on the SQL database server or with the database itself. If you can't access an SQL database table, contact the SQL database administrator.


 I can't put the columns on my chart in a form or report in the order I want.

I can't put the columns on my chart in a form or report in the order I want.

To make your data appear in a different order, you can modify the query specified by the chart's RowSource property.

  1. Open the form in form Design view or report in report Design view.

  2. Make sure the chart is selected, and then click Properties [image] .

  3. Click Build [image] to the right of the RowSource property box.

  4. In the query, put the fields you want sorted, left to right, in the order you want them sorted.

  5. Close the query and save the changes.

  6. Switch to Form view or Print Preview to view the changes.


I want to refer to a column in the list box or combo box on a form or report other than the bound column.

To refer to a column other than the bound column, use the Column property. The Column property is zero-based. For example, to refer to the second column in the combo box called SuppliersCombo on the Products form, use this syntax:

Forms![Products]![SuppliersCombo].Column(1)


 I can see data from only one table. How can I see data from other tables?

I can see data from only one table. How can I see data from other tables?

To see data from more than one table, you must base your form on a query that brings the data from the tables together. To create a multiple-table query without closing the form, do the following:

  1. In form Design View, double-click the form selector to open the form's property sheet.

  2. Click in the RecordSource property box, and then click the Build button [image] next to the property box to open the Query Builder.

  3. In the Query Builder, add the tables and fields you want to include in the underlying query, and then close the Query Builder.

Microsoft Access updates the RecordSource property to use the query you created.

For information on adding tables in the Query Builder in a Microsoft Access database (.mdb), click [image] . For information on adding fields, click [image] .

For information on adding tables in the Query Builder in a Microsoft Access project (.adp), click [image] . For information on adding fields, click [image] .

Note You can also create a multiple-table form by using a wizard. For more information, click [image] .


I can't select a value in the list box, drop-down list box, or combo box.

You may have misspelled the field name in the ControlSource property box. You use the RowSource (forms and reports) or the ListRowSource (data access pages) property to specify the items that make up the list. When you click an item in the list, Microsoft Access needs to know where to store the value that you selected. You use the ControlSource property to specify where the values are stored.


I can't type a new value in the combo box on a form.

The LimitToList property is set to Yes. Set the LimitToList property to No so that you can type new values in the combo box. If the column displayed in the text box portion of the combo box isn't the bound column, Microsoft Access automatically sets the LimitToList property to Yes.


I can't update the data in my crosstab query.

Data in a crosstab query is not updatable. For information about when you can update data from a query, click [image] .


I can't update the data in my query.

There are some types of queries or certain fields in queries that aren't updatable. For information on when you can update data, click [image] .


 The chart in my form or report appears dimmed or blank.

The chart in my form or report appears dimmed or blank.

The RowSource property for a chart may be invalid.

  1. Open the form in form Design view or report in report Design view.

  2. Make sure the chart is selected, and then click Properties [image] .

  3. Make sure the RowSource property box contains a valid value.

    For information about the RowSource property, click [image] .

  4. Switch to Form view or Print Preview to view the changes.

If the chart is record-bound, the query in the chart’s RowSource property may not contain a field that matches the fields in the LinkChildFields and LinkMasterFields properties of the form or report. Learn about record-bound charts.


 I change the chart in my form or report, but the changes aren't retained.

I change the chart in my form or report, but the changes aren't retained.

A chart is made up of information from the following places, in order of precedence:

  • The data in the underlying table or other record source.

  • The chart's RowSource property

  • The Microsoft Graph application

Microsoft Access regenerates the chart each time you print or preview the chart, or switch to Form view. Therefore, changes that you make using Microsoft Graph might be overwritten by the underlying data or the RowSource property.

Keep the following in mind when you change your chart:

  • Changes to the underlying data (such as the format of the data) have precedence over other changes. However, if the RowSource property setting contains a calculated field, such as =Format([StartDate],"MMM"), the format is determined by the result of the calculation, not by the underlying data.

  • Changes in the RowSource property, such as changes to the chart's title and labels, can be overwritten by changes in the underlying data.

  • Changes you make using Microsoft Graph, such as changes based on the data, can be overwritten by changes you make in the underlying table or other record source or in the RowSource property.

For information about the RowSource property, click [image] .


The wrong field values are showing as row or column headings.

Verify that the field whose values you want to use as column headings is in the query design grid with Column Heading in the Crosstab cell, and that the field or fields whose values you want to use as row headings are in the query design grid with Row Heading in the Crosstab cell. To change the value in a Crosstab cell, click the cell, and then click a value from the list. If you want to display only certain values as column headings, set the query's ColumnHeadings property. For more information, click [image] .


The columns the query retrieves are wrong.

What best describes the problem?

The query retrieves too many columns.

The query retrieves too few columns.

The query retrieves the wrong columns.


 I added a check box, toggle button, or option button to an option group, but the option group doesn't work.

I added a check box, toggle button, or option button to an option group, but the option group doesn't work.

You may have placed the control outside the option group. When you add a check box, toggle button, or option button to an option group, Microsoft Access highlights the option group to show that the control will become part of the option group. If the option group isn't highlighted, you're probably placing the control too close to the edge of the option group.


I can't display my records again after using the Data Entry command.

  • On the Records menu, click Remove Filter/Sort.


 The delete query deleted records from the wrong table.

The delete query deleted records from the wrong table.

Make sure the delete query includes:

  • The table you want to delete records from. Drag the asterisk (*) from the field list for that table to the query design grid.

  • The field(s) you want to specify criteria for. Drag the field you want from the table's field list to the design grid.

In the query design grid, From or Where is displayed in the Delete row. From is displayed in the Delete cell of the table you'll delete records from, and Where is displayed in the Delete cell of the field(s) you specify criteria for.


 My picture becomes distorted on a form or report when I size it.

My picture becomes distorted on a form or report when I size it.

To keep a picture's proportions when you size it, use the PictureSizeMode property (for background pictures) or the SizeMode property (for bound object frames, unbound object frames, and image controls). If the picture is a bitmap, it's best to use the Zoom setting rather than the Stretch setting. You should also consider using a metafile rather than a bitmap since you can size metafiles without causing distortions. For information on using metafiles rather than bitmaps, click [image] .


#Error? appears in the combo box or the combo box is blank.

On a form or report, you probably entered an inappropriate setting in one of the following properties: RowSource, ControlSource, BoundColumn, ColumnWidths, ColumnCount. To read about these and other properties that you can use in a list box or combo box, click [image] .


 #Error? or #Name? appears in a control on a form or report.

#Error? or #Name? appears in a control on a form or report.

#Error? or #Name? may appear in a control for a number of reasons. To correct the problem, do the following:

  • Make sure that the field specified in the control's ControlSource property hasn't been removed from the underlying table or other record source.

  • Check the spelling of the field name in the control's ControlSource property.

  • If you specified an expression in the control's ControlSource property, make sure that there is an equal sign preceding the expression.

  • Make sure that there are brackets around references in expressions to control or field names that include spaces. For example, to subtract a Shipped Date field from a Required Date field, enter the following expression: =[Required Date]-[Shipped Date].

  • If you are using one of the built-in functions, make sure that you're using the right number of arguments, that the arguments are in the right order, and that you haven't left out any necessary punctuation. To determine the correct syntax to use, see the Help topic for the function you're using.

  • If you are referring to another control, make sure that you're using the correct syntax. For more information on referring to controls, click [image] .

  • Make sure that there isn't a circular reference to a control. For example, if you specify MyControl in the Name property of a control, and then type =[A]+[B]+[MyControl] in the ControlSource property box for the control, Microsoft Access can't process the expression.


I'm seeing unexpected results when I try to refer to a column in a list box or combo box.

You use the Column property to refer to a column in a list box or combo box. The Column property might produce unexpected results for any of the following reasons:

  • You haven't supplied an index number to the Column property. The index number identifies the column you're referring to. For example, Column(0) refers to the first column in a list box or combo box.

  • You've specified an index number for the wrong column. Remember that index numbers for the Column property start at zero. Column(0) refers to the first column, Column(1) refers to the second column, and so on.

  • You're performing a numeric calculation directly on the value returned by the Column property. Because the Column property returns a text value, you must convert it to a numeric value before performing a numeric calculation. For example, the following expression uses the CCur function to convert the value returned by the Column property to a currency value before multiplying it by the value of the Quantity field:

    [Quantity] * CCur([PriceListBox].Column(1))

For more information about referring to a column in a list, click [image] .


 I'm seeing unexpected results when I try to combine (concatenate) control or field values, variables, or text in an expression.

I'm seeing unexpected results when I try to combine (concatenate) control or field values, variables, or text in an expression.

Concatenating control or field values or text in an expression might produce unexpected results for any of the following reasons:

  • You're referring to a control or field that has the same name as the current control, creating a circular reference. Change the name of the field or control.

  • You're referring to a control or field using a name that is misspelled or typed incorrectly. Verify that it's entered correctly.

  • You're referring to a control or field that has the same name as a property. Use the full identifier for the control or field. For more information about identifiers in expressions, click [image] .

  • Microsoft Access isn't evaluating the expression correctly because part of the expression must be surrounded by brackets ( [ ] ) or single (') or double (") quotation marks. Check to see whether bracket or quotation mark characters are required.

For more information about concatenating values in text expressions, click [image] .


I'm seeing unexpected results when I enter a date value in an expression.

Microsoft Access can produce unexpected results if you enter a date value in an expression without surrounding it with number signs (#). For more information about entering expressions, click [image] .


 I'm seeing unexpected results when I try to perform operations on fields that have blank values.

I'm seeing unexpected results when I try to perform operations on fields that have blank values.

Many operations might produce unexpected results if they use an expression that refers to a field that has blank (Null) values. For example, the DCount or DSum functions might produce unexpected results if they use criteria expressions that refer to a field with Null values.

To correct this problem, you can either:

  • Pass field values to the Nz function in the expression. When the Nz function evaluates a Null value, the function returns zero or a zero-length string. For more information about the Nz function, click [image] .

  • Use the IIf and IsNull functions to test whether a value is Null, and then return an appropriate value. For more information about the IIf function, click [image] . For more information about the IsNull function, click [image] .

For more information about setting field properties that determine how blank fields are handled, click [image] .


How do I convert text so that the first letter is capitalized and the rest is lowercase?

You can convert text so that the first letter is capitalized and the rest is lowercase by using the StrConv function.


 I'm seeing unexpected results when I try to refer to a subform or subreport property or control.

I'm seeing unexpected results when I try to refer to a subform or subreport property or control.

Microsoft Access can produce unexpected results if you refer to a subform or subreport property or control by using an incorrect identifier.

To refer to a subform or subreport property, you must type a full identifier for the form or report by using the Form or Report property of a subform or subreport control. For example, the following identifier refers to the Visible property of the Orders Subform subform:

Forms![Orders]![OrdersSubformControl].Form.Visible

In this example:

  • Forms![Orders]![OrdersSubformControl] refers to the subform control that contains the subform.

  • Forms![Orders]![OrdersSubformControl].Form refers to the subform itself. You must specify the Form property to refer to the subform itself or one of its properties.

In contrast, to refer to a control on a subform or subreport, or one of the control's properties, you don't have to use the Form or Report property. For example, the following identifier refers to the Visible property of the Discount control on the Orders Subform subform:

Forms![Orders]![OrdersSubformControl]![Discount].Visible

For more information about referring to a form, report, subform, or subreport in an expression, click [image] .

For more information about referring to the value of a control or property in an expression, click [image] .

For more information about identifiers in expressions, click [image] .


I created a filter on a subform, but the filter didn't have any effect on the main form. Why not?

The filter behaved correctly. When you create a filter on a subform, it only applies to the subform. To filter the records on the main form, click the main form, and then create the filter.


 I get prompted for a parameter when I don't expect it.

I get prompted for a parameter when I don't expect it.

If you get prompted to type parameters when you attempt to run a query, report, or data access page, and you don't expect this prompt, one of the following might apply:

  • You deleted a parameter from the query design grid but not from the Query Parameters dialog box.

  • You renamed or misspelled a field in the query, report, or data access page but not in the query's underlying table(s).

  • You have a field that refers to a calculated field. If a field in the query performs a calculation based on the calculated value, make sure the Show check box is checked for the calculated field in the query design grid.


The column headings aren't in the order I want, or I want to exclude some of them.

You can set the query's ColumnHeadings property to specify which column headings are displayed and in what order you want them to appear. For more information, click [image] .


 I want to delete duplicate records after using the Find Duplicates Wizard.

I want to delete duplicate records after using the Find Duplicates Wizard.

You can delete the duplicate record or the original directly in query Datasheet view by clicking the record, and then clicking Delete Record [image] on the toolbar.

If you want Microsoft Access to delete all the duplicates and keep the original records automatically, don't use the Find Duplicates Wizard or convert a Find Duplicates query to a delete query. For more information, click [image] .


 I clicked the button to edit the PivotTable form, but Microsoft Excel won't let me make any modifications. modifications. modifications. modifications.

I clicked the button to edit the PivotTable form, but Microsoft Excel won't let me make any modifications.

Before you can modify a PivotTable form, you need to update the data that's displayed in it.

  1. Open the PivotTable form in Form view.

  2. Click the Edit PivotTable Object button.

  3. On the Data menu in Microsoft Excel, click Refresh Data.

You should now be able to modify the PivotTable form.

Note When you're editing the PivotTable form, you are using Microsoft Excel and can get Microsoft Excel Help on PivotTable reports. If you don't find the answer you need in the Microsoft Excel Help topics, you can use Microsoft Access Help when the PivotTable form is open in Form view, in Microsoft Access.


If I open Microsoft Excel without going through the form containing the PivotTable form, I can't find the PivotTable form.

If I open Excel without going through the form containing the PivotTable object, I can't find the PivotTable object.

A PivotTable object is an embedded object that is stored in Microsoft Access. If you want to work with the PivotTable object by using Microsoft Excel's PivotTable Report Wizard, click the Edit PivotTable Object button on the Microsoft Access form. Once you have the PivotTable object open in Microsoft Excel, you can save a copy of it as a Microsoft Excel PivotTable report. However, the PivotTable report in Excel and the PivotTable object on the Microsoft Access form aren't linked. If you change the PivotTable object in Access, the changes won't be reflected in the PivotTable report in Excel, and vice versa, so the data will be inconsistent.


 I'm getting the message "Query contains ambiguous outer joins."

I'm getting the message "Query contains ambiguous outer joins."

This can occur when you try to run a query with certain combinations of joins. For an example of what causes the conflict and information on how to resolve it, search the Microsoft Knowledge Base for article Q124937, "Explanation of 'Ambiguous outer joins' error message." For information on accessing the Knowledge Base or other online technical resources, click [image] .


 Errors are reported when I append a spreadsheet or text file. Why?

Errors are reported when I append a spreadsheet or text file. Why?

In a Microsoft Access database, for most records that cause an error, Microsoft Access adds a row to a table called Import Errors. To view the complete list of errors that were encountered, open the Import Errors table in the Database window. For more information on the Import Errors tablemessages, click [image] .

In a Microsoft Access project, no Import Errors table is created. Consider using Data Transformation Services (DTS), which can be a faster and more flexible way to import and transform data. For more information, see the Microsoft SQL Server documentation.

Appended records must be compatible with the existing table's structure: Each field must have the same data type as the corresponding field in the destination table, and the fields must be in the same order (unless you're using the first row of the file as field names, in which case the field names must match).

If you suspect that the problem is with the data that you're appending, edit your spreadsheet or text file, and then import again. Alternatively, you might need to change the destination table itself. You can reorder the fields, change data types, run an update query (to reformat or recalculate the data, for example), or run a make-table query (to split one field into two fields or combine several fields into one field, for example).

Here are the most typical reasons for encountering errors:

  • The field names in the spreadsheet or text file do not match the field names in the table that you are appending to.

  • The data in a field is inappropriate for the data type of the destination field. For example, the destination field has the Date/Time data type in an Access database — or the datetime data type in a Microsoft Access project — but the data contains a text value that Microsoft Access can't recognize as a date or time.

  • The data in a numeric field is too large for the field size of the destination field. For example, the destination field has the FieldSize property set to Byte in an Access database ? or a data type of tinyint in an Access project — but the data contains a value greater than 255.

  • Records that you are importing contain duplicate values that cannot be stored in the primary key of the destination table or in any field in the table that has the Indexed property set to Yes (No Duplicates) in an Access database or that has the option Ignore Duplicate Key in an Access project.

  • One or more rows in the text file or spreadsheet contain more fields than the destination table.

  • The date fields that are imported from a Microsoft Excel spreadsheet are off by four years. Microsoft Excel for Windows uses the 1900 Date System, in which serial numbers range from 1 to 65,380, which correspond to the dates January 1, 1900 through December 31, 2078. Whereas, Microsoft Excel for the Macintosh uses the 1904 Date System, in which serial numbers range from 0 to 63,918, which correspond to the dates January 1, 1904 through December 31, 2078.

    Before importing the data, change the date system for the Microsoft Excel spreadsheet or, after importing the data, perform an Update Query using the expression [date field name] + 1462 to correct the dates. For more information on the Microsoft Excel date system, see the Microsoft Excel documentation.


 Errors are reported when I import a spreadsheet or text file. Why?

Errors are reported when I import a spreadsheet or text file. Why?

In a Microsoft Access database, for most records that cause an error, Microsoft Access adds a row to a table called Import Errors. To view the list of errors that were encountered, open the Import Errors table in the Database window. For more information on the Import Errors table error messages, click [image] .

In a Microsoft Access project, no Import Errors table is created. Consider using Data Transformation Services (DTS), which can be a faster and more flexible way to import and transform data. For more information, see the Microsoft SQL Server documentation.

Here are the most typical reasons for encountering errors:

  • In a field, there is data that can't be stored in the data type that Microsoft Access has assigned to that field. For example, you might have accidentally included a text value in a field that should only contain numbers or dates. Or perhaps a row in your text file or spreadsheet contains summary information or extraneous characters.

    If you think Microsoft Access assigned the correct data type for this field, edit your text file or spreadsheet to correct errors, and then import again. Otherwise, import again and specify the appropriate data type.

  • Microsoft Access has assigned an incorrect data type to a field. Microsoft Access assigns the data type for each field based on the data in the first row it imports. For example, if a field that contains mostly text values has a number in the first row, then, in an Access database, Access assigns the Number data type. In an Access project, Access assigns a data type of numeric data. In both cases, Access cannot import the rest of the records.

    Import again and specify the appropriate data type when importing.

  • One or more rows in the text file or spreadsheet contain more fields than the first row. For example, the second row in a file might have an extra field delimiter character that is followed by a value that Microsoft Access can't fit in the new table.

    Edit your text file or spreadsheet so that each row has the same number of fields, and import again.

  • The date fields that are imported from a Microsoft Excel spreadsheet are off by four years. Microsoft Excel for Windows uses the 1900 Date System, in which serial numbers range from 1 to 65,380, which correspond to the dates January 1, 1900 through December 31, 2078. Whereas, Microsoft Excel for the Macintosh uses the 1904 Date System, in which serial numbers range from 0 to 63,918, which correspond to the dates January 1, 1904 through December 31, 2078.

    Before importing the data, change the date system for the Microsoft Excel spreadsheet, or, after importing the data, perform an Update Query by using the expression [date field name] + 1462 to correct the dates. For more information on the Microsoft Excel date system, see the Microsoft Excel documentation.


I need help specifying criteria.

What do you need help with?

Understanding criteria expressions

Finding records that meet one criteria and/or another criteria for the same or different fields

Finding records containing values between, greater or less than, equal to, or not equal to specified values

Finding records with values that start or end with certain characters or words, or contain certain characters or words

Finding records that don't match a value

Finding records that contain a value, not blanks (Null values)

Finding records that don't contain a value

Finding records that contain the current date

Finding records that contain one value from a list of possible values

Limiting records involved in a calculation

Extract part of a text field

Extract part of a date field

Resolving a type mismatch problem


 I'm getting a key violation message.

I'm getting a key violation message.

A key violation occurs if:

  • You attempt to run a query that appends, deletes, or updates records in a way that violates the rules of referential integrity for related tables.

  • Your query attempts to append or update records that contain primary key values that already exist in the destination table.

If you run such a query, it will not modify the records that cause the key violation.

To modify records in a way that will violate referential integrity, you can break the relationship between the affected tables or turn referential integrity off, and then modify the affected tables one at a time. However, the resulting data in the two tables may then conflict. For more information about referential integrity, click [image] .

For more information about setting and changing primary keys, click [image] .


 Layout Preview displays the wrong data.

Layout Preview displays the wrong data.

Layout Preview displays all the sections of a report and a few detail records. It sorts and groups the data it displays, but ignores any parameters, criteria, or joins in the underlying query. For example, the detail records you see in a group may not be the records that actually belong in that group.

To verify the accuracy of the data in a report, use Print Preview. For more information, click [image] .


 When I select a value in a list, it disappears or gives me an error message.

When I select a value in a list, it disappears or gives me an error message.

You may have specified the wrong column in the BoundColumn (forms and reports) or the ListBoundField (data access pages) property box. The BoundColumn or ListBoundField property determines which column's data is stored in the field that is specified in the ControlSource property box. For example, if you have a combo box on a form or report that has a SupplierID column and a SupplierName column, the bound column would be the SupplierID column (the foreign key field) even if the SupplierName column is the only visible column.


 How do I temporarily disable an action in a macro?

How do I temporarily disable an action in a macro?

Temporarily disabling an action can be helpful when you're trying to find problems in a macro. This is similar to temporarily turning a line into a comment in Visual Basic for Applications code by typing a single quotation mark (') at the beginning of the line. To cause Microsoft Access to temporarily ignore an action, type False as a condition.

For more information about entering a condition for a macro action, click [image] .


 The RunCode action in my macro won't run a Visual Basic module.

The RunCode action in my macro won't run a Visual Basic module.

You use the RunCode action to run a Function procedure, not a module. In Microsoft Access, you run procedures rather than modules. Replace the name of the module with the name of the function in the module that you want to run. To run a Sub procedure, call it in the function.

To open a module, use the OpenModule action.


I'm using the SendKeys action in a macro to send keystrokes to a dialog box, but they're not being sent.

Because the dialog box suspends the macro, you must put the SendKeys action before the action that causes the dialog box to open and set the Wait argument to No to avoid pauses in processing. For more information about the SendKeys action, click [image] .


When I run my macro, Microsoft Access displays messages that I don't want to see.

You can hide warnings and other messages while a macro is running by carrying out the SetWarnings action in the macro. You can also use the SetWarnings action to display messages again. For more information, click [image] .


 The Where Condition argument in my macro's OpenForm or OpenReport action is producing unexpected results.

The Where Condition argument in my macro's OpenForm or OpenReport action is producing unexpected results.

The Where Condition argument of an OpenForm or OpenReport action might produce unexpected results for any of the following reasons:

  • The Where Condition expression uses invalid syntax to refer to the value of a control or property. For more information about referring to the value of a control, click [image] .

  • The Where Condition argument uses invalid syntax to combine the value of a field, control, or property with a literal string. For more information about values in expressions, click [image] .

  • The OpenForm or OpenReport action is being carried out by using the corresponding Visual Basic for Applications methods in a procedure, and the Where Condition argument is specified in the wrong position in the list of arguments. If the Where Condition argument isn't preceded by View and Filter Name arguments, you must still type a comma as a placeholder for each of these arguments.

    For more information on the OpenForm action, click [image] . For more information on the OpenReport action, click [image] .


 How do I use Microsoft Visual Basic to add a new record to a table?

How do I use Microsoft Visual Basic to add a new record to a table?

You can programmatically add a new record to a table or result set by using the AddNew and Update methods of the Recordset object. For more information, click [image] or see Building Applications with Forms and Reports.


 How can I use Visual Basic to change the underlying SQL statement of a query?

How can I use Visual Basic to change the underlying SQL statement of a query?

You can use the SQL property of a QueryDef object to change the underlying SQL statement of a query. For example, the following block of Visual Basic code changes the underlying SQL statement of the query Employee List so that the query selects all records in the Employees table:

Dim dbsCurrent As Database
Dim qryTest As QueryDef

Set dbsCurrent = CurrentDb
Set qryTest = dbsCurrent.QueryDefs("Employee List")
qryTest.SQL = "SELECT * FROM Employees;"

For more information about the SQL property, click [image] .


My procedure produces unexpected results when I use one of the Find methods.

The FindFirst, FindLast, FindNext, and FindPrevious methods might produce unexpected results for the following reasons:

  • The criteria argument you specified uses invalid syntax to refer to the value of a control or property. For more information about referring to the value of a control, click [image] .

  • The criteria argument you specified uses invalid syntax to combine the value of a field, control, or property with a literal string. For more information about values in expressions, click [image] .

The FindRecord and FindNext methods might produce unexpected results if the FindRecord method's onlycurrentfield argument is set to acCurrent. Use the GoToControl method to move the focus to the control containing the data you're searching for before using the FindRecord or FindNext method.


 I get a "Sub or Function not defined" message when I try to use the IsLoaded function.

I get a "Sub or Function not defined" message when I try to use the IsLoaded function.

The IsLoaded function is a sample Function procedure included with the Northwind sample database, and not a built-in Visual Basic function. To use the IsLoaded function in your database, first open the Northwind sample database, then copy the function, and paste it in a module in your database.

For information about opening the Northwind sample database, click [image] .


 I get a "Method or data member not found" message when I try to refer to a table field in code.

I get a "Method or data member not found" message when I try to refer to a table field in code.

Microsoft Access displays this message if you use the . (dot) operator rather than the ! operator to refer directly to a table field. For example, this error is produced by the last line of the following block of Visual Basic code:

Dim dbsCurrent As Database
Dim tblTest As TableDef
Dim fldTest As Field

Set dbsCurrent = CurrentDb
Set tblTest = dbsCurrent.TableDefs("Categories")
Set fldTest = tblTest.CategoryID

To correct the problem, replace the . (dot) operator with the ! operator or refer to the field as an element of the Fields collection. You can use either of the following lines of code, although the first might result in faster performance:

Set fldTest = tblTest!CategoryID

Set fldTest = tblTest.Fields("CategoryID")

For more information on using the . (dot) and ! operators, click [image] .


 I want to test my Function or Sub procedure to see whether it works.

I want to test my Function or Sub procedure to see whether it works.

You can use the Immediate window of the Visual Basic Editor to check the results of a Function or Sub procedure. For example, to see the value returned by the custom function FirstOfNextMonth, type a question mark followed by a space, the name of the function, and any argument surrounded by parentheses:

? FirstOfNextMonth(Now)

For more information, click [image] .


 When I run my code, Microsoft Access displays messages that I don't want to see.

When I run my code, Microsoft Access displays messages that I don't want to see.

You can temporarily stop the display of warnings and other messages while Visual Basic code is running by using the SetWarnings method to carry out the SetWarnings action. You can also use the SetWarnings method to restart the display of messages. For more information, click [image] .


My AutoLookup query isn't filling in data.

For AutoLookup to work, the joined fields must meet certain conditions, and you must include certain fields from both tables in the query design grid. For more information, click [image] .


I chose the Active Graphics option when I applied the theme, but none of the graphics are animated.

Theme graphics are only animated when you view the data access page in a Web browser, not in Access.


 I want to see the content of my object in my form or report, but I see an icon instead.

I want to see the content of my object in my form or report, but I see an icon instead.

  1. Open the form in Design view or the report in Design view.

  2. Click the icon.

  3. On the Edit menu, point to the appropriate Object command (for example, point to Worksheet Object for a Microsoft Excel object), and then click Convert.

  4. In the Convert dialog box, clear the Display As Icon check box.


 One or more column headings in the query's results are labeled "<>".

One or more column headings in the query's results are labeled "<>".

Microsoft Access returns "<>" as the column name for any Null value in the field with Column Heading in its Crosstab cell. To avoid this you can:

  • Explicitly define your column headings by setting the query's ColumnHeadings property. For more information, click [image] .

  • In the design grid, type Is Not Null in the Criteria cell of the designated Column Heading field.

  • In the Criteria cell of the designated Column Heading field, use the Nz function in an expression that will convert Null values to a more meaningful value, such as "Unknown." For more information about the Nz function, click [image] .


 I'm getting the message "Operation must use an updatable query."

I'm getting the message "Operation must use an updatable query."

This error occurs when the current query's Update To row includes a field from either a crosstab query or select query in which an aggregate (total) was calculated for the field (using either the Totals row or a domain function in the Field row). To update a field using the aggregate of another field, calculate the aggregate in the update query itself, not a different query.

  1. In query Design view for the current query, remove the field you added from the crosstab or select query (where an aggregate was calculated for the field).

  2. In the Update To cell of the field you want to update, enter a domain function that calculates the same aggregate as is calculated for that field in the select or crosstab query.

    For example, if you had a calculated field named Sales So Far in your Products table, you could update it with the product of the Quantity and UnitPrice fields in the Order Details table by adding it to the design grid in the update query and then entering the following domain function in its Update To cell.

    DSum("[Quantity]*[UnitPrice]","Order Details","[ProductID]=" & [ProductID])

  3. To run the query, click Run [image] on the toolbar.

  4. To see the results, open the table by clicking Tables [image] under Objects in the Database window and clicking Open on the Database window toolbar.


Why do the colors in my picture or on my form look so bad?

If the picture you're displaying was created on a computer that has more colors than the computer that you're displaying the picture on, Microsoft Windows substitutes colors to match the original colors. This process is known as dithering. For example, you may be trying to display a picture that was created with 256 colors on a computer that only displays 16 colors (standard VGA). If your computer can display more colors, you can use a form or report's PaletteSource property to specify that Microsoft Access use the color palette that was used to create the picture.

If you're using background pictures with forms that have popup forms, it's a good idea to set the PaletteSource property of both forms to the same value. This is true if the form has a background picture and the popup form doesn't, if the popup form has a background picture and the form doesn't, or if both have background pictures. Windows can use only one palette at a time, so if you set the PaletteSource property to the same value, then you ensure that the colors you need to paint each form are available when the focus moves to the popup form or back to the form.

For more information on the PaletteSource property, click [image] .


The query didn't perform the update I wanted.

  • You need to specify a different update by changing the expression in the Update To cell. For example, to raise salaries by 5 percent, type [Salary]*1.05 in the Update To cell of the Salary field. For more examples of expressions in update queries, click [image] .

  • If you're updating data in the wrong field, specify an update for a different field. To specify an update for a field, type the expression you want in the Update To cell.


 The records the query retrieves are in the wrong order.

The records the query retrieves are in the wrong order.

  • Specify a sort order if you haven't already done so. For more information, click [image] .

    If you're working in a multiuser environment, someone else may have set a different sort order. Sort orders are saved with the query. You can change the sort order to the one you want.

  • If you've already specified a sort order, it may be set for the wrong field. Delete the sort you specified and specify a new sort order for the correct field.

  • If the sort order is set for the correct field, you may have selected Ascending when you really wanted Descending, or vice versa. Select the correct sort order.

  • If you have sort orders specified for more than one field, you may need to reorder the fields in the query design grid because Microsoft Access performs multiple sorts from left to right in the order the fields appear in the query design grid.

  • The field you specified the sort order for may be hidden. If you want to show the field you're using to sort records, make sure the Show check box is selected in the query design grid.

  • You can't set a sort order on a Hyperlink field. However, you can sort on an expression by using the HyperlinkPart function. For more information, click [image] .

  • For more considerations when sorting records, click [image] .


There's too much white space in my report.

If a report contains too much blank space, you can reduce the blank space by decreasing the space between sections and controls and by shrinking the space within controls.

To reduce the space between sections and controls

  • Reduce the width of the report.

    How?

  • Decrease the height of the sections.

    How?

  • Move controls closer together.

    How?

To reduce the space within a subform, subreport, or text box

  • Set the CanShrink property of the control to Yes.

    How?


 I get #Error? or #Name? when I try to display data from my subform on my main form.

I get #Error? or #Name? when I try to display data from my subform on my main form.

To display a value from a subform on a main form, create a calculated control that refers to the subform control using the following syntax:

=Forms![formname]![subformname]![controlname]

For example, suppose you have an Orders form and an Orders Subform. In the form footer of the subform, you have a text box named OrderSubtotal that sums the records in the subform. To display the value of this control on the main form, use the following expression:

=Forms![Orders]![Orders Subform]![OrderSubtotal]

To learn more about calculating a total for a group of records on a form, click [image] .

If you're already using this syntax and you still get an error, check to make sure that the form, subform, and control names are correct. Make sure that the names you're referring to are the names specified in the Name property for each object. Also make sure that you're including the exclamation point in the right places.

You can also use the Expression Builder to help you refer to other controls. For information on using the Expression Builder, click [image] .


The query doesn't retrieve the records I want.

What best describes the problem?

The query retrieves too many records.

The query retrieves too few records.

The query retrieves the wrong records.


 The query is too slow.

The query is too slow.

To speed up queries you can:

  • Use the Performance Analyzer to automatically evaluate the query and recommend changes that might make it run faster. For more information, click [image] .

  • Add indexes to the underlying tables. For information on what an index is and when to use one, click [image] .

    Note If you use the Performance Analyzer, it will suggest where to create indexes and relationships.

  • Change query design or make other changes in your database to optimize query performance. For more information, click [image] .


Some of the data in the PivotTable form is cut off and there aren't any scroll bars to see the rest of the data.

  • To scroll through the data in the PivotTable form, click the Edit PivotTable Object button, which opens Microsoft Excel. You can then see the entire PivotTable form and scroll through the data.


The column headings in my subreport don't print.

Microsoft Access doesn't print the page header and footer in a subreport, so if you put the labels for the column headings in the subreport's page header, they won't show up when you print the report.

  • If a subreport will always fit on one printed page, you can put the labels for the column headings in the subreport's report header.

  • If a subreport might span several printed pages, put the labels for the column headings in the subreport's group header, and set the RepeatSection property of the group header to Yes.


 The arithmetic calculation in the query design grid returns a Null (blank) value.

The arithmetic calculation in the query design grid returns a Null (blank) value.

If you use an arithmetic operator (such as +, -, *, /) in an expression, such as [UnitsInStock]+[UnitsOnOrder], and one of the fields in the expression contains a Null value, then the result of the entire expression will be a Null value. To avoid this, you can convert Null values to zeros or other numbers. For more information, click [image] .


 The filter returns too few records.

The filter returns too few records.

If the filter is returning too few records, try the solution that best applies to your situation.

Filter By Form

  • Add alternative criteria that records can meet on the Or tab (at the bottom of the window).

  • If you have multiple criteria on the Look For or Or tab, delete the value or expression that's restricting the records you want to see.

Filter By Selection

  • Remove the filter, select a value you're looking for, and then click Filter By Selection [image] on the toolbar. If necessary, repeat this until you have the records you want to see.

  • If you're using Filter By Selection on a combo box field that gets its values from a value list, check if the bound column for the combo box is the first column displayed in the list. If it's not and you've selected as your criteria part of a value from the combo box's displayed column, Microsoft Access can't match the criteria to the data in the bound column. You need to either change the combo box so the bound column is the first column displayed in the list, or fill the combo box with values from a table or query.

Filter For Input

  • Remove the filter if it's currently applied, and then specify a different value or expression in the Filter For box.

  • Switch to the Advanced Filter/Sort window to see if you specified more than one criteria that records must meet, or if you specified the wrong criteria.

Advanced Filter/Sort window

  • Delete criteria for one or more fields in the design grid.

  • Add extra Or rows where you can specify alternative criteria.

  • Use expressions with Or instead of And.


 The query retrieves too few records.

The query retrieves too few records.

If the query includes more than one table or query, check the join properties of each join line between them. Join properties determine if a table or query contributes all of its records or only those records that match records in the other table.

Examples of join types, how to change them and how they affect query results
  • If the type of join you're using retrieves only matching records from the two joined tables, any records in which the joined field contains a Null value won't be included in the query's results. You can convert Null values to a zero, zero-length string, or other specified value so that those records are included in the query's results. For more information, click [image] .

  • If you specified criteria, it may be too restrictive. For example, if you specified criteria in the Criteria row for two different fields, both criteria must be true for a record before the query retrieves it. You may want to delete some or all of the criteria to allow the query to return more records.

  • Verify that existing criteria is entered correctly. Check for misspellings, unnecessary spaces, or extra characters. Verify that you set the criteria for the appropriate field and that it's the criteria you want the records to meet.

  • If a field name includes a colon, you must enclose the name in brackets whenever you refer to the field in an expression. Otherwise, Microsoft Access interprets the field name as a literal text value, and therefore won't retrieve the records you want.

  • Use wildcard characters in the criteria if you aren't sure of or don't want to specify the exact field values. If you're already using wildcard characters and not getting the records you want, you may be using the wildcard characters on the wrong data type. For more information on wildcard characters, click [image] .

  • Add alternative criteria to select the records you want to work with. You can do this in the query design grid, in the Or row or in the Criteria row using expressions containing the Or operator. For examples of using alternative criteria, click [image] .

  • If you're using criteria to select records containing specific values in a field or fields, any records with Null values in that field don't match the value, and therefore won't be included in the records that are returned. To include records containing Null values, type Is Null in the Or row. For more information about Null values, click [image] .


 The query retrieves too many records.

The query retrieves too many records.

  • If you have more than one table or query in the query, connect them with a join line if they aren't already connected. For more information, click [image] .

If tables or queries are already joined, check the join properties of each join line to see what type of join is in effect. Join properties determine whether one table or query contributes all of its records or only those records that match records in the other table.

Examples of join types, how to change them, and how they affect query results
  • Add criteria to limit the records that the query retrieves. Only records that meet the criteria you define are retrieved. For more information about specifying criteria, click [image] .
    • If you already specified criteria, you may want to specify additional criteria either for the same field using the And operator or for other fields. Also, verify that existing criteria is entered correctly. Check for misspellings, unnecessary spaces, or extra characters. Verify that you set the criteria for the appropriate field and that it's the criteria you want the records to meet. If you're using alternative criteria in the Or row in the query design grid or in criteria expressions that use the Or operator, you may want to remove it. For examples of specifying multiple criteria, click [image] .

    • Check the data you're trying to find. If the data contains extra spaces or other special characters, the criteria must account for this. You can use wildcard characters in the criteria if you aren't sure of or don't want to specify the exact field values. If you're already using wildcard characters and not getting the records you want, you may be using the wildcard characters on the wrong data type. For more information on wildcard characters, click [image] .

    • In a select, append, or make-table query, if you're using Top Values [image] on the toolbar in query Design view (or setting the TopValues property in the query's property sheet) to return a specified number of the highest or lowest values in a field, the query might return more records than the number you specified. This is because all records that match the last record are also returned. Therefore, a query would return all three of the following records even if you requested to see the employees with the top two sales totals because the query doesn't distinguish between the two 50,000 sales totals.
      EmployeeID | Sales
      1 | 60,000
      2 | 50,000
      3 | 50,000

      If you don't want duplicate values to be returned, set the UniqueValues property in the query property sheet to Yes.

    For more information, click


 The query retrieves the wrong records.

The query retrieves the wrong records.

  • Verify that existing criteria is entered correctly. Check for misspellings, unnecessary spaces, or extra characters. Verify that you set the criteria for the appropriate field and that it's the criteria you want the records to meet.

  • Verify that the tables and queries you've added to the upper part of query Design view are the correct ones. For information on adding a table or query, click [image] . For information on deleting a table or query, click [image] .


 The results of a totals (aggregate) calculation in the query are wrong.

The results of a totals (aggregate) calculation in the query are wrong.

  • If there are records with Null (blank) values in the field you are calculating, those records won't be included in the calculation. For more information on Null values, including how to include them in a calculation, click [image] .

  • If the query isn't performing the calculation on the correct groups, verify that you have Group By in the Total cell for the field or fields you want to use for grouping calculations. For information on performing calculations on groups of records, click [image] .

  • In a crosstab query, you might have too many or too few Group By fields. Add, remove, or change the fields designated as row headings that group the totals vertically. Verify that you're using the correct field's values as column headings that group the totals horizontally.

  • Where you specify criteria in the query design grid determines if records are excluded before the query groups or performs calculations, if groups are excluded before the calculation is performed, or if certain results are excluded after the calculation is performed. For more information, click [image] .

  • Verify that the aggregate you selected is the correct one. If not, select a different aggregate from the list in the Total cell. For more information on different aggregate functions, click [image] .


The results of a totals (aggregate) calculation are in the wrong column.

In the query design grid, delete the aggregate you specified in the Total cell for that field (column), and then select one in a different field.


The query retrieves the wrong columns.

  • In the query design grid, remove the fields that you don't want the query to retrieve. For more information, click [image] .

  • If columns are missing, add their fields to the query design grid. For more information, click [image] .

  • Verify that the tables and queries you're retrieving records from are the correct ones. For information on adding a table or query, click [image] . For information on removing a table or query, click [image] .


The query retrieves too few columns.

  • Add more fields to the query design grid. Or if you add the asterisk to the design grid, the query automatically includes all fields from the underlying table or query. For more information, click [image] .

  • Add other tables or queries, then add the other fields you need. For more information, click [image] .

  • Show hidden fields. For more information, click [image] .

  • If the Output All Fields check box is not selected, only the fields in the design grid are retrieved. (To see if it is selected, on the Tools menu, click Options, and then click the Tables/Queries tab.) If it is, all fields from the underlying table or query will appear in the query's results without being added to the query design grid. If you then add a field to the design grid, say, for setting criteria, you need to clear the Show check box for that field; otherwise, the column appears twice in the query's results. Or if you want, clear the Output All Fields check box. Changing this option only affects the property setting for new queries you create, not existing queries.


The query retrieves too many columns.

  • Remove the fields in the query design grid that you don't want to see in the query results, and remove the asterisk (*) if you added it to the design grid. The asterisk automatically includes all fields from the underlying table. For more information on removing fields, click [image] .

  • Hide fields that you don't need to display in the query's results. For more information, click [image] .

  • Verify that the Output All Fields check box isn't selected. (To see if it is selected, on the Tools menu, click Options, and then click the Tables/Queries tab.) If it is, all fields from the underlying table or query will appear in the query's results without being added to the query design grid. If you then add a field to the design grid, say, for setting criteria, you need to clear the Show check box for that field; otherwise, the column appears twice in the query's results. If you want, clear the Output All Fields check box. Changing this option only affects the property setting for new queries you create, not existing queries.


The calculations in the query are wrong.

What best describes the problem?

The results of a calculation specified in the Totals row in the query design grid are wrong.

The results of a calculation specified in the Totals row in the query design grid are in the wrong column.

An arithmetic calculation in a calculated field in the query design grid returns a Null (blank) value.


Customize a crosstab query

What do you want to do?

Change the order or the number of column headings

Sort the records

Specify criteria to limit certain records

Exclude records with Null (blank) values to avoid getting "<>" as a column heading


 Microsoft Access can't paste the data. Why not?

Microsoft Access can't paste the data. Why not?

In most cases, if Microsoft Access can't paste some or all of the data in a Microsoft Access database, it creates the Paste Errors table. In that case, Microsoft Access displays a message telling you that data will be added to the Paste Errors table. For information on displaying the Paste Errors table, click [image] .

There are several reasons why Microsoft Access will not paste some or all of your data:

  • You tried to paste an entire field or fields without selecting a destination. You must select the field or fields that you want to paste to. For information on selecting fields, click [image] .

  • You tried to paste more fields than the datasheet you're pasting to has, or more than the number of fields you selected as a destination. Microsoft Access doesn't paste the extra fields.

  • You tried to paste a value that's not compatible with the data type of the field. For example, you tried to paste a combination of letters and numbers into a field in a Microsoft Access database with the Number data type or a Microsoft Access project with the smallint data type.

  • You tried to paste text that's too long for the field. The setting in the FieldSize property of an Access database or the Length column property in an Access project determines the maximum size of a field value. Check the field in table Design view in an Access database or Column Properties view in a database diagram in an Access project to see the setting.

  • You tried to paste a duplicate value into the table's primary key, a field that has the Indexed property set to No Duplicates in an Access database, or a field with either a unique constraint or unique index in an Access project. Check the field in table Design view in an Access database or Column Properties view in a database diagram in an Access project to see the setting.

  • You tried to paste data into a hidden field. This is not permitted. To display hidden columns, click Unhide Columns on the Format menu.

  • In an Access database, you tried to remove data from or paste data into a disabled, locked, calculated, or AutoNumber field. For more information on these types of fields, click [image] .

  • You don't have permissions to add or edit data in the database object.

  • A value you tried to paste isn't allowed in the field based on the settings of the ValidationRule, InputMask, Required (Access database only), or AllowZeroLength (Access database only) properties.

  • The validation macro specified for the BeforeUpdate or OnInsert properties canceled the update. The data you tried to paste did not meet the validation requirements.


Troubleshoot printing and previewing reports

What do you need help with?

My report prints blank pages.

There's too much white space in my report.

Layout Preview displays the wrong data.

My report prompts me for unexpected parameters.

The column headings in my subreport don't print.

#Error? or #Name? appears in a control.

My subreport prints only one column when it should print more.


 I'm getting a type mismatch message.

I'm getting a type mismatch message.

  • Verify that the criteria you specified is for the same data type as the data in the underlying table or query. For example, the field ReorderLevel has a Number data type. Therefore, if you type the criteria "50", you'll get an error because Microsoft Access interprets values in quotation marks as text, not numbers.

    Other situations that cause a data type conflict include:

    • You're specifying criteria for a Lookup field and the criteria uses the values that display on the lookup list instead of their associated foreign key values. Because the foreign key values are the values actually stored in the underlying table, you should use them when you specify criteria for a field. For more information about Lookup fields, click [image] .

    • You typed the dollar sign ($) in criteria you specified for a Currency field. Remove the dollar sign, and then view the results.
  • Verify that the data type of each pair of joined fields in the query is the same. If not, change the data type of one of the joined fields to match the data type of the other. For more information, click [image] .


I'm getting a validation rule violation message.

A validation rule violation occurs if you attempt to update or append records that violate the validation rules for a field or record.

For more information about validating data, click [image] .


 I want the option of returning all records with a parameter query.

I want the option of returning all records with a parameter query.

In the design grid under the field that contains the prompt in the Criteria cell, type [prompt] Is Null in the Or cell, where prompt is the same prompt that is in the Criteria cell for that field. For example, in the CategoryID field:

In this cell | Type
Criteria | Like [Enter Category ID:]
Or | [Enter Category ID:] Is Null

Now when you run the query, if you leave the Enter Parameter Value dialog box blank, the query returns all records.


 I can't change a table's design in an Access database.

I can't change a table's design in an Access database.

  • If another user has a table open or is viewing data in queries, forms, or reports based on the table, you can't make any changes to the table's design. Microsoft Access informs you that it is read-only.

  • You might not have permission to change the design. If the shared Microsoft Access database you're using is secured, access to objects (except modules) is controlled by the people who create or administer it. Your permissions might be determined by the group you are in.


 I can't open an Access database object.

I can't open an Access database object.

You might not have permission to open the object. If the shared Microsoft Access database you're using is secured, access to objects (except modules) is controlled by the people who create or administer it. You might have permission to view an object but not to see it in Design view or to update it. Also, your permissions might be determined by the group you are in.


 I can't view data in a table in an Access database.

I can't view data in a table in an Access database.

  • You can't view data in a table that another user has open in Design view. Wait until the table is available. When you open a table in Design view, keep it open only as long as necessary if others need to use the table or any queries, forms, or reports based on the table.

  • You might not have permission to view the data. If the shared Microsoft Access database you're using is secured, access to objects (except modules) is controlled by the people who create or administer it. Your permissions might be determined by the group you are in.


Why did the size of my database increase significantly more than the size of the object I added?

The amount of information that is used to represent an object is often greater than the size of the object itself. One way to work around this disproportion is to display an icon in the form or report that represents the object instead of the object itself. When you display an icon, the OLE server (the application used to create the object) sends only the information needed to display the icon. When you double-click the icon, the OLE server is launched with the data that the icon represents.

For information on displaying an object as an icon, click [image] .


 The data I pasted is in the wrong field. Why?

The data I pasted is in the wrong field. Why?

  • When you paste records into a datasheet, Microsoft Access places them in the order they appear in the columns of the datasheet, regardless of the names of the fields. If you want the data to be pasted according to corresponding field names, paste them into a form in Form view.

  • When you paste records into a form, Microsoft Access places them into fields with the same name as the source fields, regardless of their order on the form. However, if there are no matching field names, the data is placed according to the form's tab order, which may not be the order you intend.


 Why didn't the filter sort the records in the correct order in my table, query, or form?

Why didn't the filter sort the records in the correct order in my table, query, or form?

You may need to:

  • Add or delete a sort order.

  • Sort by a different field.

  • Change the sort order from Ascending to Descending, or vice versa.

  • In the Advanced Filter/Sort window, rearrange the columns in the design grid, and then specify a sort order on one or more fields. Microsoft Access sorts the records starting with the leftmost column in the grid.

Notes

  • If you have numbers in fields with a Text data type, those numbers will not sort from lowest number to highest, or vice versa. Instead, they will sort as follows: 1, 11, 12, 2, 20, 3, and so on. For more information, click [image] .

  • If you have Null values in a field that you're sorting in ascending order, records with those values appear first in the sort order before any records with text or numeric values in the sorted field.

For more information about sorting, click [image] .


Why isn't the filter returning the correct records in my table, query, or form?

What best describes the problem?

The filter returns too many records.

The filter returns too few records.

The filter returns the wrong records.


 Why is the property sheet blank?

Why is the property sheet blank?

If the property sheet is displayed and you click a control that's already selected, the property sheet will go blank. If you don't need to type a value in the control, press ESC to redisplay the property sheet. Otherwise, type a value and press ENTER.


How records in indexed and nonindexed fields are read differently in the Filter By Form window

How many records Microsoft Access reads depends on whether or not the field is indexed. If the field is indexed, Microsoft Access reads only the unique values, not all the values in a field. If the field isn't indexed, Microsoft Access reads all the values in the field. If the number of records it reads is more than the maximum it's allowed to display, which is determined by the setting for Don't Display Lists Where More Than This Number Of Records Read, Microsoft Access doesn't display the values for that field on the list. Consequently, you need to change the setting for this option. Because Microsoft Access reads all values in nonindexed fields, not just unique values, set this option to a number greater than (or equal to) the number of records in the nonindexed field with the most values.

Note When Microsoft Access is able to display the list in a field, it only shows the unique values, even for a nonindexed field.


 Why don't I see all the properties in the property sheet?

Why don't I see all the properties in the property sheet?

If you select multiple controls but don't see the properties you expect in the property sheet, you may have selected a control that you didn't mean to select. For example, you may have included a line in a group of text boxes. Properties appear in the property sheet only if they apply to all of the selected controls. To remove a control from a group selection, hold down the SHIFT key and click the control.


 Why is the property box for a particular property blank?

Why is the property box for a particular property blank?

If the property setting for a particular property is the same for all selected controls, that setting appears in the property sheet; otherwise, the property box for that property is blank. If you have multiple controls selected, and you change a setting for a property in the property box, that change affects all selected controls.


 Why don't the property settings for my control match the settings in table Design view?

Why don't the property settings for my control match the settings in table Design view?

The property settings for a bound control might not match corresponding settings in the field in the underlying table that the control is bound to. If the settings are different, the form or report settings typically override those in the table, but they apply only to the current form or report. It's generally a good idea to set the Format, DecimalPlaces, InputMask, ValidationRule, ValidationText, and DefaultValue properties in the underlying table or query rather than in the control. This way, you can be sure that you have consistent settings for the field whenever you add it to a form or report. To learn more about property inheritance in controls, click [image] .


 Why can't I use some of the fields in the Filter By Form window?

Why can't I use some of the fields in the Filter By Form window?

You can't use the following types of fields in the Filter By Form window because they don't apply to filtering records:

  • A calculated control in a form.

  • A field created with an unbound control or unbound object frame.


The text displayed in the combo box in a form or report is from the wrong column. How do I display data from another column?

In a multiple-column combo box on a form or report, the text box portion of the combo box displays data from the first visible column in the list. You use the ColumnWidths property to determine which columns are visible. For example, if you have a combo box that is based on a query that includes the SupplierID field and the SupplierName field, in that order, then Microsoft Access displays the SupplierID field in the text box portion of the combo box unless you hide it using the ColumnWidths property. For more information on hiding a column in a list box or combo box, click [image] .


Ways to customize a report 3

Add fields from the report's record source


Ways to customize a form 5

Add fields from the form's record source


Ways to customize a form 2

Change the appearance of a form


Ways to customize a report 2

Change the appearance of a report


Ways to customize a form 6

Change a control to another type of control

More information

Add, remove, or format a form header, page header, or other section

Move, size, align, and format fields or controls in a form

Create a specific type of control on a form

Change a control to another type of control


Ways to customize a report 6

Change the text or data that appears in a control

More information

Add, remove, or format a report header, page header, or other section

Move, size, align, and format fields or controls in a report

Create a specific type of control on a report

Sort records in a report

Group records in a report


Ways to customize a form 4

Change the text or data that appears in a control


Ways to customize a report 5

Change the sorting or grouping order for the records in a report


FastTips

Microsoft FastTips is an automated, toll-free service that provides quick answers to your common technical questions — 24 hours a day, 7 days a week — when you call (800) 936-4100 from a touch-tone telephone in the United States. By using the buttons on your telephone to respond to prompts, you can hear recorded answers to your technical questions, obtain a catalog of available information, and order items by fax — for example, you can order Application Notes by fax, as well as popular articles from the Microsoft Knowledge Base. Outside the United States, contact your local Microsoft subsidiary for information.


 Change a saved search

Change a saved search

  1. On the File menu, click Open [image] .

  2. Click Tools, and then click Find.

  3. Click Open Search.

  4. Click the name of the saved search you want to change, and then click Open.

  5. In the Find Files That Match These Criteria box, click the criteria you want to change, and then click Delete.

    Settings of the deleted search criteria appear in the Define More Criteria box. If you change your mind, you can click Add To List to restore the deleted search criteria.

    To clear all search criteria and start with default search values, click New Search.

  6. Under Define More Criteria, specify new search criteria.

  7. Click Add To List.

  8. Click Save Search.

  9. To replace the existing saved search, type the name of that search, click OK, and then click Yes.

    To assign a new name to the modified search criteria, type a new name, and then click OK.

Notes

  • You will not be able to find a file by searching the text within a Microsoft Access database or Microsoft Access project file.

  • You can also change a saved search in the Import and Link dialog boxes on the File menu, or the Database to Convert From, Database To Compact From, Database to Save As MDE, and Encrypt/Decrypt Database dialog boxes on the Tools menu.


Copy an image from a graphics program to a toolbar button or menu command

For a clear image, copy a graphic that is the same size as a built-in button image or a menu command image. The default button image is 16 by 16 pixels. A larger image may be distorted because it will be scaled to fit the size of the button.

  1. In the graphics program, copy to the Clipboard the graphic you want to appear on the toolbar button or menu command.

    If you can select the format for the copied graphic, select bitmap (.bmp) format.

  2. Switch to Microsoft Access.

  3. On the View menu, point to Toolbars, and then click Customize.

  4. Show the toolbar, menu bar, or shortcut menu with the button image or menu command you want to change.

  5. With the Customize dialog box open, do one of the following:
    • To paste the copied image to a toolbar button, right-click (on the toolbar) the button that contains the image you want to change, and then click Paste Button Image on the shortcut menu.

    • To paste the copied image to a menu command, click the menu on the menu bar or toolbar, or click the shortcut menu that contains the command you want to paste the image onto. Right-click the menu command, and then click Paste Button Image on the shortcut menu.

Note If you change the image for a command on a built-in menu (for example, the Edit menu), the new image appears in all views showing that menu with that command.


Copy an image from one toolbar button or menu command to another

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the toolbar, menu bar, or shortcut menu with the button image or menu command you want to copy. If you're copying the image to a different toolbar or menu bar, show that bar, too.

  3. With the Customize dialog box open, do one of the following:
    • To copy a toolbar button image, right-click (on the toolbar) the button that contains the image you want to copy, and then click Copy Button Image on the shortcut menu.

    • To copy a menu command image, click the menu on the menu bar or toolbar, or click the shortcut menu that contains the command with the image you want to copy. Right-click the menu command, and then click Copy Button Image on the shortcut menu.
  4. Do one of the following:
    • To paste the copied image to a toolbar button, right-click (on the toolbar) the button you want to paste the image onto, and then click Paste Button Image on the shortcut menu.

    • To paste the copied image to a menu command, click the menu on the menu bar or toolbar, or click the shortcut menu you want to paste the image onto. Right-click the menu command, and then click Paste Button Image on the shortcut menu.

Note If you change the image for a command on a built-in menu (for example, the Edit menu), the new image appears in all views showing that menu with that command.


Edit a toolbar button image or a menu command image

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the toolbar, menu bar, or shortcut menu with the toolbar button image or menu command image you want to change.

  3. With the Customize dialog box open, do one of the following:
    • To edit a toolbar button image, right-click the button on the toolbar, and then click Edit Button Image on the shortcut menu.

    • To edit a menu command image, click the menu on the menu bar or toolbar, or click the shortcut menu that contains the command with the image you want to edit.

      Right-click the menu command, and then click Edit Button Image on the shortcut menu.

  4. Make the changes you want.

Note If you change the image for a command on a built-in menu (for example, the Edit menu), the new image appears in all views showing that menu with that command.


Microsoft Download Service (MSDL)

The Microsoft Download Library (MSDL) contains sample programs, device drivers, patches, software updates, and programming aids. Direct modem access to MSDL is available 24 hours a day, 365 days a year, by dialing (425) 936-6735 in the United States or (905) 507-3022 in Canada. Outside the United States and Canada, contact your local Microsoft subsidiary for information.

Note The service supports 1200-, 2400-, 9600-, or 14,400-baud data transmission, with no parity, 8 data bits, and 1 stop bit.


Restore original buttons and menus on a built-in toolbar, menu bar, or shortcut menu

  1. On the View menu, point to Toolbars, and then click Customize.

  2. On the Toolbars tab, select the name of the toolbar or menu bar you want to restore original buttons and menus on. To restore all the shortcut menus, select the Shortcut Menus toolbar.

    Note Selecting or clearing a check box in the Toolbars box shows or hides that toolbar or menu bar.

  3. Click Reset.

Notes

  • You cannot reset a custom toolbar or menu bar.

  • As you work with Microsoft Access, the menus and toolbars are personalized to show the commands that you use most often. If you want, you can return the toolbar and menu display to its initial state when you first started Access.


 Search criteria you can use to find files

Search criteria you can use to find files

In the File name box in the Open dialog box (File menu), you can enter any of the following search criteria to locate your file.

You can type | For example, type
Partial file names | region to find all files with names that include "region."
File name extensions | *.txt to find text files.
Wildcard characters | *region to find only file names that end with "region," or gr?y to find instances of both "gray" and "grey." Use an asterisk (*) to match any number of characters, or use a question mark (?) to match any single character.
The full path | c:\House finances\Property taxes in 1995. When you include a drive letter, share, or folder, the program automatically updates the location in the Look in box, displays only the name of the file in the File name box, and then opens the file.
Multiple paths | c:\House finances;c:\My work documents. Separate each path with a semicolon. All of the folders and files from each path you enter in the File name box are displayed. The Look in box displays the path that comes first alphabetically.

Notes

  • To reuse a recent entry, click its file name in the File name box.

  • You can also use these search criteria in the Import and Link dialog boxes on the File menu, or the Database to Convert From, Database To Compact From, Database to Save As MDE, and Encrypt/Decrypt Database dialog boxes on the Tools menu.

  • You can type an Internet location to open a Web page in the Locate Web Page dialog box. In the Database window, click Pages [image] under Objects and then double click Edit Web page that already exists. In the File name box type the HTTP URL, such as http://example.microsoft.com, to open the Web page.


Use shortcut keys for windows and dialog boxes

Press | Using a window
ALT+TAB | To switch to the next program
ALT+SHIFT+TAB | To switch to the previous program
CTRL+ESC | To show the Windows Start menu
CTRL+W | To close the active database window
CTRL+F6 | To switch to the next database window
CTRL+SHIFT+F6 | To switch to the previous database window

Press | Using a dialog box
CTRL+TAB or CTRL+PAGE DOWN | To switch to the next tab in a dialog box
CTRL+SHIFT+TAB or CTRL+PAGE UP | To switch to the previous tab in a dialog box
TAB | To move to the next option or option group
SHIFT+TAB | To move to the previous option or option group
Arrow keys | To move between options in the selected drop-down list box, or to move between some options in a group of options
SPACEBAR | To perform the action assigned to the selected button; select or clear the check box
Letter key for the first letter in the option name you want (when a drop-down list box is selected) | To move to the option by the first letter in the option name in a drop-down list box
ALT+letter key | To select the option, or to select or clear the check box by the letter underlined in the option name
ALT+DOWN ARROW | To open the selected drop-down list box
ESC | To close the selected drop-down list box
ENTER | To perform the action assigned to the default button in the dialog box
ESC | To cancel the command and close the dialog box

Press | Editing in a text box
HOME | To move to the beginning of the entry
END | To move to the end of the entry
LEFT ARROW or RIGHT ARROW | To move one character to the left or right
CTRL+LEFT ARROW or CTRL+RIGHT ARROW | To move one word to the left or right
SHIFT+HOME | To select from the insertion point to the beginning of the entry
SHIFT+END | To select from the insertion point to the end of the entry
SHIFT+LEFT ARROW | To select one character to the left
SHIFT+RIGHT ARROW | To select one character to the right
CTRL+SHIFT+LEFT ARROW | To select one word to the left
CTRL+SHIFT+RIGHT ARROW | To select one word to the right


I know a file is on a drive or in a folder, but I don't see it.

The current search criteria for the Open dialog box may include the correct location of the file, but other criteria may exclude the file you're looking for. Try the following:

  • In the dialog box, click Tools, click Find, and then click New Search to clear all current criteria except the location and the default file type. Try specifying different criteria before clicking Find Now.

  • In the dialog box, click All Files in the Files of type box.

  • To search through all subfolders, click Tools in the dialog box, click Find, and then select the Search subfolders check box.

  • The file may be hidden. To display all files, including file types such as *.dll and *.sys, click the Windows Start button, point to Programs, and then click Windows Explorer. On the View menu, click Options. On the View tab, click Show All Files.

Note You can also try this when searching for a file in the Import and Link dialog boxes on the File menu, or the Database to Convert From, Database To Compact From, Database to Save As MDE, and Encrypt/Decrypt Database dialog boxes on the Tools menu.


When I use one of my saved searches, I no longer find many of the files I found previously.

Check to see if the search criteria include a network drive.

If the criteria include a network drive, make sure that the drive is still available.

If the criteria don't include a network drive, the missing files may have been deleted, renamed, or moved since the last time you performed this search.


Databases: What they are and how they work

1 2 3 4 5 6 7 8


Databases: What they are and how they work


Values for the DefaultSource Member

Value | Meaning
1 | Upper or only one bin
2 | Lower bin
3 | Middle bin
4 | Manual bin
5 | Envelope bin
6 | Envelope manual bin
7 | Automatic bin
8 | Tractor bin
9 | Small-format bin
10 | Large-format bin
11 | Large-capacity bin
14 | Cassette bin
256 | Device-specific bins start here


Example of a crosstab query


Example Of Grouped Records In A Report

1 2 3


Example of grouped records in a report


Constants for the Fields Member

A printer driver supports only those members that are appropriate for the printer technology.

Constant | Value
DM_ORIENTATION | &H0000001
DM_PAPERSIZE | &H0000002
DM_PAPERLENGTH | &H0000004
DM_PAPERWIDTH | &H0000008
DM_SCALE | &H0000010
DM_COPIES | &H0000100
DM_DEFAULTSOURCE | &H0000200
DM_PRINTQUALITY | &H0000400
DM_COLOR | &H0000800
DM_DUPLEX | &H0001000
DM_YRESOLUTION | &H0002000
DM_TTOPTION | &H0004000
DM_COLLATE | &H0008000
DM_FORMNAME | &H0010000


Forms What They Are And How They Work

1 2 3


Forms: What they are and how they work


 I see a red X, a blank image, or no image at all on my data access page.

I see a red X, a blank image, or no image at all on my data access page.

If you see a red X, a blank image, or no image at all where your graphics should be, check the following:

You might have the wrong browser settings Although all browsers support the same language (HTML), there are some differences among browsers. Some support different versions of HTML and different HTML extensions. Custom options can be set in browsers, such as the default text and background colors, and whether or not graphics are displayed. Consider testing your data access page in different browsers — some of which are available for downloading on the Web — and with different monitor settings, to see if all of your page elements appear.

You might have used the wrong picture format If you link a graphic to a data access page, and the graphic format isn't supported by your browser, your graphics won't be visible. Make sure that the linked picture is in a graphic format that is compatible with your browser. The JPG and GIF graphic formats are compatible with most browsers.


Join types and how they affect query results

1 2 3 4 5


Join types and how they affect query results


Ways to customize a report 4

Move, size, and align controls


Ways to customize a form 3

Move, size, and align controls


My subreport prints only one column when it should print more.

A subreport might print only one column if, in the subreport, Column Layout is set to Down, Then Across on the Columns tab in the Page Setup dialog box and, on the main report, the CanGrow property is set to Yes for the subreport control.

You can redesign the report in one of the following ways:

  • In the subreport, change Column Layout to Across, Then Down and, on the main report, leave the CanGrow property set to Yes for the subreport control. The subreport control will display multiple columns and expand as needed.

  • In the subreport, leave Column Layout set to Down, Then Across. On the main report, size the subreport control to fit the maximum number of records, and set its CanGrow property to No. Because the subreport control will always be the same size, if the number of records is greater than the maximum number you anticipated, records that don't fit in the subreport control will be truncated.

If possible, don't use a subreport. Put the controls that print the data in the main report in a group header or the page header, and put the controls that print the data in the subreport in the detail section.


Move or copy a menu to a menu bar or toolbar

  1. Show the menu bar or toolbar with the menu you want to move or copy and the menu bar or toolbar you want to move or copy to.

  2. Do one of the following:
    • To move a menu when the Customize dialog box is open, drag the menu to the new location on the same or another menu bar or toolbar. If the dialog box isn't open, hold down ALT, and then drag the menu to the new location.

    • To copy a menu when the Customize dialog box is open, hold down CTRL and drag the menu to the new location on the same or another menu bar or toolbar. If the dialog box isn't open, hold down CTRL+ALT, and then drag the menu to the new location.


Restore original settings for a built-in menu

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the menu bar or toolbar that contains the built-in menu you want to restore to its original settings.

  3. Leave the Customize dialog box open. On the menu bar or toolbar, right-click the menu you want to restore, and then click Reset on the shortcut menu.

Notes

  • If you restore a menu (for example, the Edit menu), the menu is restored in all views that have that menu.

  • You can also return to the default commands on the personalized menus that appeared when you first started Microsoft Access.


 Add an FTP site to the list of FTP locations

Add an FTP site to the list of FTP locations

You can add an FTP site to the FTP Locations list in the Open and Save As dialog boxes. To do this procedure, your company must have an intranet or you must have access to the Internet — for example, you could have a modem and an Internet account through a service provider, or you could have access through your corporation's network.

  1. On the File menu, click Open [image] .

  2. In the Look In box, click Add/Modify FTP Locations.

  3. In the Name of FTP site box, type the FTP site name; for example, type ftp.microsoft.com.

  4. To log on to a site anonymously, click Anonymous (some sites don't allow this).

    To log on to a site you have user privileges for, click User, type your logon name, and then type your password if prompted.

  5. Click Add.


 Change the logon name or password for an FTP site

Change the logon name or password for an FTP site

You can change the way you log on to an FTP site. To do this procedure, your company must have an intranet or you must have access to the Internet — for example, you could have a modem and an Internet account through a service provider, or you could have access through your corporation's network.

  1. On the File menu, click Open [image] .

  2. In the Look In box, click FTP Locations.

  3. Right-click the FTP site you want to change, and then click Modify on the shortcut menu.

  4. Change the options you want. For information about a specific item in the Add/Modify FTP Locations dialog box, click the question mark button [image], and then click the item.


Minimize all program windows on the Windows desktop

  • Right-click the background of the Windows taskbar, and then click Minimize All Windows on the shortcut menu.


 Remove an FTP site from the list of Internet sites

Remove an FTP site from the list of Internet sites

  1. On the File menu, click Open [image] .

  2. In the Look In box, click FTP Locations.

  3. Right-click the FTP site you want to remove, and then click Remove on the shortcut menu.


Display text, an icon, or both on a toolbar button

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the toolbar with the button you want to change.

  3. Leave the Customize dialog box open. On the toolbar, right-click the button you want to change, and then click the option you want on the shortcut menu.

Notes

  • You can't change the text and icon format for a button that displays a list or a menu when you click it.

  • If the button has the Default Style format, when you copy or move the button to a menu, the menu automatically displays the command name and icon (which is the default for menus).


 I can't open a file on the Internet.

I can't open a file on the Internet.

You must have access to the Internet — for example, you could have a modem and an Internet account through a service provider, or you could have access through your corporation's network — to open files at an FTP site or on the World Wide Web.

  • If you have Internet access and you still can't open the file, the site may be too busy. Try to open the file later.


Use shortcut keys for menus

Press | Using a menu
SHIFT+F10 | To show the shortcut menu
F10 | To make the menu bar active
ALT+SPACEBAR | To show the program icon menu (on the program title bar)
DOWN ARROW or UP ARROW | With the menu or submenu is visible, to select the next or previous command
LEFT ARROW or RIGHT ARROW | To select the menu to the left or right; or, when a submenu is visible, to switch between the main menu and the submenu
HOME or END | To select the first or last command on the menu or submenu
ALT | To close the visible menu and submenu at the same time
ESC | To close the visible menu; or, with a submenu visible, to close the submenu only


 About the Microsoft Office Shortcut Bar

About the Microsoft Office Shortcut Bar

The Microsoft Office Shortcut Bar provides single-click access to the resources you use most often. You can quickly start a new budget proposal, locate and open a slide presentation, send an e-mail message, schedule an appointment, or create a task, note, contact, or journal entry in Microsoft Outlook.

Working with the Office Shortcut Bar

You can drag the Office Shortcut Bar to any location on the screen and — if it's docked — you can hide it until you need it by clicking Auto Hide on the Office Shortcut Bar menu [image]. When you're ready to show the Office Shortcut Bar again, just point to the area where it's docked.

To quickly create any type of file from the Office Shortcut Bar — for example, an Office Binder or a Microsoft Excel workbook — click New Office Document [image] . Click the tab that contains the type of file you want to create, and then double-click the file or template you want.

To quickly open files from the Office Shortcut Bar, click Open Office Document [image] , locate the file you want in the folder list, and then double-click the file.

Customizing the Office Shortcut Bar toolbar

The first time you use Office, the Office Shortcut Bar shows only the Office toolbar. More buttons and toolbars are available but hidden. To show hidden buttons or toolbars, right-click the background of any toolbar on the Office Shortcut Bar, and then click Customize on the shortcut menu. For example — if you show the Desktop toolbar on the Office Shortcut Bar, you can easily open Windows desktop files and programs even when you can't see the desktop. To show a different toolbar on the Office Shortcut Bar, click the icon that represents the toolbar. To show the name of a button or toolbar, rest the pointer on the button or toolbar icon until its name appears.

You can also add your own toolbars and buttons. To add frequently used files and programs as toolbar buttons, drag them onto the Office Shortcut Bar from Windows Explorer or My Computer.

Installing the Office Shortcut Bar

If the Office Shortcut Bar isn't available, run Office Setup again to install it. When you install the Office Shortcut Bar, you can configure it to run automatically when you start Windows. Learn how to install a program or component of Office.


 Save a data access page to an FTP site

Save a data access page to an FTP site

To do this procedure, your company must have an intranet, or you must have access to an Internet site that supports saving files. In addition, you must have access rights to save, and you must add the FTP site to your list of FTP locations. For information about adding an FTP site to the list of Internet sites, click [image] .

  1. If the data access page you want to save to an FTP site isn't already open, open it in Page view or Design view. The page you want to save can be a new data access page that has never been saved or an existing data access page.

  2. On the File menu, click Save As.

  3. In the Save As dialog box, type a name for the link to the data access page and click OK.

  4. In the Save As Data Access Page dialog box, click FTP Locations in the Save In box.

  5. In the list of FTP sites, double-click the site you want, and then double-click the location you want to save the data access page to.

    Note You must have write permissions for the FTP location to save the data access page there.

  6. In the File name box, type a name for the .htm file.

  7. Click Save.


 Conditions and values in the Find dialog box

Conditions and values in the Find dialog box

The conditions available depend on the property selected. Some conditions require a value. When you select a property and a condition, if the Value box is available, the condition requires a value.

You can use operators such as And and Or in the Value box to separate multiple values. For example, to find files that either Mary or John authored, click Author in the Property box. Click Includes Words in the Condition box, and then type Mary or John in the Value box.

Text values

You can use wildcards in the Value box with the Includes Words condition. Type a question mark (?) to find any single character, or an asterisk (*) to find any string of characters. For example, s?t finds "sat" and "set"; s*d finds "sad" and "started."

Number values

To use the Any Number Between condition, type the two numbers you want the value to be between in the Value box, separated by and. For example, type 1 and 5.

Date values

To use the Any Time Between condition, type two dates in the Value box, separated by and. For example, type March 1, 1996 and March 30, 1996.

Note You will not be able to find a file by searching the text within a Microsoft Access database or Microsoft Access project file.


Use shortcut keys for toolbars

Press | Using a toolbar
F10 | To make the menu bar active
CTRL+TAB or CTRL+SHIFT+TAB | To select the next or previous toolbar
TAB or SHIFT+TAB | When a toolbar is active, to select the next or previous button or menu on the toolbar
ENTER | When a menu on a toolbar is selected, to open the menu
ENTER | When a button is selected, to perform the action assigned to a button
ENTER | When the text box is selected, to enter text in a text box
DOWN ARROW or UP ARROW | When a drop-down list box or drop-down menu on a button is selected, to move through options in the list or menu; then press ENTER to select the option you want


 The Office Assistant doesn't show the Help topic I want.

The Office Assistant doesn't show the Help topic I want.

Language-specific information

If you don't see the Help topic you want, click None of the above, look for more help on the Web in the Office Assistant balloon. Information on finding Help topics appears and provides you with two suggestions for finding the Help you want. Click search tips for guidelines on how to narrow the list of Help topics by rephrasing your question to the Assistant or by using the Index in Help.

If you still can't find the Help you want, click Send and go to the Web to start your Web browser and connect you to a Web site to look for more Help. You can also describe what you were trying to do at the time you asked the Assistant for Help. Your question and any comments you provide will be collected and used to improve future versions of the Help system.

Note Depending on your system configuration, None of the above, look for more help on the Web may not be available on your computer. You must have a Web browser installed on your computer and access to the Internet to use this feature. If this feature isn't available, see your system administrator.


The Office Assistant is distracting.

Choose a different Office Assistant Some Assistants are more active than others. To choose a different one, right-click the Assistant, and then click Choose Assistant on the shortcut menu. On the Gallery tab, click Back or Next to see the available Assistants. The Office Logo is the least active of the Assistants.

Limit its movements Click the Assistant, and then click Options. On the Options tab, clear the Move when in the way check box. Clearing this option also limits the movement of floating toolbars.

Move the Assistant Drag the Assistant to another location on your screen.

Hide the Assistant On the Help menu, click Hide the Office Assistant.

Turn off the Assistant Click the Assistant, and then click Options. On the Options tab, clear the Use the Office Assistant check box.

Turn off its sounds Click the Assistant, and then click Options. On the Options tab, clear the Make sounds check box.


 When I click a hyperlink, an error message appears.

When I click a hyperlink, an error message appears.

  • The destination of the hyperlink may have been removed or renamed.

  • The destination of the hyperlink may have been moved to another location. If the path to the destination was created as a fixed file location, which identifies the destination by its full address — such as C:\My Documents\Sales.doc — and the destination was moved to another location, then the link will be broken. To change the hyperlink, right-click the hyperlink, point to Hyperlink on the shortcut menu, and then click Edit Hyperlink.

  • If the destination of the hyperlink is on the Internet, you must have access to the Internet. If you have access to the Internet, the site may be too busy. Try to open the file later.

  • If the destination of the hyperlink is on your company's intranet, check your network connections to make sure the network server you use is running. See your administrator to make sure you have access to the server.


How can I get to the Customize dialog box after removing the Toolbars command or the View menu?

  • To customize a toolbar, menu bar, or shortcut menu after removing the Toolbars command from the View menu, or after removing the View menu, right-click any toolbar or menu bar and then click Customize on the shortcut menu.

  • To restore the View menu to its original set of commands, including the Toolbars command, right-click any toolbar or the menu bar, and then click Customize on the shortcut menu. Right-click the View menu on the menu bar, and then click Reset on the shortcut menu.

  • To restore all the menus and commands on the built-in menu bar, including the View menu, right-click any toolbar or the menu bar, and then click Customize on the shortcut menu. On the Toolbars tab, click the name Menu Bar, and then click Reset.


Values for the PaperSize Member

Value | Paper size
1 | Letter (8.5 x 11 in.)
2 | Letter Small (8.5 x 11 in.)
3 | Tabloid (11 x 17 in.)
4 | Ledger (17 x 11 in.)
5 | Legal (8.5 x 14 in.)
6 | Statement (5.5 x 8.5 in.)
7 | Executive (7.25 x 10.5 in.)
8 | A3 (297 x 420 mm)
9 | A4 (210 x 297 mm)
10 | A4 Small (210 x 297 mm)
11 | A5 (148 x 210 mm)
12 | B4 (250 x 354 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)
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


Learn about language-specific information

Language-specific Help topics apply only if the language-specific feature is available. Learn about working in another language or installing the proofing tools for another language, or see your system administrator for more information.


 Ways to send e-mail messages

Ways to send e-mail messages

You can set message options to determine how and when the output of a database object, or data access page is delivered, and the response required from the recipient, in the following ways:

Set the importance and sensitivity level You can set the level of importance for a message to indicate if the recipient needs to read your message immediately. If you want a reply to your message by a certain date and time, you can set a flag to remind the recipient to respond. You can also mark the sensitivity of the message content as private, personal, or confidential.

Set the security level If you and the recipients of your messages use Microsoft Exchange Server, you can sign a message with a digital signature, or seal (encode) a message to ensure that the message is not readable to anyone other than the recipients that you select.

Track messages and replies You can track your messages by receiving notification when your message is delivered and when it's read by the recipient. To easily find, sort, filter, or group messages, you can assign a keyword or phrase to a message. You can also add voting buttons to a message so that that others vote on an issue through e-mail.

Set delivery options You can use an expiration date to show that the content of a message is no longer up-to-date. You can have the message saved in a specified folder in Microsoft Outlook after you send it. You can also specify if you want another recipient to receive replies to your message.

Return to Set options for sending an e-mail message


 About adding security to messages

About adding security to messages

You can add two security features to the messages that you send. You can sign a message with a digital signature to ensure that the message is not altered by someone else. Or you can seal (encode) a message to ensure that the message and its attachments are not readable to anyone other than the recipients you select.

You must obtain a keyword to your security file from your system administrator to seal or digitally sign a message, and the recipients of your message must provide their passwords to open your sealed message or verify your digital signature.

Note These security features apply only within your organization, and only if you and the recipients of your messages use Microsoft Exchange Server. Your system administrator must set up the security features on your computers.

Return to Add security to messages


 Create a script on a Web page

Create a script on a Web page

Microsoft Visual Basic Scripting Edition (VBScript) is the default script language added to your Web page. Change the default script language.

  1. Open the Web page in Design view or Page view.

  2. On the Tools menu, point to Macro, and then click Microsoft Script Editor.

  3. In the Microsoft Script Editor, write your script. Learn about the Microsoft Script Editor.


Add security to messages

What do you want to do?

Seal all outgoing messages

Add a digital signature to all outgoing messages

Not sure which choice you want?


Add voting buttons to an e-mail message

  1. Display the message header by sending a database object as an attachment or sending a data access page as the body of an e-mail message.

  2. Click Options.

  3. Under Voting and Tracking options, click Use voting buttons, and then click the voting button names you want to use in the box.

    To create your own voting button names, delete the default button names, and then type any text you want. Separate the text with semicolons. For example: Small;Large;Extra Large.

  4. To track the voting responses, select the Save sent message to check box, and then enter the folder name where you want the message saved.

Notes

  • For information about viewing vote responses, see Microsoft Outlook Help.

  • This procedure is applicable only if you installed Outlook in Corporate or Workgroup mode. Learn about how to get Outlook installation information.


Assign a message to a category

  1. Display the message header by sending a database object as an attachment or sending a data access page as the body of an e-mail message.

  2. Click Options, and then click Categories.

  3. In the Available categories list, select the check boxes next to the categories you want.

  4. To create a new category, click the Master Category List button.

  5. In the New category box, type a name for the category, and then click Add.

  6. To create more categories, repeat step 5.

  7. Click OK twice, and then click Close.

Tip You can also assign a message to a category by clicking Options, and then typing the category name in the Categories box. If you use this method, make sure that you spell and capitalize the category name correctly or the message won't be assigned to a category in the Master Category List. Categories that are not included in the Master Category List are not available to assign other messages to.


Delay delivery of a message

Note This feature is available only with Microsoft Exchange Server.

  1. Display the message header by sending a database object as an attachment or sending a data access page as the body of an e-mail message.

  2. Click Options.

  3. Under Delivery options, click Do not deliver before, and then enter the delivery date that you want.


 Have replies to your message sent to another user

Have replies to your message sent to another user

  1. Display the message header by sending a database object as an attachment or sending a data access page as the body of an e-mail message.

  2. Click Options.

  3. Under Delivery options, select the Have replies sent to check box.

  4. Type the name of another user, or click Select Names to select from a list.

Note You cannot have replies sent to a personal distribution list.


 Load or unload a Component Object Model (COM) add-in program

Load or unload a Component Object Model (COM) add-in program

If you are not a developer, you do not need to load or unload a Component Object Model (COM) add-in because most COM add-ins include an install/uninstall program.

  1. If you have already added the COM Add-Ins command to the Tools menu, skip to step 6.

  2. On the Tools menu, click Customize, and then click the Commands tab.

  3. In the Categories box, click Tools.

  4. Drag COM Add-Ins from the Commands box to the Tools menu. When the menu commands are displayed, point to the location where you want the COM Add-Ins command to appear on the menu, and then release the mouse button.

  5. Click Close.

  6. On the Tools menu, click COM Add-Ins.

    To load an add-in, select the check box next to the add-in name in the Add-Ins available list.

    If the add-in you want isn't in the Add-Ins available list, click Add, locate the add-in, and then click OK.

    To unload an add-in from memory but keep its name in the list, clear the check box next to the add-in name.

    To remove an add-in from the list and also from the registered list of add-ins in the registry file, select its name, and then click Remove.

Note Unloading or removing an add-in doesn't remove the add-in file from your computer.

Tip For information about creating a COM add-in, see the Microsoft Office 2000/Visual Basic Programmer's Guide.


Make a sent message unavailable after a specified date

  1. Display the message header by sending a database object as an attachment or sending a data access page as the body of an e-mail message.

  2. Click Options.

  3. Under Delivery options, click Expires after, and then enter the expiration date.


Mark a message as private, personal, or confidential

  1. Display the message header by sending a database object as an attachment or sending a data access page as the body of an e-mail message.

  2. Click Options.

  3. Under Message settings, click the sensitivity level that you want.

Note Marking a message Private prevents the message from being modified after you send it.


Receive notification when a message is delivered

  1. Display the message header by sending a database object as an attachment or sending a data access page as the body of an e-mail message.

  2. Click Options.

  3. Under Voting and Tracking options, click Request a delivery receipt for this message.

Notes

  • This option applies to the current message only.

  • This procedure is applicable only if you installed Microsoft Outlook in Corporate or Workgroup mode. Learn about how to get Outlook installation information.


Receive notification when a message is read

  1. Display the message header by sending a database object as an attachment or sending a data access page as the body of an e-mail message.

  2. Click Options.

  3. Under Voting and Tracking options, click Request a read receipt for this message.

Notes

  • This option applies to the current message only.

  • This procedure is applicable only if you installed Microsoft Outlook in Corporate or Workgroup mode. Learn about how to get Outlook installation information.


Save a copy of a message you send

  1. Display the message header by sending a database object as an attachment or sending a data access page as the body of an e-mail message.

  2. Click Options.

  3. Under Delivery options, click Save sent message to.

    To specify a folder you want the message saved in, click the Browse button.

Note This option applies to the current message only.


Add a digital signature to all outgoing messages

This feature applies only within your organization, and only if you and the recipients of your messages use Microsoft Exchange Server. Your system administrator must have set up security on your computers.

  1. Display the message header by sending a database object as an attachment or sending a data access page as the body of an e-mail message.

  2. Click Options.

  3. Under Security, click Add digital signature to outgoing message.


Seal all outgoing messages

This feature applies only within your organization and only if you and the recipients of your messages use Microsoft Exchange Server. Your system administrator must have set up security on your computers.

  1. Display the message header by sending a database object as an attachment or sending a data access page as the body of an e-mail message.

  2. Click Options.

  3. Under Security, click Encrypt message contents and attachments.


Set the importance level for a message

  1. Display the message header by sending a database object as an attachment or sending a data access page as the body of an e-mail message.

  2. Do one of the following:

    To mark the message as very important, click Importance: High [image].

    To mark the message as not important, click Importance: Low [image].

    To remove the importance level symbol from the message, click the importance button again.

Note To automatically mark all messages you send with the same importance level, click Options. Under Message settings, click the importance level you want.


Set a message flag

Flagging a message is a quick way for you to either mark a message to follow up or mark a message with a request for someone else. When the recipient receives a message with a flag, a comment on the purpose of the flag appears at the top of the message. If you set a due date, this will also appear.

  1. Display the message header by sending a database object as an attachment or sending a data access page as the body of an e-mail message.

  2. Click Flag for Follow Up [image].

  3. In the Flag to box, select one of the flags from the list or type your own.

    To clear a flag you've already set, click Clear Flag.

  4. In the Reminder box, select a date or type your own to set a due date.


 About assigning messages to categories

About assigning messages to categories

A category is a keyword or phrase that helps you keep track of items so that you can easily find, sort, filter, or group them. Use categories to keep track of different types of items that are related but stored in different folders.

Categories also give you a way to keep track of items without putting them in separate folders. For example, you can keep business and personal tasks in the same task list and use the Business and Personal categories to view the tasks separately.

Outlook supplies a list of categories that you can assign items to, called the Master Category List. You can use this list as it is or add your own categories to it.

Items can be assigned to more than one category.

For more information about categories, see Outlook Help.

Next step

Assign a message to a category


 My data access page is displaying the wrong characters for a language.

My data access page is displaying the wrong characters for a language.

If a data access page is encoded for a different language, Microsoft Access tries to determine the language. If Access displays the wrong characters for that language when you open the page in a browser, you can select the language that you think the page is encoded in. Some languages have more than one encoding, so try each encoding until you can read the text.

  1. Open the data access page in Design view.

  2. On the Tools menu, click Options.

  3. Click the General tab, and then click Web Options.

  4. In the Web Options dialog box, click the Encoding tab.

  5. Under Reload the current document as, select the language that you think the page is encoded in.


 I don't want to keep my supporting data access page files in a folder.

I don't want to keep my supporting data access page files in a folder.

When you save a data access page in Design view, all supporting files — such as bullets, background textures, and graphics — are by default stored in a separate folder. If you do not want to use a separate folder, do the following:

  1. Open the data access page in Design view.

  2. On the Tools menu, click Options.

  3. Click the General tab, and then click Web Options.

  4. In the Web Options dialog box, click the Files tab.

  5. Under File names and locations, clear the Organize supporting files in a folder check box.


 I saved my data access page to a file server, and now some people can't find or view it.

I saved my data access page to a file server, and now some people can't find or view it.

If you use a long file name to save your data access page in Design view, users running Windows 3.1 won't be able to find or open your data access page, because Windows 3.1 recognizes and supports only short file names (maximum of eight characters, plus a three-character file extension). To always save files with short file names, do the following:

  1. Open the data access page in Design view.

  2. On the Tools menu, click Options.

  3. Click the General tab, and then click Web Options.

  4. In the Web Options dialog box, click the Files tab.

  5. Under File names and locations, clear the Use long file names whenever possible check box.


 The graphics and text on my data access page look different on another computer.

The graphics and text on my data access page look different on another computer.

If your data access page looks different from what you expect, check the browser settings. Although all Web browsers support the same language (HTML), there are some differences among browsers. Some support different versions of HTML and different HTML extensions. Custom options can be set in browsers, such as the default text and background colors, and whether or not graphics are displayed. Consider testing your page in different browsers — some of which are available for downloading on the Web — and with different monitor settings, to see whether all of your page elements appear.


 The Clipboard toolbar no longer appears when I copy and paste items.

The Clipboard toolbar no longer appears when I copy and paste items.

If you close the Clipboard toolbar three times in a row without using the Paste All button or any of the item buttons, the Clipboard toolbar will no longer appear automatically. To show the Clipboard toolbar again, point to Toolbars on the View menu, and then click Clipboard. You can also show the Clipboard toolbar again by copying an item two times consecutively.

When you display the Clipboard toolbar manually and then click Paste All [image] or click an individual item, the count is reset. From that point on, the Clipboard toolbar appears automatically again.


 Other people in the online meeting see a crosshatch pattern on the screen.

Other people in the online meeting see a crosshatch pattern on the screen.

Make sure no windows are covering your Microsoft Access database, Microsoft Access project, or data access page.

  • Quit programs you are not using.

  • Minimize other windows on your desktop.


 I can't add additional items to the Office Clipboard.

I can't add additional items to the Office Clipboard.

You might have copied more than 12 items The Office Clipboard can hold up to 12 items. If you try to copy a thirteenth item in a Microsoft Office program, a message asks if you want to discard the first item on the Office Clipboard and add the new item to the end of the clipboard. If you click OK, the next time you copy an item from any program, the Office Clipboard will automatically discard the first item and add the new item. If you click Cancel, any new items you copy won't be added to the Office Clipboard. You won't see the message again until you clear and then refill the Office Clipboard.

You may have copied large items If you copy large items to the Office Clipboard, the Office Clipboard may stop adding items even if there are fewer than 12. To begin copying items again, click Clear Clipboard [image] on the Clipboard toolbar.


 I can't automatically create a backup copy of my data access page.

I can't automatically create a backup copy of my data access page.

When you save a data access page in Design view, a backup copy is not automatically created. To save a copy of a data access page, click Save As on the File menu. In the Save Data Access Page <object name> To box, enter a new name for the data access page, and then click Save.


I can't find a menu command, toolbar button, or dialog box option.

The menu might not be expanded If arrows Double arrows pointing down appear at the bottom of the menu, the menu item might be available on the expanded menu. Click the arrows Double arrows pointing down, and then click the command you want. You can also double-click the menu to expand it. Or you can specify that Access display the entire set of commands for all menus.

The toolbar might be on the same row as another toolbar The toolbar button might not appear on the toolbar because there is not enough room to display all the buttons. Click More Buttons [image], and then click the button you want. Or you can show all the buttons on the toolbar.

The Microsoft Office component might not be installed Run the installer again, and install the component.

You might have a different language setting The command or control doesn't appear if you don't have editing enabled for the language that the command or control applies to. You need to enable editing for the language you want to work with. Learn about multilingual editing and proofing tools kits.


 I can't print or save an Access database, Access project, or data access page opened from an online meeting to my local printer or hard disk. meeting to my local printer or hard disk. meeting to my local printer or hard disk.

I can't print or save an Access database, Access project, or data access page opened from an online meeting to my local printer or hard disk.

You can only print or save to the printer or hard disk from the Microsoft Access database, Microsoft Access project, or data access page that hosted the online meeting. When you click Print, you print the file on the printer of the person hosting the online meeting. When you click Save, you save the file to the host's hard disk or server, not your own.

If you want a copy of the file you're collaborating on, ask the host of the online meeting to send you a copy of the file, or copy the document contents to a file on your computer.

Note You can save only if you have control of the Access data file.


I don't see some items that other people in the online meeting see.

Make sure your screen resolution settings match the settings of the other online meeting participants. How to set your screen resolution.


 I moved my data access page to another location and now some of the links are broken.

I moved my data access page to another location and now some of the links are broken.

When you save your file as a data access page in Design view, all supporting files — such as bullets, background textures, and graphics — are by default organized in a supporting folder. If you move or copy your data access page to another location, you must also move the supporting folder so that you maintain all links to your data access page.


I want the menus to look like they did in Office 97.

  1. On the Tools menu, click Customize, and then click the Options tab.

  2. Clear the Menus show recently used commands first check box.

Note The Menus show recently used commands first check box affects all of your Microsoft Office programs.


 My settings aren't available when I log on.

My settings aren't available when I log on.

The user profile might not be valid for the operating system A user profile is only valid on the operating system for which it was created. For example, a Windows NT user profile cannot be used on a computer running Windows 95. If your user profile is created in Windows 95, and you log on to a computer running Windows NT, you won't see any of your settings. You need to make sure that you log on to a computer that uses the same operating system that the user profile was created in.

The computer might not be configured for multiple users If you log on to a computer running Windows 95, the computer might not be configured to allow settings for multiple users. To enable multiple users to personalize settings on a computer running Windows 95, do the following:

  1. On the Windows Start menu, point to Settings, and then click Control Panel.

  2. Double-click the Passwords Set of keys icon, and then click the User Profiles tab.

  3. Click Users can customize their preferences and desktop settings. Windows switches to your personal settings whenever you log in.

Your user account might not be enabled Your system administrator might not have configured your user account on the network to use roaming user profiles. If you don't see any of your settings when you log on to a computer, see your system administrator.

Multiple logons differ between operating systems If you're logged on to more than one computer at the same time, the changes you make to your settings on one computer may or might not be available immediately on another computer because of differences between operating systems. On computers running Windows 95 and Windows NT 4.0, the changes you made on the last computer you logged off are the settings that are copied to your user profile and used the next time you log on. On computers running Windows 2000, you'll see changes you make to your settings immediately because your user profile is copied to the server at regular intervals.


My custom templates aren't appearing on the correct tab.

You should save your custom templates in the appropriate subfolder within your Templates folder. You can find the Templates folder in the following location:

Root\OS\Profiles\User_name\Application Data\Microsoft\Templates

where Root is a server location or a directory on a drive from which all other folders branch (for example, c:\), OS is the operating system folder (for example, Windows or Winnt), and User_name is your user name.

Templates in the Templates folder appear on the General tab; templates in subfolders of the Templates folder appear on tabs with the same names as the subfolders. For example, if you create a subfolder under the Templates folder called Reports, a Reports tab will appear in the New dialog box (File menu).

Note In Windows 2000, the path for the Templates folder is Root\Users\User_name\Application Data\Microsoft\Templates.


I want the menus to stop expanding automatically.

  1. On the Tools menu, click Customize, and then click the Options tab.

  2. Clear the Show full menus after a short delay check box.

Note The Show full menus after a short delay check box affects all of your Microsoft Office programs.


 The name of the supporting folder for a data access page is in another language.

The name of the supporting folder for a data access page is in another language.

When you save your data access page in Design view, all supporting files — such as bullets, background textures, and graphics — are by default organized in a supporting folder. By default, the name of the supporting folder is the name of the data access page plus an underscore (_), a period (.), or a hyphen (-) and the word "files." The word "files" will appear in the language of the version of Microsoft Office 2000 that was used to save the file as a data access page. For example, suppose you use the Dutch language version of Office 2000 to save a file called Page1 as a data access page. The default name of the supporting folder would be Page1_bestanden. Learn more about the default name for supporting folders.

Note If you save your data access page with a short file name (maximum of eight characters, plus a three-character file extension) by clearing the Use long file names whenever possible check box in the Web Options dialog box, the supporting folder is the name of the data access page without the word "files."


 The name of the person I want to invite to an online meeting is not in the list.

The name of the person I want to invite to an online meeting is not in the list.

Connect to another server

  • In the Place a Call dialog box, select another directory in the Directory list.

Send an e-mail message or telephone the person

Let the person know that you want to have an online meeting. Find out what directory server they are logged on to, or use their computer name or Internet protocol (IP) address.


 The Paste All button is not available.

The Paste All button is not available.

In some cases, the Paste All button on the Clipboard toolbar is not available even when individual items are available for pasting:

In all Microsoft Office programs Paste All is not available if any individual item on the Office Clipboard cannot be pasted into the program.

In Microsoft Access Paste All is only available in data access pages.

If the Paste All button is not available, you might still be able to paste specific items.


The Clipboard toolbar is not available.

You might be using a program other than Microsoft Excel, Microsoft Word, Microsoft Access, Microsoft Outlook, or Microsoft PowerPoint The Clipboard toolbar is available only in Excel, Word, Access, Outlook, and PowerPoint. The Clipboard toolbar is not available in the Visual Basic Editor. However, if the Office Clipboard is displayed in any Microsoft Office program, any items you cut or copy in any program are collected automatically.

The Copy, Cut, and Paste commands might not be available The Copy and Paste All buttons and the collected items on the Clipboard toolbar are not available anywhere you cannot use the Copy, Cut, and Paste commands.


Queries: What they are and how they work

1 2 3


Queries: What they are and how they work


Display text only or an icon and text on a menu command

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the menu bar, shortcut menu, or toolbar with the menu command you want to change.

  3. With the Customize dialog box open, click the menu on the menu bar or toolbar, or click the shortcut menu that has the command you want to change.

  4. Right-click the command on the menu, and then click the option you want on the shortcut menu.

Notes

  • Some commands do not have an icon associated with them and can only be displayed on a menu as text.

  • On a menu, a command can't be displayed as an icon only. However, if the command has the Default Style format, when you copy or move the menu command to a toolbar or menu bar, the command automatically appears as an icon on the toolbar or menu bar (which is the default for both types of bars).

  • If you change how a command appears on a built-in menu (for example, the Edit menu), it will be changed in all views that have that menu with that command.


Reports What They Are And How They Work

1 2 3


Reports: What they are and how they work


The Office Assistant balloon disappeared.

  • A tip or message balloon might appear in front of another balloon. Close the balloon in front to see the one behind it.

  • Some message balloons close automatically when you click in the Microsoft Access window. These are informational messages that don't require a response. For example, when you check spelling a message tells you when you're finished. You won't see this type of message again unless you repeat the action that causes it to appear — for example, when you check spelling again.


 I can't access the Microsoft Office Update Web site.

I can't access the Microsoft Office Update Web site.

  • To use Office on the Web (Help menu), you must have access to the Internet — either through your company's intranet or through a modem on your computer or network — and you must have an Internet account through an Internet service provider. For more information, see the Microsoft Office 2000 Resource Kit. Learn about obtaining the Microsoft Office 2000 Resource Kit.

  • The settings to connect your computer to the Internet might not be correct. To make sure they are, double-click the Internet icon in the Windows Control Panel.

  • Your modem might not be working correctly. For more information, see Modem Troubleshooter in Microsoft Windows Help.

  • The Microsoft Office Update Web site might be temporarily unavailable. If you can access to other Web sites, wait awhile and then try again.


Sections Of A Form

1 2 3


Sections of a form


Sections Of A Report

1 2 3


Sections of a report


Tables: What they are and how they work

1 2 3 4 5


Tables: What they are and how they work


Values for the TTOption Member

Value | Meaning
1 | Print TrueType fonts as graphics. This is the default for dot-matrix printers.
2 | Download TrueType fonts as soft fonts (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.


Ways To Customize A Form

1 2 3 4 5 6


Ways to customize a form


Ways to customize a query

1 2 3 4 5


Ways to customize a query


Ways To Customize A Report

1 2 3 4 5 6


Ways to customize a report


Ways to customize a table

1 2 3 4 5 6


Ways to customize a table


Ways to specify multiple criteria in a query

One field using Or
One field using And
Two fields using Or
Two fields using And
Three fields using And and Or


Ways to specify multiple criteria in a query


Ways To Work With Data In A Form

1 2 3 4


Ways to work with data in a form


Ways to work with data in a query's datasheet

1 2 3 4 5 6 7


Ways to work with data in a query's datasheet


Ways to work with data in a table's datasheet

1 2 3 4 5 6 7


Ways to work with data in a table's datasheet


Restore how a built-in toolbar button or menu command appears

  1. On the View menu, point to Toolbars, and then click Customize.

  2. Show the toolbar, menu bar, or shortcut menu with the button or menu command you want to restore.

  3. With the Customize dialog box open, do one of the following:
    • To restore a toolbar button, right-click (on the toolbar) the button you want to restore, and then click Reset on the shortcut menu.

    • To restore a menu command, click the menu on the menu bar or toolbar, or click the shortcut menu that contains the command you want to restore. Right-click the menu command, and then click Reset on the shortcut menu.

Note The Reset command is not available for a button that displays a list when you click it. If you altered the image on a built-in button or command, you can restore just the original image by right-clicking the button or command while the Customize dialog box is displayed, and then clicking Reset Button Image on the shortcut menu.


About formatting charts

To display this topic, click the graphic:

To display this topic, click the graphic.

To display this topic by using the keyboard, press F6 to activate the topic pane, press the TAB key to select the graphic, and then press ENTER.


 Type ¢, £, ¥, ®, and other characters not on the keyboard

Type ¢, £, ¥, ®, and other characters not on the keyboard

  1. On the Windows Start menu, point to Programs, point to Accessories, and then click Character Map.

    If Character Map is not available, see Windows Help for information about how to install a Windows component.

  2. In the Font box, select the font that contains the character you want.

  3. In the character grid, click the character you want.

  4. Click Select, and then click Copy.

  5. Switch to your database, and then place the insertion point where you want to paste the character.

  6. Click Paste [image] .

  7. If the character looks different from the one you selected, select the character and apply the same font you selected in Character Map.

Tip Character Map shows the key combination you can use in Microsoft Access to insert the selected character. To type numbers in the key combination, use the numeric keypad, not the keyboard.