Vous êtes sur la page 1sur 256

What is a database?

A database is a tool for collecting and organizing information. Databases can store information about people, products, orders, or anything else. Many databases start as a list in a word-processing program or spreadsheet. As the list grows bigger, redundancies and inconsistencies begin to appear in the data. The data becomes hard to understand in list form, and there are limited ways of searching or pulling subsets of data out for review. Once these problems start to appear, it's a good idea to transfer the data to a database created by a database management system (DBMS), such as Office Access 2007.

A computerized database is a container of objects. One database can contain more than one table. For example, an inventory tracking system that uses three tables is not three databases, but one database that contains three tables. Unless it has been specifically designed to use data or code from another source, an Access database stores its tables in a single file, along with other objects, such as forms, reports, macros, and modules. Databases created in the Access 2007 format have the file extension .accdb, and databases created in earlier Access formats have the file extension .mdb. You can use Access 2007 to create files in earlier file formats (for example, Access 2000 and Access 2002-2003).

Using Access, you can:

Add new data to a database, such as a new item in an inventory

Edit existing data in the database, such as changing the current location of an item

Delete information, perhaps if an item is sold or discarded

Organize and view the data in different ways

Share the data with others via reports, e-mail messages, an intranet , or the Internet

The parts of an Access database


The following sections are short descriptions of the parts of a typical Access database.

Tables

Forms Reports Queries Macros Modules

Tables
A database table is similar in appearance to a spreadsheet, in that data is stored in rows and columns. As a result, it is usually quite easy to import a spreadsheet into a database table. The main difference between storing your data in a spreadsheet and storing it in a database is in how the data is organized.

A table contains data about a particular subject, such as employees or products. Each record in a table contains information about one item, such as a particular employee. A record is made up of fields, such as name, address and telephone number. A record is also commonly called a row, and a field is also commonly called a column.

Record or row

Field or column

Your database can contain many tables, each storing information about a different subject. Each table can contain many fields of different types, including text, numbers, dates, and pictures.

The following list shows some common examples of tables you might create.

A customers table that lists your companys customers and their addresses

A catalog of products you sell, including prices and pictures for each item

A tasks table that tracks tasks and due dates

An inventory of equipment or stock on hand

You should plan and design your database carefully to ensure its correctness and to avoid having to make too many changes later.

Forms
Forms are sometimes referred to as "data entry screens." They are the interfaces you use to work with your data, and they often contain command buttons that perform various commands. You can create a database without using forms by simply editing your data in the table datasheets. However, most database users prefer to use forms for viewing, entering, and editing data in the tables.

Forms provide an easy-to-use format for working with the data, and you can also add functional elements, such as command buttons, to them. You can program the buttons to determine which data appears on the form, open other forms or reports, or perform a variety of other tasks. For example, you might have a form named "Customer Form" in which you work with customer data. The customer form might have a button which opens an order form where you can enter a new order for that customer.

Forms also allow you to control how other users interact with the data in the database. For example, you can create a form that shows only certain fields and allows only certain operations to be performed. This helps protect data and to ensure that the data is entered properly.

Reports
Reports are what you use to summarize and present data in the tables. A report usually answers a specific question, such as "How much money did we receive from each customer this year?" or "What cities are our customers located in?" Each report can be formatted to present the information in the most readable way possible.

A report can be run at any time, and will always reflect the current data in the database. Reports are generally formatted to be printed out, but they can also be viewed on the screen, exported to another program, or sent as email message.

Queries

Queries are the real workhorses in a database, and can perform many different functions. Their most common function is to retrieve specific data from the tables. The data you want to see is usually spread across several tables, and queries allow you to view it in a single datasheet. Also, since you usually don't want to see all the records at once, queries let you add criteria to "filter" the data down to just the records you want. Queries often serve as the record source for forms and reports.

Certain queries are "updateable," meaning you can edit the data in the underlying tables via the query datasheet. If you are working in an updateable query, remember that your changes are actually being made in the tables, not just in the query datasheet.

Queries come in two basic varieties: select queries and action queries. A select query simply retrieves the data and makes it available for use. You can view the results of the query on the screen, print it out, or copy it to the clipboard. Or, you can use the output of the query as the record source for a form or report.

An action query, as the name implies, performs a task with the data. Action queries can be used to create new tables, add data to existing tables, update data, or delete data.

Macros
Macros in Access can be thought of as a simplified programming language which you can use to add functionality to your database. For example, you can attach a macro to a command button on a form so that the macro runs whenever the button is clicked. Macros contain actions that perform tasks, such as opening a report, running a query, or closing the database. Most database operations that you do manually can be automated by using macros, so they can be great time-saving devices.

Modules
Modules, like macros, are objects you can use to add functionality to your database. Whereas you create macros in Access by choosing from a list of macro actions, you write modules in the Visual Basic for Applications (VBA) (Visual Basic for Applications (VBA): A macro-language version of Microsoft Visual Basic that is used to program Microsoft Windows-based applications and is included with several Microsoft programs.) programming language. A module is a collection of declarations, statements, and procedures that are stored together as a unit. A module can be either a class module or a standard module. Class modules are attached to forms or reports, and usually contain procedures that are specific to the form or report they're attached to. Standard modules contain general procedures that aren't associated with any other object. Standard modules are listed under Modules in the Navigation Pane, whereas class modules are not.

Create a new table


A simple database, such as a contact list, might use only a single table. Many databases, however, use several tables. When you create a new database, you create a new file on your computer that acts as a container for all of the objects in your database, including your tables.

You can create a table by creating a new database, by inserting a table into an existing database, or by importing or linking to a table from another data source such as a Microsoft Office Excel 2007 workbook, a Microsoft Office Word 2007 document, a text file, or another database. When you create a new blank database, a new empty table is automatically inserted for you. You can then enter data to start defining your fields.

Create a new table in a new database


1. Click the Microsoft Office Button , and then click New.

2.

In the File Name box, type a file name. To change the location, click the folder icon to browse.

3.

Click Create.

The new database is opened, and a new table named Table1 is created and opened in Datasheet view.

Create a new table in an existing database


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

On the Create tab, in the Tables group, click Table.

A new table is inserted in the database and the table is opened in Datasheet view.

Top of Page

Create a table based on a table template


To create a Contacts, Tasks, Issues, Events or Assets table, you might want to start with the table templates for these subjects that come with Office Access 2007. The table templates were designed to be compatible with the Microsoft Windows SharePoint Services 3.0 lists of the same name.

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

On the Create tab, in the Tables group, click Table Templates and then select one of the available templates from the list.

A new table is inserted, based on the table template you chose.

Top of Page

Import or link to create a table


You can create a table by importing or linking to information stored elsewhere. For instance, you can import or link to information in an Excel worksheet, SharePoint list, an XML file, another Access database, a Microsoft Office Outlook 2007 folder, and a number of other sources. When you import the information, you create a copy of the information in a new table in the current database. Conversely, when you link to the information, you create a linked table in the current database that represents a live link to the existing information that is stored elsewhere. Thus, when you change data in the linked table, you also change it in the original source too (with some exceptions see the note below). When information is changed in the original source by using another program, that change is visible in the linked table.

NOTE

In some cases, you cannot make changes to your data source through a linked table, most notably when

the data source is an Excel worksheet.

Create a new table by importing or linking to external data


1. To use an existing database, on the File menu, click Open.

2.

In the Open dialog box, select and open the database.

3.

To create a new database, on the File menu, click New.

In the File Name text box, type a file name. To change the location, click the folder icon.

Click Create.

The new database is opened, and a new table named Table1 is created and opened in Datasheet view.

4.

On the External Data tab, in the Import group, click one of the available data sources.

5.

Follow the instructions in the dialog boxes.

Access creates the new table and displays it in the Navigation Pane.

Add fields to a table in Datasheet view


You store the information items you want to track in fields (also called columns). For example, in a Contacts table you might create fields for LastName, FirstName, Telephone Number and Address, among others. For a Products table you might create Product Name, Product ID and Price.

It is important that you choose fields carefully. For example, it's usually a bad idea to create a field to store a calculated value. You can usually have Office Access 2007 calculate the value when needed instead. When choosing

fields, try to store information in its smallest useful parts. For instance, instead of a FullName, consider storing a LastName and a FirstName. Generally speaking, if you need to report, sort, search or calculate on an item of information, put it in a column by itself. For more information about designing a database and choosing fields, see the article Database design basics.

A field has certain defining characteristics. For example, every field has a Name that uniquely identifies the field within a table. A field also has a data type that's chosen to match the information to be stored. The data type determines the values that can be stored and the operations that can be performed, as well as how much storage space to set aside for each value. Every field also has an associated group of settings called properties that define the appearance or behavior characteristics of the field. For example, the Format property defines a field's display layout that is, how it should appear when displayed.

When you create a new table, the table opens in Datasheet view. You can immediately add a field by typing some information in the Add New Field column.

Add a new field to an existing table


1. Click the Microsoft Office Button , and then click Open.

2.

In Open dialog box, select and open the database.

3.

In the Navigation Pane, double-click one of the available tables to open it.

4.

Type your data in the cell below the Add New Field column header.

Add a new field to a new table


1. Click the Microsoft Office Button , and then click Open.

2.

In Open dialog box, select and open the database.

3.

On the Create tab, in the Tables group, click Table.

Access inserts a new table in the database and opens it in Datasheet view.

4.

Type your data in the cell below the Add New Field column header.

When you enter data in the new column, Office Access 2007 uses the information you type to recognize the appropriate data type for the field. For example, if you type a date in the column, such as 1/1/2006, Office Access 2007 sees the information you entered, recognizes it as a date, and sets the data type for the field to Date/Time. If Access doesn't have enough information from what you enter to guess the data type, the data type is set to Text.

The following table shows how automatic data type detection works in Datasheet view.

If you type: John http://www.contoso.com You can use any valid Internet protocol prefix. For example, http://, https://, and mailto: are valid prefixes.

Office Access 2007 creates a field with a data type of: Text Hyperlink

50000 50,000 50,000.99 50000.389 12/31/2006 The date and time formats recognized are those of your user locale.

Number, Long Integer Number, Long Integer Number, Double Number, Double Date/Time

December 31, 2006 10:50:23 10:50 am

Date/Time Date/Time Date/Time

17:50 $12.50 The currency symbol recognized is that of your user locale.

Date/Time Currency

21.75 123.00% 3.46E+03

Number, Double Number, Double Number, Double

In addition to determining the data type, Office Access 2007 may set the Format property, depending on what you enter. For example, if you type 10:50 am, Access sets the data type Date/Time and the Format property to Medium Time.

If you want to explicitly set the data type and format for a field, overriding the choice that Office Access 2007 makes, you can do so by using the commands in the Data Type & Formatting group on the Datasheet tab.

Explicitly set the data type


1. On the Datasheet tab, in the Data Type & Formatting group, click Data Type.

2.

Click the data type you want.

Explicitly set the format


1. On the Datasheet tab, in the Data Type & Formatting group, click Format.

2.

Click the format you want.

When you add a field by typing information into the cell below the Add New Field header, Office Access 2007 automatically assigns a name to the field. These names start with Field1 for the first field, Field2 for the second field, and so on. It is a good practice to use more descriptive field names. You can rename the field by right-clicking its header, and then clicking Rename Column on the shortcut menu.

Field names can consist of up to 64 characters (letters or numbers), including spaces. You should try to give fields descriptive names so that you can easily identify them when you view or edit records. For example, you might use field names such as Last Name, Address, and Home Phone.

Top of Page

Add fields by using field templates


Sometimes it is easier to choose from a predefined list of fields than to manually create a field. You can use the Field Templates task pane to choose from a list of predefined fields. Office Access 2007 comes with a set of built-in field templates that can save you considerable time when you create fields. To create a new field using a field template, you display the Field Templates pane, and then drag and drop one or more templates to the table that is opened in Datasheet view.

A field template is a predefined set of characteristics and properties that describes a field. The field template definition includes a field name, a data type, a setting for the field's format property, and also a number of other field properties that, when taken together, form a model that serves as the basis for creating a new field.

1.

Ensure that your table is in Datasheet view.

2.

On the Datasheet tab, in the Fields & Columns group, click New Field.

The Field Templates pane appears.

3.

Select one or more fields in the Field Templates pane and drag them to the table. When the insertion line appears, drop the fields in position.

The fields appear in the datasheet.

Field templates are models. They provide a basis from which you can create a new field. But it is not the only basis from which you can create a new field. In addition to creating a new field from a field template, you can also create a new field from an existing field in another table.

Top of Page

Add a field from an existing table


If you are using a database that contains multiple tables, you can add a field from another table. In fact, chances are good that some of those tables are related. In a relational database, you store information in separate subject-based tables, and then define relationships to provide your database management system with what it needs to bring the information together as needed. Office Access 2007 allows you to create a new field by adding it from another related table, or by adding it from another table for which you have not created a relationship. You add the field by using the Field List, which shows you fields available in other tables in your database.

Open the Field List pane

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, double-click the table in which you want to add an existing field.

The table opens in Datasheet view.

4.

On the Datasheet tab, in the Fields & Columns group, click Add Existing Fields.

The Field List pane appears.

The Field List pane lists all of the other tables in your database, grouped into categories. When you work with a table in Datasheet view, two categories appear in the Field List pane: Fields available in related tables, and Fields available in other tables. The first category lists all of the tables with which the table you have open has a relationship. The second category lists all of the tables with which your table does not have a relationship.

For more information about table relationships, see the article Create, edit or delete a relationship.

When you click the plus sign (+) next to a table to, you see a list of all of the fields available in that table. To add a field to your table, drag and drop the field you want from the Field List pane to the table in Datasheet view.

Add a field from the Field List pane


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, double-click the table in which you want to add an existing field.

The table opens in Datasheet view.

4.

On the Datasheet tab, in the Fields & Columns group, click Add Existing Fields.

The Field List pane appears.

5.

Click the plus sign (+) next to a table to display the list of fields in that table.

6.

Drag the field you want from the Field List pane to the table in Datasheet view.

7.

When the insertion line appears, drop the field in position.

The Lookup Wizard starts.

8.

Follow the instruction to complete the wizard.

After you have completed the wizard, the field appears in the table in Datasheet view.

NOTE

When you drag and drop a field from an unrelated table and then complete the Lookup Wizard, a new one-

to-many relationship is automatically created between the table in the Field List pane and the table you have open.

Top of Page

Set a field's data type in Datasheet view


Office Access 2007 does a good job of automatically detecting the data type for a field that you create in Datasheet view. Sometimes, however, you will need to override the decision that Access makes. For example, you might have existing products IDs that serve to identify the products you sell. If you type a numeric ID, such as 1003, into a table in Datasheet view, the automatic data type detection feature sets a numeric data type for the field. However, you should only use a numeric data type for fields that will be involved in arithmetic calculations. Normally, identifiers such as a product ID should be stored as the Text data type.

If you want to explicitly set the data type and format for a field, overriding the choice that Office Access 2007 makes, you can do so by using the commands in the Data Type & Formatting group on the Data tab.

Explicitly set the data type


1. On the Datasheet tab, in the Data Type & Formatting group, click Data Type.

2.

Click the data type you want.

Use the following table to determine the correct data type.

Explicitly set the format


1. On the Datasheet tab, in the Data Type & Formatting group, click Format.

2.

Click the format you want.

The following table describes the data types available for fields in Office Access 2007.

Data type Text

Stores Alphanumeric characters Use for text, or text and numbers that are not used in calculations (for example, a product ID).

Size Up to 255 characters.

Memo

Alphanumeric characters (longer than 255 characters in length) or text with rich text formatting. Use for text greater than 255 characters in length, or for text that uses rich text formatting. Notes, lengthy descriptions, and paragraphs with formatting such as bold or italics are good examples of where you would use a Memo field.

Up to 1 gigabyte of characters, or 2 gigabytes of storage (2 bytes per character), of which you can display 65,535 characters in a control.

Number

Numeric values (integers or fractional values). Use for storing numbers to be used in calculations, except for monetary values (use the Currency for data type for

1, 2, 4, or 8 bytes, or 16 bytes when used for replication ID.

monetary values).

Date/Time

Dates and times. Use for storing date/time values. Note that each value stored includes both a date component and a time component.

8 bytes.

Currency

Monetary values. Use for storing monetary values (currency).

8 bytes.

AutoNumber

A unique numeric value that Office Access 2007 automatically inserts when a record is added. Use for generating unique values that can be used as a primary key. Note that AutoNumber fields can be incremented sequentially, by a specified increment, or chosen randomly.

4 bytes or 16 bytes when used for replication ID.

Yes/No

Boolean values. Use for True/False fields that can hold one of two possible values: Yes/No or True/False, for example.

1 bit (8 bits = 1 byte).

OLE Object

OLE objects or other binary data. Use for storing OLE objects from other Microsoft Windows applications.

Up to 1 gigabyte.

Attachment

Pictures, Images, Binary files, Office files. This is the preferred data type for storing digital images and any type of binary file.

For compressed attachments, 2 gigabytes. For uncompressed attachments, approximately 700k, depending on the degree to which the attachment can be compressed.

Hyperlink

Hyperlinks. Use for storing hyperlinks to provide single-click access to Web pages through a URL (Uniform Resource Locator) or files through a name in UNC (universal naming convention) format. You can also link to Access objects stored in a database.

Up to 1 gigabyte of characters, or 2 gigabytes of storage (2 bytes per character), of which you can display 65,535 characters in a control.

Lookup Wizard

Not actually a data type; instead, this invokes the Lookup Wizard. Use to start the Lookup Wizard so you can create a field that uses a combo box to look up a value in another table, query or list of values.

Table or query based: The size of the bound column. Value based: The size of the Text field used to store the value.

TIP

For phone numbers, part numbers, and other numbers you dont intend to use for mathematical calculations, you

should select the Text data type, not the Number data type.

For the Text and Number data types, you can specify the field size or data type more specifically by setting a value in the FieldSize property box.

Top of Page

Save a table
After you add fields to a table, you should save its design. When you save a new table for the first time, give it a name that describes the information it contains. You can use up to 64 characters (letters or numbers), including spaces. For example, you might name a table Customers, Parts Inventory, or Products.

1.

Click the Microsoft Office Button

, and then click Save.

-or-

Right-click the table's document tab, and then click Save on the shortcut menu.

-or-

Click Save on the Quick Access Toolbar.

2.

If you are saving the table for the first time, type a name for the table, and then click OK.

Top of Page

Set the primary key


The primary key of a table consists of one or more fields that uniquely identify each row you store in the table. Often, there is a unique identification number, such as an ID number, a serial number, or a code, that serves as a primary key. For example, you might have a Customers table where each customer has a unique customer ID number. The customer ID field is the primary key of the table.

A good candidate for the primary key has several characteristics. First, it uniquely identifies each row. Second, it is never empty or null there is always a value. Third, it rarely (ideally never) changes. Access uses primary key fields to quickly bring together data from multiple tables.

You should always specify a primary key for a table. Access automatically creates an index for the primary key, which helps speed up queries and other operations. Access also ensures that every record has a value in the primary key field, and that it is always unique.

When you create a new table in Datasheet view, Access automatically creates a primary key for you and assigns it a field name of ID and the AutoNumber data type. The field is hidden in Datasheet view, but you can see it if you switch to Design view.

Switch to Design View


1. Right click the document tab, and then click Design View.

- or -

Right-click the table name in the Navigation Pane, and then click Design View.

- or -

Click Design View in the Access status bar.

To change or remove the primary key, or to set the primary key for a table that doesn't already have one, you must use Design view.

Set or change the primary key


1. Open the table in Design view.

2.

Select the field or fields you want to use as the primary key.

To select one field, click the row selector for the field you want.

To select more than one field, hold down the CTRL key and then click the row selector for each field.

3.

On the Design tab, in the Tools group, click Primary Key.

A key indicator is added to the left of the field or fields that you specify as the primary key.

Remove the primary key


1. Open the table in Design view.

2.

Click the row selector for the current primary key.

If the primary key consists of a single field, click the row selector for that field.

If the primary key consists of multiple fields, click the row selector for any field in the primary key.

3.

On the Design tab, in the Tools group, click Primary Key.

The key indicator is removed from the field or fields you previously specified as the primary key.

NOTE

When you save a new table without setting a primary key, Access prompts you to create one. If you choose

Yes, Access creates an ID field that uses the AutoNumber data type to provide a unique value for each record. If your table already includes a AutoNumber field, Access uses it as the primary key.

Top of Page

Set field properties


You can control the appearance of information, prevent incorrect entries, specify default values, speed up searching and sorting, and control other appearance or behavior characteristics by setting field properties. For example, you can format numbers to make them easier to read, or you can define a validation rule that must be satisfied for information to be entered in a field.

The data type of the field determines the properties you can set. For example, the AppendOnly property applies only to a field that is set to the Memo data type. You cannot set this property on a field with any other data type.

Access uses the field property settings when you view and edit data. For example, the Format, InputMask, and Caption properties affect how your information appears in table and query datasheets. In addition, any controls on new forms and reports that are based on the fields in the table inherit these same property settings by default. You use other properties to set a default value for a field or to require a user to enter a value, which Access enforces whenever you add or edit data in the table.

Set a field property for a table in Datasheet view


1. Open the table in Datasheet view.

2.

Click in the field for which you want to set the property.

3.

On the Datasheet tab, in the Data Type & Formatting group, select one of the following commands:

4.

 

Unique Sets the Indexed property.

Is Required Toggles the setting of the Required property. If it was set to Yes, it is set to No. If it was set to No, it is set to Yes.

You can set only a few of the available field properties in Datasheet view. To set additional field properties, you must open the table in Design view.

To have access to and set the complete list of field properties, you must use Design view.

Set a field property for a table in Design view


1. Open the table in Design view.

2.

In the upper portion of the table design grid, click the field for which you want to set properties (or move to the field by using the arrow keys).

3.

Access displays the properties for this field in the lower portion of the table design grid. The data type of the field determines the properties you can set.

4.

In the lower portion of the window, under Field Properties, click the box for the field property you want to set. Alternatively, you can press F6 and then move to the property by using the arrow keys.

5.

Type a setting for the property or, if an arrow appears at the right side of the property box, click the arrow to choose from a list of settings for the property.

The following table lists the available field properties.

Use this field property FieldSize Format DecimalPlaces NewValues InputMask Caption DefaultValue ValidationRule ValidationText Required AllowZeroLength Indexed UnicodeCompression IMEMode IMESentenceMode SmartTags AppendOnly

To Set the maximum size for data stored as a Text, Number, or AutoNumber data type. Customize the way the field appears when displayed or printed. Specify the number of decimal places to use when displaying numbers. Set whether an AutoNumber field is incremented or assigned a random value. Display editing characters to guide data entry. Set the text displayed by default in labels for forms, reports, and queries. Automatically assign a default value to a field when new records are added. Supply an expression that must be true whenever you add or change the value in this field. Enter text that appears when a value violates the ValidationRule expression. Require that data be entered in a field. Allow entry (by setting to Yes) of a zero-length string ("") in a Text or Memo field. Speed up access to data in this field by creating and using an index. Compress text stored in this field when a large amount of text is stored (> 4,096 characters) Control conversion of characters in an Asian version of Windows. Control conversion of characters in an Asian version of Windows. Attach a smart tag to this field. Allow versioning (by setting to Yes) of a Memo field.

TextFormat

Choose Rich Text to store text as HTML and allow rich formatting. Choose Plain Text to store only text. Specify the default alignment of text within a control. Specify the total number of digits allowed, including those both to the right and the left of the decimal point. Specify the maximum number of digits that can be stored to the right of the decimal separator.

TextAlign Precision

Scale

If you want more space to enter or edit a property setting in the property box, press SHIFT+F2 to display the Zoom box. If you are entering an input mask or validation expression and would like help in building it, click next to the property box to display the appropriate builder.

6.

To save your changes, click Save on the Quick Access Toolbar.

-or-

Right-click the table's document tab, and then click Save on the shortcut menu.

-or-

Click the Microsoft Office Button

, and then click Save.

The following table provides additional information about the FieldSize, Format and New Values field properties.

FieldSize property Text

Description Enter a value from 1 to 255. Text fields can range from 1 to 255 characters. For larger text fields, use the Memo data type. Select one of the following: Byte For numeric values that range from 0 to 255. Storage requirement is a single byte.

Number

Integer For numeric values that range from -32,768 to +32,768. Storage requirement is two bytes. Long Integer For numeric values that range from -2,147,483,648 to +2,147,483,647. Storage requirement is four bytes. TIP Use Long Integer for storing as a foreign key the value that appears in another table's primary key AutoNumber field.

Single For numeric floating point values that range from -3.4 x 1038 to +3.4 x 1038 and up to seven significant digits. Storage requirement is four bytes. Double For numeric floating point values that range from -1.797 x 10 308 to +1.797 x 308 10 and up to fifteen significant digits. Storage requirement is eight bytes. Replication ID For storing a globally unique identifier required for replication. Storage requirement is sixteen bytes. Note that replication is not supported using the .accdb file format. Decimal For numeric values that range from -9.999... x 1027 to +9.999... x 1027. Storage requirement is twelve bytes.

AutoNumber

Select one of the following: Long Integer For unique, numeric values that range from 1 to +2,147,483,648 when the New Values field property is set to Increment, and -2,147,483,648 to +2,147,483,647 when the New Values field property is set to Random. Storage requirement is four bytes. Replication ID For storing a globally unique identifier required for replication. Storage requirement is sixteen bytes. Note that replication is not supported using the .accdb file format.

Format property Text You can define a custom format. For more information, see Format data in tables, forms, and reports. Select one of the following: General Number Displays the number as entered.

Number

For example, 3456.789 becomes 3456.789 Currency Displays the number using the thousand separator, and applies the settings in the Regional and Language Options in the Control Panel for negative amounts, decimal and currency symbols, and decimal places. For example, 3456.789 becomes $3,456.79 Euro Displays the number using the Euro currency symbol, regardless of the symbol specified in the Regional and Language Options. Fixed Displays at least one digit and applies the settings in the Regional and Language Options in the Control Panel for negative amounts, decimal and currency symbols, and decimal places. For example, 3456.789 becomes 3456.79 Standard Displays the number using the thousand separator and applies the settings in the Regional and Language Options in the Control Panel for negative amounts, decimal symbols, and decimal places. This format does not display a currency symbol. For example, 3456.789 becomes 3,456.79 Percent Multiplies the value by 100 and displays the number with a percent sign added to the end. Applies the settings in the Regional and Language Options in the Control Panel

for negative amounts, decimal symbols, and decimal places. For example, 0.3456 becomes 35% Scientific Displays the value in standard scientific notation.

For example, 3456.789 becomes 3.46E+03

Date/Time

Select one of the following predefined display formats: General Date settings. Displays the value using a combination of the Short Date and Long Time

Long Date Displays the value using the Long Date setting from the Regional and Language Options settings in the Control Panel. Medium Date Displays the value using the format dd-mmm-yy (14-Jul-06, for example).

Short Date Displays the value using the Short Date setting from the Regional and Language Options in the Control Panel. Long Time Displays the value using the Time setting in the Regional and Language Options in the Control Panel. Medium Time Displays the value using the format HH:MM PM where HH is the hour, MM is the minute, and PM is either AM or PM. The hour can range from 1 to 12. The minute can range from 0 to 59. Short Time Displays the value using the format HH:MM where HH is the hour and MM is the minute. The hour can range from 0 to 23 and the minute from 0 to 59.

Yes/No

Select one of the following: True/False Yes/No On/Off NOTE Displays the value as either True or False. Displays the value as either Yes or No. Displays the value as either On or Off.

In the above, On, True and Yes are equivalent. False, No and Off are also equivalent.

New Values property AutoNumber Select one of the following (for the AutoNumber data type only): Increment Random Start value at 1 and increment by 1 for each new record. Start with a random value and assign a random value to each new record.

Top of Page

Set table properties


In addition to field properties, you can set properties that apply to an entire table and to entire records. You set these properties in the tables property sheet.

Set a table property


1. Open the table in Design view.

2.

On the Design tab, in the Tools group, click Property Sheet.

The table's property sheet is displayed.

3.

Click the box for the property you want to set.

4.

Type a setting for the property.

The following table lists the available table properties.


Use this table property Description DefaultView ValidationRule ValidationText Filter OrderBy SubdatasheetName To Provide a description of the table. Set Datasheet, PivotTable, or PivotChart as the default view when you open the table. Supply an expression that must be true whenever you add a record or change a record. Enter text that appears when a record violates the ValidationRule expression. Define criteria to display only matching rows in Datasheet view. Select one or more fields to specify the default sort order of rows in Datasheet view. Specify whether a subdatasheet should appear in Datasheet view, and if so, which table or query should supply the rows in the subdatasheet. List the fields in the table or query used for the subdatasheet that match this table's primary key field(s). List the primary key field(s) in this table that match the child fields for the subdatasheet. Specify whether to expand to show all available subdatasheet rows (the default) when opened, or set the height of the subdatasheet window to show when opened.

LinkChildFields

LinkMasterFields SubdatasheetHeight

SubdatasheetExpanded Orientation

Set whether to expand all subdatasheets when you open the table. Set the view orientation, according to whether your language is read left-to-right, or right-toleft. Specify whether forms and reports associated with this table should be available on the View menu in Windows SharePoint Services if the database is published to a SharePoint site. Automatically apply the filter criteria in the Filter property (by setting to Yes) when the table is opened in Datasheet view. Automatically apply the sort criteria in the OrderBy property (by setting to Yes) when the table is opened in Datasheet view.

DisplayViewsOnSharePoint

FilterOnLoad

OrderByOnLoad

If you want more space to enter or edit a setting in the property box, press SHIFT+F2 to display the Zoom box. If you are setting the ValidationRule property to an expression and would like help in building it, click next to the ValidationRule property box to display the Expression Builder.

5.

To save your changes, click Save on the Quick Access Toolbar.

-or-

Right-click the table's document tab, then click Save on the shortcut menu.

-or-

Click the Microsoft Office Button

, and then click Save.

Understand Number fields


If you are new to Office Access 2007, remember that the data in a database is stored in one or more tables. You can view the information in a datasheet a grid that resembles a Microsoft Office Excel 2007 worksheet or in a dataentry form or a report, but the database stores all data in one or more tables. In turn, each table consists of a set of fields (columns), and each field is set to accept one specific type of data. For example, you set a field to the Date/Time data type when you need to store dates and times, and you set a field to the Number data type when you need to store numbers for use in mathematical calculations.

Number field specifications


You use a Number field for all mathematical calculations except those involving money and those that require a high degree of accuracy, or for figures that you don't want to round up or down (you use a Currency field to prevent rounding). The size of the values that you store in a Number field depends on how you set the Field Size property. For example, you can set Number fields to contain 1-byte, 2-byte, 4-byte, 8-byte, or 16-byte values, plus Replication IDs (globally unique identifier values, or GUIDs) and decimal values.

You set the field size by opening the table in Design view and changing the Field Size property. For information about changing the properties of a Number field, see the section Set or change field properties. For information about the field properties, see the section Number field property reference.

The following table lists the values that each Field Size setting can contain and explains when to use each size setting.

Field Size setting Byte Integer Long Integer Single Double

Description A 1-byte integer containing values from 0 to 255. A 2-byte integer containing values from -32,768 to +32,767. A 4-byte integer containing values from -2,147,483,648 to 2,147,483,647. A 4-byte integer containing values from -3.4 x 10 38 to +3.4 x 10 38 and up to 7 significant digits. An 8-byte floating point number containing values from -1.797 x 10308 to +1.797 x 10308 and up to 15 significant digits. A 16-byte globally unique identifier (GUID). Randomly generated GUIDs are long enough that they are not likely to overlap. You use them for a variety of applications, such as tracking goods. A 12-byte integer with a defined decimal precision that can contain values from -1028 to +1028. The default precision is 0. The default scale (the number of decimal places displayed) is 18. You can set the scale up to 28.

Replication ID

Decimal

In addition to setting field sizes and other field properties, you can apply custom and predefined display formats and input masks to your number data.

For more information about formatting Number data, see the article Format data in tables, forms, and reports. For information about input masks, see the article Create an input mask to enter field or control values in a specific format.

Methods for creating a Number field


Office Access 2007 provides several ways to add a Number field to a new or existing table:

Datasheet view You can add a Number field to a new or existing table in Datasheet view by adding a new field and then typing a number into a blank row in the field, or by pasting a number into a blank row. You can also select the Number data type from a drop-down list and set properties such as Is Required, which forces users to enter a date in the field, and Unique, which forces users to enter a non-duplicate value in the field.

Design view You use Design view to add a Number field and set properties for the field that you cannot set in Datasheet view. Those properties include input masks and a default value for the field. For more information about the properties, see the section Number field property reference.

Top of Page

Add a Number field in Datasheet view


The steps in this section explain how to add a Number field to an existing table and a new table in Datasheet view. If you are new to Access, a datasheet is a grid that is similar in appearance to an Office Excel 2007 worksheet.

Add a Number field to an existing table


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, double-click the table that you want to change.

Access opens the table in Datasheet view.

4.

If necessary, scroll horizontally to the first blank field. By default, Access displays Add New Field in the header row of all new fields, like so:

5.

Double-click the header row, and then type a name for the new field.

6.

Select the first blank row under the header, and then type or paste a block of numbers. Access infers the Number data type for the field when you enter numbers or paste numbers.

-or-

On the Datasheet tab, in the Data Type & Formatting group, from the Data Type list, select Number, and then from the Format list, select the number format you want.

If you type or paste data into the field, Access sets the Field Size setting based on the size of the number that you enter.

7.

Save your changes.

Add a Number field to a new table


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

On the Create tab, in the Tables group, click Table.

Access opens the new table in Datasheet view. This figure illustrates a new table:

4.

Click Save

, and in the Save As dialog box, enter a name for the new table.

5.

Double-click the header row for the first table field (the one labeled Add New Field), and then type a name for the field.

6.

Select the first blank row under the header, and then type a block of numbers. Access infers the Number data type for the field when you enter numbers.

In addition, Access sets the Field Size property based on the size of the number that you enter or paste.

Top of Page

Add a Number field in Design view


You use Design view to add a Number field to a new or existing table and then to set or change the field properties that you can't set or change in Datasheet view. For example, you can specify an input mask or a default value. The steps in this section explain how to add a Number field and set properties for the field.

Add a Number field to an existing table


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, right-click the table that you want to change, and then click Design View

4.

In the Field Name column, select the first blank row, and then type a name for the field.

5.

Select the adjacent cell in the Data Type column, and then select Number from the list.

6.

Save your changes.

Add a Number field to a new table


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

On the Create tab, in the Tables group, click Table.

4.

Click Save, and in the Save As dialog box, enter a name for the new table.

5.

Right-click the document tab for the new table and click Design View on the shortcut menu.

6.

In the Field Name column, select the first blank row and type a name for the field.

7.

Select the adjacent cell in the Data Type column, and then select Number from the list.

8.

Save your changes. If you want to set properties for the field, leave the table open in Design view and go to the next steps.

Set or change field properties


1. On the General tab in the lower section of the table designer, under Field Properties, locate the property that you want to change.

2.

Select the field next to the property name. Depending on the property, you enter data (such as default text or an input mask), start the Expression Builder by clicking ..., or select an option from a list.

For information about how to use each field property, select the property and then press F1.

Top of Page

Delete a Number field

You can use Datasheet view or Design view to delete a Number field from a table. However, when you delete a Number field that contains data, you lose that data permanently you cannot undo the deletion. For that reason, you should back up your database before you delete any table fields or other database components.

Delete a Number field in Datasheet view


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, double-click the table that you want to change.

Access opens the table in Datasheet view.

4.

Locate the Number field, right-click the header row (the field name), and then click Delete Column.

Delete a Number field in Design view


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, right-click the table that you want to change, and then click Design View.

Access opens the table in Design view.

4.

Click the row selector (the blank square) next to the Number field, and then press DELETE.

-or-

Right-click the row selector, and then click Delete Rows.

5.

Click Yes to confirm the deletion.

Top of Page

Number field property reference


When you use Design view to add a Number field to a table, you can set and change several properties for the field. This table lists and describes the Number field properties and explains the implications of setting or changing them.

Property Field Size

Usage Controls the size of the value that you can enter and store in the field. For more information about the Field Size property, see Number field specifications earlier in this article. You enter custom formatting characters to define a display format. Formats defined here appear in datasheets, forms, and reports. For more information about custom formats, see the article Format data in tables, forms, and reports.

Format

Decimal Places Input Mask

Sets the number of decimal places for the values in the field. Default value: Auto. Other possible values range from 0 to 15. You define an input mask when you need to control how users enter data in the field. For more information about using input masks, see the article Create an input mask to enter field or control values in a specific format.

Caption

Specifies the name of your Text field. This property accepts up to 2,048 characters. If you don't specify a caption, Access applies the default field name. Specifies the value that automatically appears in a field when you create a new record.

Default Value Validation Rule

Specifies the requirements for data entered into an entire record, an individual field, or a control. When users enter data that violates the rule, you can use the Validation Text property to specify the resulting error message. Maximum length: 2,048 characters. For more information about creating validation rules, see the article Create a validation rule to validate data in a field.

Validation Text

Specifies the text in the error message that appears when users violate a validation rule. Maximum length: 255 characters. For more information about creating validation rules, see the article Create a validation rule to validate data in a field.

Required

When this property is set to Yes, you must enter a value in the field or in any controls bound to the field. In addition, the value cannot be null. You use an index to speed up queries, sorting, and grouping operations run against large amounts of data. You can also use indexes to prevent users from entering duplicate values. Choices: No Turns off indexing (default). Yes (Duplicates OK) Indexes the field and allows duplicate values. For example, you may have duplicate first and last names.

Indexed

Yes (No Duplicates) Indexes the field and does not allow duplicate values.

Smart Tags

You specify one or more smart tags for the field and any controls bound to the field. Smart tags are components that recognize the types of data in a field and allow you to take action based on that type. For example, in an E-mail Address field, a smart tag can create a new mail message or add the address to a list of contacts. Click Build (...) to see a list of available smart tags.

Text Align

Specifies the alignment for data. Choices: General Aligns text to the left, numbers and dates to the right (default setting). Left Aligns all text, dates, and numbers to the left. Right Aligns all text, dates, and numbers to the right. Center Centers all text, dates, and numbers. Distribute Justifies all text, dates, and numbers evenly against both sides of the field or text box.

Understand Text fields


If you are new to Office Access 2007, remember that the data in a database is stored in one or more tables. You can view the information in a datasheet a grid that resembles a Microsoft Office Excel 2007 worksheet or in a dataentry form or a report, but the database stores all data in one or more tables. In turn, each table consists of a set of fields (columns), and each field is set to accept one specific type of data. For example, you set a field to the Date/Time data type when you need to store dates and times, and you set a field to the Text data type when you need to store textual data such as names, addresses, or telephone numbers. If you need to store large amounts of text (more than 256 characters), you set the field to the Memo data type.

Text field specifications


Text fields in Office Access 2007 can store up to 256 alphanumeric characters. You can display all 256 characters in the table field and in a control on a form or report. Unlike Memo fields, you cannot apply Rich-Text formatting to the data in a Text field. However, you can apply custom display formats, and you can also apply input masks that control how users enter data.

For more information about formatting Text data, see the article Format data in tables, forms, and reports. For information about input masks, see the article Create an input mask to enter field or control values in a specific format.

Methods for creating a Text field


Office Access 2007 provides several ways to add a Text field to a new or existing table:

Datasheet view You can add a Text field to a new or existing table in Datasheet view by adding a new field and then typing text into a blank row in the field, or by pasting as many as 256 characters of text into a blank row. You can also select the data type from a drop-down list, and set properties such as Is Required, which forces users to enter a date in the field, and Is Unique, which forces users to enter a nonduplicate value in the field.

Design view You use Design view to add a Text field and to set properties for the field that you cannot set in Datasheet view. Those properties include input masks and a default value for the field. For more information about the field properties that you can set in Design view, see Text field property reference at the end of this article.

Top of Page

Add a Text field in Datasheet view


The steps in this section explain how to add a Text field to an existing table and a new table in Datasheet view. If you are new to Access, a datasheet is a grid similar in appearance to an Office Excel 2007 worksheet.

Add a Text field to an existing table


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, double-click the table that you want to change.

Access opens the table in Datasheet view.

4.

If necessary, scroll horizontally to the first blank field. By default, Access displays Add New Field in the header row of all new fields.

5.

Double-click the header row, and then type a name for the new field.

6.

Select the first blank row under the header, and then type a block of text or a combination of text and numbers. You can enter a maximum of 256 characters. Access infers the Text data type for the field when you enter text or a mix of text and numbers, and you enter no more than 256 characters. If you enter more than 256 characters, Access infers the Memo data type.

-or-

Paste up to 256 characters of text data into the first row.

7.

Save your changes.

Add a Text field to a new table

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

On the Create tab, in the Tables group, click Table.

Access opens the new table in Datasheet view. This figure illustrates a new table:

4.

Click Save

, and in the Save As dialog box, enter a name for the new table.

5.

Double-click the header row for the first table field (the one labeled Add New Field), and then type a name for the field.

6.

Select the first blank row under the header, and then type a block of text or a combination of text and numbers. You can enter a maximum of 256 characters. Access infers the Text data type for the field when you enter text or a mix of text and numbers, and you enter no more than 256 characters. If you enter more than 256 characters, Access infers the Memo data type.

-or-

Paste up to 256 characters of text data into the first row.

-or-

On the Datasheet tab, in the Data Type & Formatting group, from the Data Type list, select Text.

Top of Page

Add a Text field in Design view

You use Design view to add a Text field to a new or existing table and then to set or change field properties that you cannot set or change in Datasheet view. For example, you can specify an input mask or a default value. The steps in this section explain how to add a Text field and set properties for the field.

Add a Text field to an existing table


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, right-click the table that you want to change, and then click Design View.

4.

In the Field Name column, select the first blank row, and then type a name for the field.

5.

Select the adjacent cell in the Data Type column, and then select Text from the list.

6.

Save your changes.

Add a Text field to a new table


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

On the Create tab, in the Tables group, click Table.

4.

Click Save

, and in the Save As dialog box, enter a name for the new table.

5.

Right-click the document tab for the new table and click Design View.

6.

In the Field Name column, select the first blank row, and then type a name for the field.

7.

Select the adjacent cell in the Data Type column, and then select Text from the list.

8.

Save your changes. If you want to set properties for the field, leave the table open in Design view and go to the next steps.

Set or change field properties


1. On the General tab in the lower section of the table designer, under Field Properties, locate the property that you want to change.

2.

Select the field next to the property name. Depending on the property, you can enter data (such as default text or an input mask), start the Expression Builder by clicking , or select an option from a list.

For information about how to use each field property, select the property and then press F1.

Top of Page

Delete a Text field


You can use Datasheet view or Design view to delete a Text field from a table. However, when you delete a Text field that contains data, you lose that data permanently you cannot undo the deletion. For that reason, you should back up your database before you delete any table fields or other database components.

Delete a Text field in Datasheet view


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, double-click the table that you want to change.

Access opens the table in Datasheet view.

4.

Locate the Text field, right-click the header row (the name), and then click Delete Column.

Delete a Text field in Design view


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, right-click the table that you want to change and then click Design View.

Access opens the table in Design view.

4.

Click the row selector (the blank square) next to the Text field, and then press DELETE.

-or-

Right-click the row selector and then click Delete Rows.

5.

Click Yes to confirm the deletion.

Top of Page

Text field property reference


When you use Design view to add a Text field to a table, you can set and change a number of properties for the field. This table lists the Text field properties, describes what each one does, and explains the implications of setting or changing them.

Property Field Size

Usage Controls the size of your Text fields. Valid values: 0 to 255. If you leave this property blank, the field accepts 256 characters. You enter custom formatting characters to define a display format. Formats defined here appear in datasheets, forms, and reports. For more information about custom formats, see the article Format data in tables, forms, and reports.

Format

Input Mask

You define an input mask when you need to control how users enter data in the field. For more information about using input masks, see the article Create an input mask to enter field or control values in a specific format.

Caption

Specifies the name of your Text field. This property accepts up to 2,048 characters. If you don't specify a caption, Access applies the default field name. Specifies the value that automatically appears in a field when you create a new record. For example, in an addresses table, you can set the default value for the City field to a certain city. When users add a record to the table, they can either accept this value or enter the name of a different city. Maximum length: 255 characters. Specifies requirements for data entered into an entire record, an individual field, or a control. When a user enters data that violates the rule, you can use the Validation Text property to specify the resulting error message.

Default Value

Validation Rule

Maximum length: 2,048 characters. For more information about creating validation rules, see the article Create a validation rule to validate data in a field.

Validation Text

Specifies the text in the error message that appears when users violate a validation rule. Maximum length: 255 characters. For more information about creating validation rules, see the article Create a validation rule to validate data in a field.

Required

When this property is set to Yes, you must enter a value in the field or in any controls that are bound to the field. In addition, the value cannot be null. When this property is set to Yes, you can enter zero-length strings in a field. A zero-length string contains no characters. You use it to indicate that you know no value exists for a field. You enter a zero-length string by typing two double quotation marks with no space between them ("") . You use an index to speed up queries, sorting, and grouping operations run against large amounts of data. You can also use indexes to prevent users from entering duplicate values. Choices: No Turns off indexing (default). Yes (Duplicates OK) Indexes the field and allows duplicate values. For example, you may have duplicate first and last names. Yes (No Duplicates) Indexes the field and does not allow duplicate values.

Allow Zero Length

Indexed

Unicode Compression

Access uses Unicode to represent data in Text, Memo, and Hyperlink fields. Because Unicode uses 2 bytes per character instead of 1, it takes up more storage space. To offset this effect and help ensure optimal performance, Access sets the default value of this property to Yes for Text, Memo, and Hyperlink fields. When the property is set to Yes, any character whose first byte is 0 is compressed when it is stored and uncompressed when it is retrieved.

IME Mode

Specifies an Input Method Editor, a tool for using English versions of Access with files created in Japanese or Korean versions of Access. Default value: No Control. For more information about using this property, press F1. Specifies the type of data you can enter by using an Input Method Editor. For more information about using this property, press F1. You specify one or more smart tags for the field and any controls bound to the field. Smart tags are components that recognize the types of data in a field and allow you to take action based on that type. For example, in an Email Address field, a smart tag can create a new mail message or add the address to a list of contacts.

IME Sentence Mode Smart Tags

Click

to see a list of available smart tags.

Text Align

Specifies the alignment for data in a Text field. Choices: General Aligns all text to the left.

Left Aligns all text to the left. Center Centers all text. Right Aligns all text to the right. Distribute Justifies all text evenly against both sides of the field or text box.

Understand Date/Time fields


If you are new to Office Access 2007, remember that the data in a database is stored in one or more tables. You can view the information in a datasheet a grid that resembles a Microsoft Office Excel 2007 worksheet or in a dataentry form or a report, but the data ultimately resides in one or more tables. In turn, each table consists of a set of fields (columns), and each field is set to accept one specific type of data. For example, you set a field to the Date/Time data type when you need to store dates and times, and those are the only types of values that the field accepts.

Date/Time field specifications


When you use an Access database, you might see date and time values in any number of formats, such as a European format (28.11.2006 or 28-11-2006), a South Asian format (28/11/2006), or the U.S. format (11/28/2006).

Regardless of how Access formats the date and time data, and regardless of how you enter the date or time data, Date/Time fields store the dates and times as double-precision floating point numbers a system also called serial dates. The following figure represents a typical serial date and time value.

The integer portion of the value, to the left of the decimal point, represents the date. The fractional portion, to the right of the decimal point, represents the time.

The number in this figure represents December 24, 2003, at 9:00 P.M. The date component is the number of whole days that have elapsed since the starting or "base" date of 12/30/1899. In this example, 37,979 days have elapsed from 12/30/1899 to 12/24/2003. The time component is a fraction of a 24-hour day. So, a value of 0.875 multiplied by 24 hours equals 21 hours, or 9:00 P.M.

Negative values in the date component represent dates prior to the base date. For example, a value of -1 as the date component resolves to one day prior to the base date, or 12/29/1899.

Valid date values range from -657,434 (January 1, 100 A.D.) to 2,958,465 (December 31, 9999 A.D.). Valid time values range from 0.0 to 0.9999, or 23:59:59.

Storing the date and time values as numbers allows you to perform a large number of calculations on date and time data. For example, you can calculate a total number of hours worked (for a time card), or determine the age of an invoice.

Formats for Date/Time fields


You can use two broad types of formatting with a Date/Time field: data-entry formatting and display formatting. You use an input mask a set of literal and placeholder characters that control how users enter data when you need to provide data-entry formatting. You use display formats to control what users see in datasheets, forms, and reports. Access provides two types of display formats: a set of predefined formats that you choose from a list, and the ability to create a custom format.

For more information about using predefined and custom formats, see the article Format data in tables, forms, and reports.

For information about input masks, see the article Create an input mask to enter field or control values in a specific format.

Methods for creating a Date/Time field


Office Access 2007 provides several ways to add a Date/Time field to a new or existing table:

Datasheet view You can add a Date/Time field to a new or existing table in Datasheet view by adding a new field and then entering a date manually, or by copying and pasting a date. You can also select the data type from a drop-down list and set properties such as Is Required, which forces users to enter a date in the field, and Is Unique, which forces users to enter a non-duplicate value in the field.

Design view You use Design view to add a Date/Time field and set properties for the field that you cannot set in Datasheet view, including input masks and default values.

Top of Page

Add a Date/Time field in Datasheet view


The steps in this section explain how to add a Date/Time field to an existing table and to a new table in Datasheet view. If you are new to Access, a datasheet is a grid similar in appearance to an Office Excel 2007 worksheet.

Add a Date/Time field to an existing table

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, double-click the table that you want to change.

Access opens the table in Datasheet view.

4.

If necessary, scroll horizontally to the first blank field. By default, Access displays Add New Field in the header row of all new fields, like so:

5.

Double-click the header row and type a name for the new field.

6.

Select the first blank row under the header and type a date.

-or-

Paste a date into the first row.

-or-

On the Datasheet tab, in the Data Types & Formatting group, from the Data Type list, select Date/Time.

7.

Save your changes.

Add a Date/Time field to a new table

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

On the Create tab, in the Tables group, click Table.

Access opens the new table in Datasheet view. This figure illustrates a new table:

4.

Click Save

, and in the Save As dialog box, enter a name for the new table.

5.

Double-click the header row for the first table field (the one labeled Add New Field), and type a name for the field.

6.

Select the first blank row under the header, and type a date. Access infers the Date/Time data type automatically when you enter a date.

-or-

Paste a date into the first row.

-or-

On the Datasheet tab, in the Data Type & Formatting group, from the Data Type list, select Date/Time.

Top of Page

Add a Date/Time field in Design view

You use Design view to add a Date/Time field to a new or existing table and then to set or change the field properties that you can't set or change in Datasheet view. For example, you can specify an input mask or a validation rule. For more information about input masks and other properties, see the section Date/Time field property reference.

Add a Date/Time field to an existing table

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, right-click the table that you want to change, and then click Design View

4.

In the Field Name column, select the first blank row, and then type a name for the field.

5.

Select the adjacent cell in the Data Type column, and then select Date/Time from the list.

6.

Save your changes.

Add a Date/Time field to a new table

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

On the Create tab, in the Tables group, click Table.

4.

Click Save

, and in the Save As dialog box, enter a name for the new table.

5.

Right-click the document tab for the new table and click Design View.

6.

In the Field Name column, select the first blank row, and then type a name for the field.

7.

Select the adjacent cell in the Data Type column, and then select Date/Time from the list.

8.

Save your changes. If you want to set properties for the field, leave the table open in Design view and continue to the next steps.

Set or change the field properties

1.

On the General tab in the lower section of the table designer, under Field Properties, locate the property that you want to change.

2.

Select the field next to the property name. Depending on the property, you can do any of the following:

   

Enter data (such as default text or an input mask).

Start either the Expression Builder or the Input Mask Wizard.

Display the Smart Tags dialog box by clicking

next to the property box.

Select an option from a list.

For information about how to use each field property, select the property and then press F1.

Top of Page

Delete a Date/Time field


You can use Datasheet view or Design view to delete a Date/Time field from a table. However, when you delete a Date/Time field that contains data, you lose that data permanently you cannot undo the deletion. For that reason, you should back up your database before you delete any table fields or other database components.

Delete a Date/Time field in Datasheet view

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, double-click the table that you want to change.

Access opens the table in Datasheet view.

4.

Locate the Date/Time field, right-click the header row (the name), and click Delete Column.

5.

Click Yes to confirm the deletion.

Delete a Date/Time field in Design view

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, right-click the table that you want to change and then click Design View

Access opens the table in Design view.

4.

Click the row selector (the blank square) next to the Date/Time field, and then press DELETE.

-or-

Right-click the row selector and click Delete Rows.

5.

Click Yes to confirm the deletion.

Top of Page

Date/Time field property reference


When you use Design view to add a Date/Time field to a table, you can set and change a number of properties for the field. This table lists the Date/Time field properties and describes what each one does, including the implications of setting or changing the properties.
Property Format Usage You enter custom formatting characters to define a display format. Formats defined here appear in datasheets, forms, and reports. For more information about custom formats, see the article Format data in tables, forms, and reports.

Input Mask You enter an input mask string, or click to start the Input Mask Wizard.

For more information about creating and using input masks, see the articles Create an input mask to enter field or control values in a specific format and Format data in tables, forms, and reports.

Caption Default Value Validation Rule

Specifies the name of your Date/Time field. If you don't specify a caption, Access applies the default field name. Specifies the value that automatically appears in a field when you create a new record. For example, you can enter a function such as Date() to automatically display today's date. Specifies requirements for data entered into an entire record, an individual field, or a control on a form or report. When a user enters data that violates the rule, you can use the Validation Text property to specify the resulting error message. Maximum length: 2,048 characters.

For more information about creating validation rules, see the article Create a validation rule to validate data in a field.

Validation Text

Specifies the text in the error message that appears when users violate a validation rule. Maximum length: 255 characters. For more information about creating validation rules, see the article Create a validation rule to validate data in a field.

Required

When this property is set to Yes, you must enter a value in the field or in any controls that are bound to the field. In addition, the value cannot be null. You use an index to speed up queries, sorting, and grouping operations that are run against large amounts of data. You can also use indexes to prevent users from entering duplicate values. Choices: No Turns off indexing (default). Yes (Duplicates OK) Indexes the field and allows duplicate values. For example, you may have duplicate first and last names. Yes (No Duplicates) Indexes the field and does not allow duplicate values.

Indexed

IME Mode

Specifies an Input Method Editor, a tool for using English versions of Access with files created in Japanese or Korean versions of Access. Default value: No Control. For more information about using this property, press F1. Specifies the type of data you can enter by using an Input Method Editor. For more information about using this property, press F1.

IME Sentence Mode Smart Tags

You specify one or more smart tags for the field and any controls that are bound to the field. Smart tags are components that recognize the types of data in a field and allow you to take action based on that type. For example, you can select a Date/Time field and then use a smart tag to open your personal calendar.

Click

next to the property box to see a list of available smart tags.

Text Align

Specifies the alignment for data in a Date/Time field. Choices: General Aligns text to the left, numbers and dates to the right. Left Aligns all text, dates, and numbers to the left. Right Aligns all text, dates, and numbers to the right. Center Centers all text, dates, and numbers. Distribute Justifies all text, dates, and numbers evenly against both sides of the field or text box.

Show Date Picker

Shows or hides a pop-up calendar control that appears when users click Date/Time fields. Default: For dates. Select Never to hide the control.

Introduction
After you have created a table for each subject in your database, you must provide Office Access 2007 with the means by which to bring that information back together again when needed. You do this by placing common fields in tables that are related, and by defining relationships between your tables. You can then create queries, forms, and reports that display information from several tables at once. For example, the form shown here includes information drawn from several tables:

Information in this form comes from the Customers table...

...the Orders table...

...the Products table...

...and the Order Details table.

The customer name in the Bill To box is retrieved from the Customers table, the Order ID and the Order Date values come from the Orders table, the Product name comes from the Products table, and the Unit Price and Quantity values come from the Order Details table. These tables are linked to each other in a variety of ways to bring information from each into the form.

In the preceding example, the fields in the tables must be coordinated so that they show information about the same order. This coordination is accomplished by using table relationships. A table relationship works by matching data in key fields often 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 for which they are responsible by creating a table relationship between the EmployeeID fields in the Employees and the Orders tables.

EmployeeID appears in both tables as a primary key ...

... and as a foreign key.

Top of Page

Types of table relationships


There are three types of table relationships.

A one-to-many relationship

Consider an order tracking database that includes a Customers table and an Orders table. A customer can place any number of orders. It follows that for any customer represented in the Customers table, there can be many orders represented in the Orders table. The relationship between the Customers table and the Orders table is, therefore, a one-to-many relationship.

To represent a one-to-many relationship in your database design, take the primary key on the "one" side of the relationship and add it as an additional field or fields to the table on the "many" side of the relationship. In this case, for example, you add a new field the ID field from the Customers table to the Orders table and name it Customer ID. Access can then use the Customer ID number in the Orders table to locate the correct customer for each order.

A many-to-many relationship

Consider the relationship between a Products table and an Orders table. A single order can include more than one product. On the other hand, a single product can appear on many orders. Therefore, for each record in the Orders table, there can be many records in the Products table. In addition, for each record in the Products table, there can be many records in the Orders table. This type of relationship is called a many-to-many relationship because, for any product, there can be many orders and, for any order, there

can be many products. Note that to detect existing many-to-many relationships between your tables, it is important that you consider both sides of the relationship.

To represent a many-to-many relationship, you must create a third table, often called a junction table, that breaks down the many-to-many relationship into two one-to-many relationships. You insert the primary key from each of the two tables into the third table. As a result, the third table records each occurrence, or instance, of the relationship. For example, the Orders table and the Products table have a many-to-many relationship that is defined by creating two one-to-many relationships to the Order Details table. One order can have many products, and each product can appear on many orders.

A one-to-one relationship

In a one-to-one relationship, each record in the first table can have only one matching record in the second table, and each record in the second table can have only one matching record in the first table. This type of relationship is not common because, most often, the information related in this way is stored in the same 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. When you do identify such a relationship, both tables must share a common field.

Top of Page

Why create table relationships?


You can create table relationships explicitly by using the Relationships window, or by dragging a field from the Field List pane. Office Access 2007 uses table relationships to how to join tables when you need to use them in a database object. There are several reasons why you should create table relationships before you create other database objects, such as forms, queries and reports.

Table relationships inform your query designs

To work with records from more than one table, you often must create a query that joins the tables. The query works by matching the values in the primary key field of the first table with a foreign key field in the second table. For example, to return rows that list all of the orders for each customer, you construct a query that joins the Customers table with the Orders table based on the Customer ID field. In the Relationships window, you can manually specify the fields to join. However, if you already have a relationship defined

between the tables, Office Access 2007 supplies the default join, based on existing the table relationship. In addition, if you use one of the query wizards, Access uses the information it gathers from the table relationships you have already defined to present you with informed choices and to prepopulate property settings with appropriate default values.

Table relationships inform your form and report designs

When you design a form or report, Office Access 2007 uses the information it gathers from the table relationships you have already defined to present you with informed choices and to prepopulate property settings with appropriate default values.

Table relationships are the foundation upon which you can enforce referential integrity to help prevent orphan records in your database. An orphan record is a record with a reference to another record that does not exist for example, an order record that references a customer record that does not exist.

When you design a database, you divide your information into tables, each of which has a primary key. You then add foreign keys to related tables that reference those primary keys. These foreign key-primary key pairings form the basis for table relationships and multi-table queries. It is important, therefore, that these foreign key-primary key references stay synchronized. Referential integrity helps ensure that references stay synchronized and is dependent upon table relationships.

Top of Page

Understanding referential integrity


When you design a database, you divide your information into many subject-based tables to minimize data redundancy. You then provide Office Access 2007 with the means by which to bring the data back together by placing common fields into related tables. For example, to represent a one-to-many relationship you take the primary key from the "one" table and add it as an additional field to the "many" table. To bring the data back together, Access takes the value in the "many" table and looks up the corresponding value in the "one" table. In this way the values in the "many" table reference the corresponding values in the "one" table.

Suppose you have a one-to-many relationship between Shippers and Orders and you want to delete a Shipper. If the shipper you want to delete has orders in the Orders table, those orders will become "orphans" when you delete the

Shipper record. The orders will still contain a shipper ID, but the ID will no longer be valid, because the record that it references no longer exists.

The purpose of referential integrity is to to prevent orphans and keep references in sync so that this hypothetical situation never occurs.

You enforce referential integrity by enabling it for a table relationship (see Enforce referential integrity for step-by-step instructions). Once enforced, Access rejects any operation that would violate referential integrity for that table relationship. This means Access will reject both updates that change the target of a reference, and deletions that remove the target of a reference. However, it is possible you might have a perfectly valid need to change the primary key for a shipper that has orders in the Orders table. For such cases, what you really need is for Access to automatically update all the effected rows as part of a single operation. That way, Access ensures that the update is completed in full so that your database is not left in an inconsistent state, with some rows updated and some not. For this reason Access supports the Cascade Update Related Fields option. When you enforce referential integrity and choose the Cascade Update Related Fields option, and you then update a primary key, Access automatically updates all fields that reference the primary key.

It's also possible you might have a valid need to delete a row and all related records for example, a Shipper record and all related orders for that shipper. For this reason, Access supports the Cascade Delete Related Records option. When you enforce referential integrity and choose the Cascade Delete Related Records option, and you then delete a record on the primary key side of the relationship, Access automatically deletes all records that reference the primary key.

Top of Page

View table relationships


To view your table relationships, click Relationships on the Database Tools tab. The Relationships window opens and displays any existing relationships. If no table relationships have yet been defined and you are opening the Relationships window for the first time, Access prompts you to add a table or query to the window.

Open the Relationships window

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

On the Database Tools tab, in the Show/Hide group, click Relationships.

4.

If the database contains relationships, the Relationships window appears. If the database does not contain any relationships and you are opening the Relationships window for the first time, the Show Table dialog box appears. Click Close to close the dialog box.

5.

On the Design tab, in the Relationships group, click All Relationships.

This displays all of the defined relationships in your database. Note that hidden tables (tables for which the Hidden check box in the table's Properties dialog box is selected) and their relationships will not be shown unless the Show Hidden Objects check box is selected in the Navigation Options dialog box.

For more information about the Show Hidden Objects option, see the article Guide to the Navigation Pane.

The primary key

This line represents the relationship

The foreign key

A table relationship is represented by a relationship line drawn between tables in the Relationships window. A relationship that does not enforce referential integrity appears as a thin line between the common fields supporting

the relationship. When you select the relationship by clicking its line, the line thickens to indicate it is selected. If you enforce referential integrity for this relationship, the line appears thicker at each end. In addition, the number 1 appears over the thick portion of the line on one side of the relationship, and the infinity symbol () appears over the thick portion of the line on the other side.

You can select from the following commands on the ribbon when the Relationships window is active:

On the Design tab, in the Tools group:

Edit Relationships Opens the Edit Relationships dialog box. When you select a relationship line, you can click Edit Relationships to change the table relationship. You can also double-click the relationship line.

Clear Layout Removes all tables and relationships from display in the Relationships window. Note that this command only hides the tables and relationships it does not delete them.

Relationships Report Creates a report that displays the tables and relationships in your database. The report shows only the tables and relationships that are not hidden in the Relationships window.

On the Design tab, in the Relationships group:

Show Table Opens the Show Table dialog box so that you can select tables and queries for viewing in the Relationships window.

Hide Table Hides the selected table in the Relationships window.

Direct Relationships Displays all relationships and related tables for the selected table in the Relationships window, if they are not already displayed.

All Relationships Displays all of the relationships and related tables in your database in the Relationships window. Note that hidden tables (tables for which the Hidden check box in the table's Properties dialog box is selected) and their relationships will not be shown unless Show Hidden Objects is selected in the Navigation Options dialog box.

For more information about the Show Hidden Tables option, see the article Guide to the Navigation Pane.

Close Closes the Relationships window. If you made any changes to the layout of the Relationships window, you are asked whether to save those changes.

Top of Page

Create a table relationship


You can create a table relationship by using the Relationships window, or by dragging a field onto a datasheet from the Field List pane. When you create a relationship between tables, the common fields are not required to have the same names, although it is often the case that they do. Rather, those fields must have the same data type. If the primary key field is an AutoNumber field, however, the foreign key field can be a Number field if the FieldSize property of both fields is the same. For example, you can match an AutoNumber field and a Number field if the FieldSize property of both fields is Long Integer. When both common fields are Number fields, they must have the same FieldSize property setting.

Create a table relationship by using the Relationships window


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

On the Database Tools tab, in the Show/Hide group, click Relationships.

4.

If you have not yet defined any relationships, the Show Table dialog box automatically appears. If it does not appear, on the Design tab, in the Relationships group, click Show Table.

The Show Table dialog box displays all of the tables and queries in the database. To see only tables, click Tables. To see only queries, click Queries. To see both tables and queries, click Both.

5.

Select one or more tables or queries and then click Add. When you have finished adding tables and queries to the Relationships window, click Close.

6.

Drag a field (typically the primary key) from one table to the common field (the foreign key) in the other table. To drag multiple fields, press the CTRL key, click each field, and then drag them.

The Edit Relationships dialog box appears.

7.

Verify that the field names shown are the common fields for the relationship. If a field name is incorrect, click the field name and select a new field from the list.

To enforce referential integrity for this relationship, select the Enforce Referential Integrity check box. For more information about referential integrity, see the Understanding Referential Integrity and the Enforce Referential Integrity sections.

8.

Click Create.

The relationship line is drawn between the two tables. If you selected the Enforce Referential Integrity check box, the line appears thicker at each end. In addition, again only if you selected the Enforce Referential Integrity check box, the number 1 appears over the thick portion of the line on one side of the relationship, and the infinity symbol () appears over the thick portion of the line on the other side.

NOTES

To create a one-to-one relationship Both of the common fields (usually the primary key and foreign key fields) must have a unique index. This means the Indexed property for these fields should be set to Yes (No Duplicates). If both fields have a unique index, Access creates a one-to-one relationship.

To create a one-to-many relationship The field on the "one" side (typically the primary key) of the relationship must have a unique index. This means the Indexed property for this field should be set to Yes (No Duplicates). The field on the "many" side should not have a unique index. It can have an index, but it must allow duplicates. This means the Indexed property for this field should be set to either No, or Yes (Duplicates OK). When one field has a unique index and the other does not, Access creates a one-tomany relationship.

Create a table relationship by using the Field List pane


In Office Access 2007, you can add a field to an existing table that is open in Datasheet view by dragging it from the Field List pane. The Field List pane shows fields available in related tables and also fields available in other tables. When you drag a field from an "other" (unrelated) table and then complete the Lookup Wizard, a new one-to-many relationship is automatically created between the table in the Field List pane and the table to which you dragged the field. This relationship, created by Access, does not enforce referential integrity by default. To enforce referential integrity, you must edit the relationship. See the section Change a table relationship for more information.

Open a table in Datasheet view

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation pane, right-click the table to which you want to add the field and create the relationship, and click Datasheet View on the shortcut menu.

Open the Field List pane


On the Datasheet tab, in the Fields & Columns group, click Add Existing Fields.

The Field List pane appears.

The Field List pane shows all of the other tables in your database, grouped into categories. When you work with a table in Datasheet view, Access displays fields in either of two categories in the Field List pane: Fields available in related tables and Fields available in other tables. The first category lists all of the tables that have a relationship with the table you are currently working with. The second category lists all of the tables with which your table does not have a relationship.

In the Field List pane, when you click the plus sign (+) next to a table name, you see a list of all the fields available in that table. To add a field to your table, drag the field that you want from the Field List pane to the table in Datasheet view.

Add a field and create a relationship from the Field List pane
1. On the Datasheet tab, in the Fields & Columns group, click Add Existing Fields.

The Field List pane appears.

2.

Under Fields available in other tables, click the plus sign (+) next to a table name to display the list of fields in that table.

3.

Drag the field that you want from the Field List pane to the table that is open in Datasheet view.

4.

When the insertion line appears, drop the field in position.

The Lookup Wizard starts.

5.

Follow the instructions to complete the Lookup Wizard.

The field appears in the table in Datasheet view.

When you drag a field from an "other" (unrelated) table and then complete the Lookup Wizard, a new one-to-many relationship is automatically created between the table in the Field List and the table to which you dragged the field.

This relationship, created by Access, does not enforce referential integrity by default. To enforce referential integrity, you must edit the relationship. See the section Change a table relationship for more information.

Top of Page

Delete a table relationship


To remove a table relationship, you must delete the relationship line in the Relationships window. Carefully position the cursor so that it points at the relationship line, and then click the line. The relationship line appears thicker when it is selected. With the relationship line selected, press DELETE. Note that when you remove a relationship, you also remove referential integrity support for that relationship, if it is enabled. As a result, Access will no longer automatically prevent the creation of orphan records on the "many" side of a relationship.

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

On the Database Tools tab, in the Show/Hide group, click Relationships.

The Relationships window appears.

If you have not yet defined any relationships and this is the first time you are opening the Relationships window, the Show Table dialog box appears. If the dialog box appears, click Close.

4.

On the Design tab, in the Relationships group, click All Relationships.

All tables that have relationships are displayed, showing relationship lines.

5.

Click the relationship line for the relationship that you want to delete. The relationship line appears thicker when it is selected.

6.

Press the DELETE key.

or

Right-click and then click Delete.

7.

Access might display the message Are you sure you want to permanently delete the selected relationship from your database?. If this confirmation message appears, click Yes.

NOTE

If either of the tables employed in the table relationship are in use, perhaps by another person or process, or

in an open database object (such as a form), you will not be able to delete the relationship. You must first close any open objects that use these tables before you can remove the relationship.

Top of Page

Change a table relationship


You change a table relationship by selecting it in the Relationships window and then editing it. Carefully position the cursor so that it points at the relationship line, and then click the line to select it. The relationship line appears thicker when it is selected. With the relationship line selected, double-click it or click Edit Relationships in the Tools group on the Design tab. The Edit Relationships dialog box appears.

Make your changes in the Edit Relationships dialog box

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

On the Database Tools tab, in the Show/Hide group, click Relationships.

The Relationships window appears.

If you have not yet defined any relationships and this is the first time you are opening the Relationships window, the Show Table dialog box appears. If the dialog box appears, click Close.

4.

On the Design tab, in the Relationships group, click All Relationships.

All tables that have relationships are displayed, showing relationship lines. Note that hidden tables (tables for which the Hidden check box in the table's Properties dialog box is selected) and their relationships will not be shown unless Show Hidden Objects is selected in the Navigation Options dialog box.

For more information about the Show Hidden Objects option, see the article Guide to the Navigation Pane.

5.

Click the relationship line for the relationship that you want to change. The relationship line appears thicker when it is selected.

6.

Double-click the relationship line.

or

On the Design tab, in the Tools group, click Edit Relationships.

The Edit Relationships dialog box appears.

7.

Make your changes, and then click OK.

The Edit Relationships dialog box allows you to change a table relationship. Specifically, you can change the tables or queries on either side of the relationship, or the fields on either side. You can also set the join type, or enforce referential integrity and choose a cascade option. For more information about the join type

and how to set it, see the section Set the join type. For more information about how to enforce referential integrity and choose a cascade option, see the section Enforce referential integrity.

Set the join type


When you define a table relationship, the facts about the relationship inform your query designs. For example, if you define a relationship between two tables, and you then create a query that employs those tables, Access automatically selects the default matching fields based upon the fields specified in the relationship. You can override these initial default values in your query, but the values supplied by the relationship will often prove to be the correct ones. Because matching and bringing together data from more than one table is something you will do frequently in all but the most simple databases, setting defaults by creating relationships can be time saving and beneficial.

A multiple table query combines information from more than one table by matching the values in common fields. The operation that does the matching and combining is called a join. For instance, suppose you want to display customer orders. You create a query that joins the Customers table and the Orders table on the Customer ID field. The query result contains customer information and order information for only those rows where a corresponding match was found.

One of the values you can specify for each relationship is the join type. The join type tells Access which records to include in a query result. For example, consider again a query that joins the Customers table and the Orders table on the common fields that represent the Customer ID. Using the default join type (called an inner join), the query returns only the Customer rows and the Order rows where the common fields (also called the joined fields) are equal.

However, suppose you want to include all Customers even those who have not yet placed any orders. To accomplish this, you must change the join type from an inner join to what is called a left outer join. A left outer join returns all of the rows from the table on the left side of the relationship and only those that match from the table on the right. A right outer join returns all of the rows on the right and only those that match on the left.

NOTE

In this case, "left" and "right" refer to the position of the tables in the Edit Relationships dialog box, not the

Relationships window.

You should think about the result you will most often want from a query that joins the tables in this relationship, and then set the join type accordingly.

Set the join type

Set the join type


1. In the Edit Relationships dialog box, click Join Type.

The Join Properties dialog box appears.

2.

Click your choice, and then click OK.

The following table (using the Customers and Orders tables) shows the three choices that are displayed in the Join Properties dialog box, the type of join they use, and whether all rows or matching rows are included for each table.
Choice 1. Only include rows where the joined fields from both tables are equal. 2. Include ALL records from 'Customers' and only those records from 'Orders' where the joined fields are equal. 3. Include ALL records from 'Orders' and only those records from 'Customers' where the joined fields are equal. Relational join Inner join Left table Matching rows Right table Matching rows

Left outer join

All rows

Matching rows

Right outer join

Matching rows

All rows

When you choose option 2 or option 3, an arrow is shown on the relationship line. This arrow points to the side of the relationship that shows only matching rows.

Make changes in the Join Properties dialog box


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

On the Database Tools tab, in the Show/Hide group, click Relationships.

The Relationships window appears.

If you have not yet defined any relationships and this is the first time you are opening the Relationships window, the Show Table dialog box appears. If the dialog box appears, click Close.

4.

On the Design tab, in the Relationships group, click All Relationships.

All tables that have relationships are displayed, showing relationship lines. Note that hidden tables (tables for which the Hidden check box in the table's Properties dialog box is selected) and their relationships will not be shown unless Show Hidden Objects is selected in the Navigation Options dialog box.

For more information about the Show Hidden Objects option, see the article Guide to the Navigation Pane.

5.

Click the relationship line for the relationship that you want to change. The relationship line appears thicker when it is selected.

6.

Double-click the relationship line.

or

On the Design tab, in the Tools group, click Edit Relationships.

The Edit Relationships dialog box appears.

7.

Click Join Type

8.

In the Join Properties dialog box, click an option, and then click OK.

9.

Make any additional changes to the relationship, and then click OK.

Top of Page

Enforce referential integrity

The purpose of using referential integrity is to to prevent orphan records and to keep references synchronized so that you don't have any records that reference other records that no longer exist. You enforce referential integrity by enabling it for a table relationship. Once enforced, Access rejects any operation that would violate referential integrity for that table relationship. Access rejects updates that change the target of a reference, and also deletions that remove the target of a reference. To have Access propagate referential updates and deletions so that all related rows are changed accordingly, see the section Set the cascade options.

Turn referential integrity on or off


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

On the Database Tools tab, in the Show/Hide group, click Relationships.

The Relationships window appears.

If you have not yet defined any relationships and this is the first time you are opening the Relationships window, the Show Table dialog box appears. If the dialog box appears, click Close.

4.

On the Design tab, in the Relationships group, click All Relationships.

All tables that have relationships are displayed, showing relationship lines. Note that hidden tables (tables for which the Hidden check box in the table's Properties dialog box is selected) and their relationships will not be shown unless Show Hidden Objects is selected in the Navigation Options dialog box.

For more information about the Show Hidden Objects option, see the article Guide to the Navigation Pane.

5.

Click the relationship line for the relationship that you want to change. The relationship line appears thicker when it is selected.

6.

Double-click the relationship line.

or

On the Design tab, in the Tools group, click Edit Relationships.

The Edit Relationships dialog box appears.

7.

Select the Enforce Referential Integrity check box.

8.

Make any additional changes to the relationship, and then click OK.

After you have enforced referential integrity, the following rules apply:

You cannot enter a value in the foreign key field of a related table if that value doesn't exist in the primary key field of the primary table doing so creates orphan records.

You cannot delete a record from a primary table if matching records exist in a related table. For example, you cannot delete an employee record from the Employees table if there are orders assigned to that employee in the Orders table. You can, however, choose to delete a primary record and all related records in one operation by selecting the Cascade Delete Related Records check box.

You cannot change a primary key value in the primary table if doing so would create orphan records. For example, you cannot change an order number in the Orders table if there are line items assigned to that Order in the Order Details table. You can, however, choose to update a primary record and all related records in one operation by selecting the Cascade Update Related Fields check box.

NOTES

If you have difficulty enabling referential integrity, note that the following conditions are required in order to enforce referential integrity:

The common field from the primary table must be a primary key or have a unique index.

The common fields must have the same data type. The one exception is that an AutoNumber field can be related to a Number field that has a FieldSize property setting of Long Integer.

Both tables must exist in the same Access database. Referential integrity cannot be enforced on linked tables. However, if the source tables are in Access format, you can open the database in which they are stored and enable referential integrity in that database.

Set the cascade options


You might encounter a situation in which you have a valid need to change the value on the "one" side of a relationship. In such a case, you need Access to automatically update all of the effected rows as part of a single operation. That way, the update is completed in full so that your database is not left in an inconsistent state with some rows updated and some not. Access helps you avoid this problem by supporting the Cascade Update Related Fields option. When you enforce referential integrity and choose the Cascade Update Related Fields option, and you then update a primary key, Access automatically updates all fields that reference the primary key.

You might also need to delete a row and all related records for instance, a shipper record and all related orders for that shipper. For this reason, Access supports the Cascade Delete Related Records option. When you enforce referential integrity and choose the Cascade Delete Related Records option, Access automatically deletes all records that reference the primary key when you delete the record that contains the primary key.

Turn cascade update and/or cascade delete on or off


1. Click the Microsoft Office Button , and then click Open.

2.

In the Open dialog box, select and open the database.

3.

On the Database Tools tab, in the Show/Hide group, click Relationships.

The Relationships window appears.

If you have not yet defined any relationships and this is the first time you are opening the Relationships window, the Show Table dialog box appears. If the dialog box appears, click Close.

4.

On the Design tab, in the Relationships group, click All Relationships.

All tables that have relationships are displayed, showing relationship lines. Note that hidden tables (tables for which the Hidden check box in the table's Properties dialog box is selected) and their relationships will not be shown unless Show Hidden Objects is selected in the Navigation Options dialog box.

For more information about the Show Hidden Objects option, see Guide to the Navigation Pane.

5.

Click the relationship line for the relationship that you want to change. The relationship line appears thicker when it is selected.

6.

Double-click the relationship line.

or

On the Design tab, in the Tools group, click Edit Relationships.

The Edit Relationships dialog box appears.

7.

Select the Enforce Referential Integrity check box.

8.

Select either the Cascade Update Related Fields or Cascade Delete Related Records check box, or select both.

9.

Make any additional changes to the relationship, and then click OK.

What is a lookup column?


A lookup column (or field) is a field in a table whose value is retrieved from another table or from a value list. You can use a lookup column to display a list of choices in a combo box or list box. The choices can come from a table or query, or they can be values that you supply. You can create a lookup column manually by setting a field's Lookup field properties, or automatically by completing the Lookup Wizard. Whenever possible, you should use the Lookup Wizard to create a lookup column. The Lookup Wizard simplifies the process and automatically populates the appropriate field properties and creates the appropriate table relationships.

You can create a lookup column in either Datasheet View or in Design View.

Top of Page

Create a lookup column in Datasheet View


By default, when you open a table, it opens in Datasheet view. You can add a lookup column by clicking Lookup Column in the Fields & Columns group on the Datasheet tab. Doing so starts the Lookup Wizard, which leads you through the process of creating the lookup column.

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, double-click the table in which you want to create the lookup column this opens the table in Datasheet view.

4.

On the Datasheet tab, in the Fields & Columns group, click Lookup Column.

The Lookup Wizard starts.

5.

On the first page of the Lookup Wizard, indicate whether you want to base the lookup column on the values in a table or a query, or on a list of values that you type.

The most common type of lookup column is one that displays values looked up from a related table or query.

6.

Click Next, and then follow the instructions to complete the wizard. For more information about completing the wizard, see the section Using the Lookup Wizard.

When you click Finish, a lookup column is created whose field properties are set based on the choices you made in the Lookup Wizard.

Top of Page

Create a lookup column by using the Field List pane


If you are using a database that contains more than one table, you can start the process of creating a lookup field by dragging a field from the Field List pane. The Field List pane displays fields that are available in other tables in your database. When you create a lookup column this way, the Lookup Wizard is automatically started and the field that you drag to the datasheet becomes one of the fields in your lookup column.

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, double-click the table in which you want to create the lookup column this opens the table in Datasheet view.

4.

On the Datasheet tab, in the Fields & Columns group, click Add Existing Fields.

The Field List pane appears.

5.

Click the plus sign (+) next to a table to display the list of fields in that table.

6.

Drag the field that you want from the Field List pane to the table in Datasheet view.

7.

When the insertion line appears, drop the field in position.

The Lookup Wizard starts.

8.

Follow the instructions to complete the wizard. For more information about completing the wizard, see the section Using the Lookup Wizard.

When you have completed the wizard, the lookup column appears in the table in Datasheet view.

Top of Page

Create a lookup column in Design View


You can create a lookup column in Design view, in addition to Datasheet view. When you work in Design view, you create a lookup column by using the same Lookup Wizard that you use in Datasheet view. However, in Design view, you also have full access to all of the field properties as a result, you can edit them directly.

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, right-click the table in which you want to add the lookup column, and then click Design View on the shortcut menu.

4.

Locate the first available empty row in the table design grid.

5.

In the first available empty row, click a cell in the Field Name column, and then type a field name for the lookup column.

6.

Next, click a cell in the Data Type column for that row, click the drop-down arrow, and then select Lookup Wizard.

The Lookup Wizard starts.

7.

On the first page of the Lookup Wizard, indicate whether you want to base the lookup column on the values in a table or a query, or on a list of values that you type.

The most common type of lookup column is one that displays values looked up from a related table or query.

8.

Click Next, and then follow the instructions to complete the wizard. For more information about completing the wizard, see the section Using the Lookup Wizard.

When you click Finish, a lookup column is created whose field properties are set based on the choices you made in the Lookup Wizard. You can view the field properties in the bottom pane of Design view under Field Properties. To see the properties that apply specifically to the lookup column, click the Lookup tab.

Understanding the bound value and the display value in a lookup column
The purpose of using a lookup column is to replace the display of a number ,such as an ID (or other foreign key value), with something more meaningful, such as a name. For example, instead of displaying a contact ID number, Access can display a contact name. The contact ID number is the bound value. It is automatically looked up in a source table or query to find the contact name. The contact name is the display value.

Display value

Bound value

A lookup column has a display value that appears in the user interface, and a bound value that is stored in the control. The display value is "looked up," based on the bound value. This means that Access often displays a lookedup display value that is not the same as the bound value that is stored in the field. For example, in the example of an Orders table, a customer ID value from the Customers table is stored in the Customer field in the Orders table this is the bound value. However, because the Customer field is a lookup field, Access displays the looked-up value in this case, the customer name. The customer name is the display value.

It is important to understand the distinction between a lookup field's display value and its bound value. The display value is automatically shown in Datasheet view, by default. However, the bound value is what is stored, what you use in query criteria, and what Access uses by default in joins with other tables.

Top of Page

Introducing the Lookup field properties

You can view the Lookup field properties in the bottom pane of Design view under Field Properties. To see the properties specifically related to the lookup column, click the Lookup tab.

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, right-click the table in which you want to add the lookup column, and then click Design View on the shortcut menu.

4.

Click a cell in the Field Name column for the lookup column.

5.

Under Field Properties, click the Lookup tab.

The Lookup field properties appear.

When you set the first property (Display Control), the list of available properties changes to reflect your choice. You can set the Lookup field properties to change the behavior of a lookup column. Note than when you create the lookup column by using the Lookup Wizard, the Lookup field properties are set for you by the wizard.

Lookup field Properties


Set this property Display Control To Set the control type to Check Box, Text Box, List Box or Combo Box.Combo Box is the most common choice for a lookup column. Choose whether to fill the lookup column with values from another table or query, or from a list of values that you specify. You can also choose to fill the list with the names of the fields in a table or query. Specify the table, query, or list of values that provides the values for the lookup column. When the Row Source Type property is set to Table/Query or Field List, this property should be set to the name of a table or query or to a SQL statement that represents the query. When the Row Source Type property is set to Value List, this property should contain a list of values separated by semicolons. Specify the column in the row source that supplies the value stored by the lookup column. This value can range from 1 to the number of columns in the row source. NOTE The column that supplies the value to store does not have to be the same column as the display column.

Row Source Type

Row Source

Bound Column

Column Count

Specify the number of columns in the row source that can be displayed in the lookup column. To select which columns to display, you provide a column width in the Column Widths property. Specify whether to display column headings.

Column Heads

Column Widths

Enter the column width for each column. If you don't want to display a column, such as an ID number, specify 0 for the width. Specify the number of rows that appear when you display the lookup column. Specify the width of the control that appears when you display the lookup column. Choose whether a user can enter a value that isn't found in the list. Specify whether the lookup column employs a multivalued field and allows multiple values to be selected. For more information about multivalued fields, see the article Guide to multivalued fields.

List Rows List Width Limit To List Allow Multiple Values

Allow Value List Edits

Specify whether you can edit the items in a lookup column that is based on a value list. When this property is set to Yes, and you right-click a lookup field that is based on a single column value list, you will see the Edit List Items menu option. If the lookup field has more than one column, this property is ignored. Specify an existing form to use with which you can edit the list items in a lookup column that is based on a table or query. Show only values that match the current row source when Allow Multiples Values is set to Yes.

List Items Edit Form

Show Only Row Source Values

The bound value in a lookup column is determined by the Bound Column property. The display value in a lookup column is the column or columns that are represented in the Column Widths property as having a non-zero width.

Top of Page

Using the Lookup Wizard


The Lookup Wizard starts in the following cases: when you create a lookup column in Datasheet view, when you drag a field from the Field List pane to a table that is opened in Datasheet view, and in Design view when you select Lookup Wizard in the Data Type column. The wizard walks you through the steps needed to create a lookup column and automatically sets the appropriate field properties to match your choices. The wizard also creates table relationships and indexes, where needed, to support the lookup column.

When the wizard starts, you must decide whether to base the lookup column on a table or query, or on a list of values that you enter. Most of the time, if your database is properly designed and your information is divided into subjectbased tables, you should choose a table or query as the source of data for the lookup column.

Table or query based lookup column


If you chose the I want the lookup column to look up the values in a table or query option, when you click Next, the Lookup Wizard displays a list of tables that are available to provide the values for the lookup column. To see only tables, click Tables. To see only queries, click Queries. To see both tables and queries, click Both. When you have chosen a table or query, click Next.

The Lookup Wizard lists the available fields from your table or query. For each field that you want to include in your lookup column, click the field and then click the greater than button (>) to move it into the Selected Fields list. Note that you should select the fields that you want to be visible in addition to the field that you want to supply the value that is stored when you make a selection in the lookup column. When you are finished, click Next.

The Lookup Wizard displays a page that allows you to specify a field or fields that you can use to sort the lookup column. This sorting is optional. When you are finished, click Next.

You can adjust the width of the columns that will appear in the lookup column. If you reduce the width of a field so that it is no longer visible, it will not appear in the lookup column. For example, you can use this feature to prevent an ID column from being displayed. When you are finished, click Next.

When you select a row in the lookup column, you can store a value from that row in your database or use the value later to perform an action. This page of the wizard, shown in the following figure, allows you to choose the field that supplies that value. You should choose a field that uniquely identifies the row. Usually, the primary key field of the source table makes a good choice. When you are finished, click Next.

On the final page of the Lookup Wizard, you should type a name for your lookup column this becomes the name of the field in your table.

If you want to allow selection of more than one value when the lookup column appears, and then store the multiple values, select the Allow Multiple Values check box. Note that selecting this check box changes the lookup column to a multivalued field.

For more information about multivalued fields, see the articles Guide to multivalued fields and Add or change a lookup column that lets you store multiple values.

Value list-based lookup column


If you chose the I will type in the values that I want option, when you click Next, the Lookup Wizard displays a grid in which you can type the values for the lookup column.

First, enter the number of columns that you want to include in the lookup column. Then, type your values in the grid. You can adjust the width of the columns that will appear in the lookup column. If you reduce the width of a field so that it is no longer visible, it will not appear in the lookup column. When you are finished, click Next.

When you select a row in the lookup column, you can store a value from that row in your database or use the value later to perform an action. This page in the wizard, shown in the following figure, allows you to choose the field that supplies that value. You should choose a field that uniquely identifies the row. When you are finished, click Next.

On the final page of the Lookup Wizard, you should enter a name for your lookup column this becomes the name of the field in your table. If you want to allow selection of more than one value when the lookup column appears, and then store the multiple values, select the Allow Multiple Values check box. Note that selecting this check box changes the lookup column to a multivalued field.

For more information about multivalued fields, see the articles Guide to multivalued fields or Add or change a lookup column that lets you store multiple values.

Top of Page

Change a lookup column


To change a lookup column, you can open the table in Design View and then modify the Lookup field properties. For information about the Lookup field properties, see the section Introducing the Lookup Field Properties. If the lookup column is based on a value list and the Allow Value List Edits property is set to Yes, you can edit the list items in Datasheet view or Form view. To edit the list items in Datasheet view or Form view:

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation pane, double-click the table or form that contains the multivalued field.

The table opens in Datasheet view or the form opens in Form view.

4.

Right-click the lookup column, and then click Edit List Items on the shortcut menu.

5.

Change the value list and then click OK.

Top of Page

Change a field to a lookup column


To change an existing field to a lookup column, in Design view, open the table that contains the field you want to change, click in the Data Type column of the field, click the drop-down list, and then select Lookup Wizard. Then, follow the instructions in the Lookup Wizard to create the lookup column.

1.

Click the Microsoft Office Button

, and then click Open.

2.

In the Open dialog box, select and open the database.

3.

In the Navigation Pane, right-click the table in which you want to add the lookup column, and then click Design View on the shortcut menu.

4.

Locate the field that you want to change to a lookup column.

5.

Next, click the cell in the Data Type column for that row, click the drop-down arrow, and then select Lookup Wizard....

The Lookup Wizard starts.

6.

On the first page of the Lookup Wizard, indicate whether you want to base the lookup column on the values in a table or query, or on a list of values that you enter.

The most common type of lookup column is one that displays values looked up from a related table or query.

7.

Click Next, and then follow the instructions to complete the wizard. For more information about completing the wizard, see the section Using the Lookup Wizard.

When you click Finish, a lookup column is created whose field properties are set based on the choices you made in the Lookup Wizard. You can view the field properties in the bottom pane of Design view under Field Properties. To see the properties that apply specifically to the lookup column, click the Lookup tab.

About expressions
In Office Access 2007, an expression is the equivalent of a formula in Office Excel 2007. An expression consists of a number of elements that you use, alone or in combination, to produce a result. Those elements can include:

Identifiers the names of table fields or controls on forms or reports, or the properties of those fields or controls.

Operators, such as + (plus) or - (minus).

Functions, such as SUM or AVG, and the arguments that are used with them.

Constants values that do not change such as strings of text, or numbers that are not calculated by an expression.

You use an expression to perform a calculation, retrieve the value of a field or control, supply criteria to a query, define rules, create calculated controls and calculated fields, and define a grouping level for a report.

You use an expression when you need to create values that do not reside directly in your data. For example, you might need to calculate sales tax on an order, or calculate the total value of the order itself. At other times, you'll need to add criteria to a query or filter information that determines which records the query returns or that appear when a filter is applied. In other cases, you might want to set a default value or a validation rule for a field or control. In all of these cases, you use an expression.

The following table shows some sample expressions and how they are typically used:

Expression =[RequiredDate]-[ShippedDate]

Purpose Calculates the difference between the date values in two text box controls (called RequiredDate and ShippedDate) on a report. Sets the default value for a Date/Time table field to the current date. Creates a calculated field in a query.

Date() ExtendedPrice: CCur([Order Details].Unit Price*[Quantity]*(1[Discount])/100)*100 Between #1/1/2005# And #12/31/2005# =[Orders Subform].Form!OrderSubtotal

Used to enter criteria for a Date/Time field in a query. Returns the value of the OrderSubtotal control on the Orders subform that is on the Orders form. Sets a validation rule for a numeric field in a table users must

>0

enter values greater than zero.

As you can see from the preceding examples, an expression in Access is not just a mathematical calculation. Instead, expressions serve a variety of purposes. You will also notice that the sample expressions differ from each other in some ways. For example, some expressions start with the = (equal) operator. When calculating a value for a control on a form or report, you use the = operator to start the expression. In other instances, you don't use the = operator. For example, when you type an expression in a query or in the DefaultValue or ValidationRule property of a field or control, you don't use the = operator unless you're adding the expression to a Text field in a table. In some cases, such as adding expressions to queries, Access removes the = operator automatically. For more information about expression syntax, see the article A guide to expression syntax.

The following sections describe the various parts of an expression in more detail. The examples in the sections also provide brief descriptions of the syntax that expressions use.

Identifiers
An identifier is the name of a field, property, or control. You use an identifier in an expression to refer to the value that is associated with a field, property, or control. For example, consider the expression =[RequiredDate][ShippedDate]. This expression subtracts the value of the ShippedDate field or control from the value of the RequiredDate field or control. In this expression, both RequiredDate and ShippedDate serve as identifiers.

Operators
Access supports a variety of operators, including the expected arithmetic operators such as +, -, * (multiply), / (divide). You can also use comparison operators for comparing values, text operators for concatenating (combining) text, logical operators for determining true or false values, and other operators specific to Access. For details about operators, see the section Table of operators.

Functions and arguments


Functions are built-in procedures that you can use in your expressions. You use functions for a wide variety of operations, such as calculating values, manipulating text and dates, and summarizing data. For example, one commonly used function is Date, which returns the current date. You can use the Date function in a variety of ways, such as an expression that sets the default value for a field in a table. That way, whenever someone adds a new record, the value for the field defaults to the current date.

Some functions require arguments. An argument is a value that provides input to the function. If a function requires more than one argument, you separate the arguments with a comma. For example, consider the Date function in the following example expression:

=Format(Date(),"mmmm d, yyyy")

This example uses two arguments. First, the Date function supplies the current date. The second argument, separated from the first by a comma, is a text string that tells the Format function how to format the date value. Note that the text string is enclosed in quotation marks. As a general rule, when you need to supply text, you place it inside quotation marks. This expression also illustrates a principle that you should remember as you proceed: You can often use the value returned by one function as an argument to yet another function.

For more information about how to use quotation marks and expression syntax in general, see the article A guide to expression syntax.

Finally, Access supports a large number of built-in functions. For links to information about the functions, see the article Functions (arranged by category).

Constants
A constant is a named item whose value remains constant while Access is running. Typically, you use the True, False, and Null constants most often in your expressions. You can also define your own constants in Visual Basic for Applications (VBA) code that you can use in VBA procedures. VBA is the programming language that Access uses.

NOTE

You cannot use Microsoft Visual Basic constants in custom functions that you use in your expressions. For

example, Visual Basic has constants for the days of the week: vbSunday represents Sunday, vbMonday represents Monday, and so on. Each of these constants has a corresponding numeric value: The numeric value for vbSunday is 1, vbMonday is 2, and so on. You cannot use these constants in a custom function that is called from within an expression. You must instead use the numeric values.

Values
You can employ literal values in your expressions, such as the number 1,254 or the string "Enter a number between 1 and 10." Numeric values can be a series of digits, including a sign and a decimal point, if needed. In the absence of a

sign, Access assumes a positive value. To make a value negative, include the minus sign (-). You can also use scientific notation. To do so, include "E" or "e" and the sign of the exponent (for example, 1.0E-6).

When you use text strings as constants, place them within quotation marks. In some circumstances, Access will supply the quotation marks for you. For example, when you type text in an expression for a validation rule or for query criteria, Access surrounds your text strings with quotation marks automatically.

For example, if you type the text Paris, Access displays "Paris" in the expression. If you want an expression to produce a string that is actually enclosed in quotation marks, you can enclose the nested string either in single (') quotation marks or within three sets of double (") quotation marks. For example, the following expressions are equivalent:

Forms![Contacts]![City].DefaultValue = ' "Paris" '

Forms![Contacts]![City].DefaultValue = " " "Paris" " "

To use date/time values, you enclose them in pound signs (#). For example, #3-7-07#, #7-Mar-07#, and #Mar-72007# are all valid date/time values. When Access sees a valid date/time value enclosed by # characters, it automatically treats the value as a Date/Time data type.

Top of Page

Why you use expressions


In Access, you use expressions when you need to do any of the following:

Calculate values that do not exist directly in your data. You can calculate values for table fields, for queries, and for controls on forms and reports.

Set a default value for a table field or a control on a form or report. Your default values then appear whenever you open a table, form, or report for use.

Create a validation rule. Validation rules control what values users can and cannot enter into a field or control.

Set criteria for a query.

The following figure illustrates some typical expressions used in the scenarios described here:

For example, suppose that you need to calculate the total dollar amount for a line item in an invoice. Typically, you do not store the line item total in the database. Instead, you calculate it as needed from two items that you should store in the database quantity and price. You then use an expression such as this one to calculate the value:

=CCur([Quantity]*[Price])

This expression multiplies quantity times price and then uses the CCur function (convert to currency) to convert the result to the Currency data type. You can also calculate a discount for each order.

You can also create a field in a query that calculates a line item total, and then use that value in a form or report. A column in a query that results from such a calculation is called a calculated field. For example, the following expression in a query calculates the line item totals with an applied discount:

ExtendedPrice: CCur([Order Details].[Unit Price]*[Quantity]*(1-[Discount])/100)*100

The expression gives the resulting column the name ExtendedPrice. You create a calculated field whenever you need to calculate or perform operations on the data in two or more table fields. For example, many tables store first and last names in separate fields. If you want to combine those first and last names and display them in a single field, you create a calculated field in a query. Some users try to create those types of calculated fields directly in tables, but

by default, tables do not support that type of operation they do not provide a field or property in which you can add the necessary expression.

A calculated field that combines first and last names would look like this: [FirstName] & " " & [LastName]. In this case, the ampersands combine the values in the FirstName and LastName fields with a space the double quotes with a space between them.

You can also use expressions to provide a default value for a field in a table or for a control. For example, if you have a date field that you want to default to the current date, you can type Date() in the Default Value property box for that field.

You can also use an expression to set a validation rule. For example, you might use a validation rule that requires the date that is entered to be greater than or equal to the current date. In that case, you set the value in the Validation Rule property box to >= Date().

Finally, you can also use an expression to set criteria for a query. For example, suppose you want to see product sales for the orders that were shipped within a certain time frame. You can enter criteria to define a date range, and Access returns only the rows that match the criteria:

Between #1/1/2007# And #12/31/2007#

When you add criteria to the query and then run the query, it returns only those values that match the specified dates.

Top of Page

Where and how to use expressions


You can use an expression in many places in a database. For example, tables, queries, forms, reports, and macros all have properties that accept an expression. For example, you can use expressions in the Control Source and Default Value properties of controls. You can also use them in the Validation Rule property in table fields. In addition, when you write VBA code for an event procedure or for a module, you often use expressions that are similar to those that you use in an Access object, such as a table or query.

A brief look at expression syntax

Expressions often use the data in your tables and queries and also data stored in controls on forms and reports. To use those data, expressions reference the names of the fields in your tables and queries, and the names of your controls. To use field and control names in expressions, you enclose them in brackets ([ ]). For example, if you want to use a table field called Unit Price in an expression, you enter it as [Unit Price]. If you enter a name that doesn't include spaces or special characters, Access automatically encloses it in brackets. If a name includes spaces or special characters, you must type the brackets yourself.

For more information about expression syntax, see the article A guide to expression syntax.

Using expressions in form and report controls


You can give a name to a calculated control by setting the control's Name property. The name must be unique among all the control names on the form or report. It also must be different from any field or control name that is used in the expression for that control, and it should be different from any field name in the underlying table or query. You can use this name when you want to refer to the value in the control in other expressions on the form or report.

The most common places where you use expressions include the following:

In a text box control on a form or report This creates a calculated control. For example, suppose you want to create a subtotal that sums all of the line items on an order form. The subtotal might look something like this on your form:

To calculate the subtotal, you place a text box control on the form and set the ControlSource property of the text box to the following expression:

=Sum([table_field])

In this case, table_field is the name of the field that contains your subtotal values. That field can reside in a table or a query. The Sum function calculates the total for a set of values from your record source.

The following steps explain how to enter an expression in a text box control.

Enter an expression in a text box control


1. In the Navigation Pane, right-click the form that you want to change and click Design View.

2.

Right-click the text box that you want to change, and click Properties to display the property sheet for the control.

-or-

On the Design tab, in the Tools group, click Property Sheet.

3.

On the Data tab or the All tab of the property sheet, click the ControlSource property of the text box, and then enter = and the rest of your expression. For example, to calculate the subtotal shown above, you type =Sum([table_field]), being sure to substitute the name of your field with table_field.

-or-

Click the Build button Expression Builder.

to the right of the property box to create an expression by using the

Your property sheet will look something like the following illustration:

4.

Close the property sheet and save your changes.

Using expressions in query criteria

You use an expression to define criteria in a query. Access then returns only those rows that match the criteria. For example, suppose you want to see all orders whose shipped date occurs in the year 2004. To enter the criteria, you enter the following expression in the Criteria cell for the Date/Time column in your query. This example uses a Date/Time column called ShippedDate. To define a date range, enter the following criteria:

Between #1/1/2004# And #12/31/2004#

The ShippedDate column will look something like the following illustration.

The expression determines whether the values in the ShippedDate column fall in the date range that you specify. Note that you surround the dates with pound signs (#). Access treats a value within the pound signs as a Date/Time data type. If you are new to Access, treating those values as date/time data enables you to perform calculations on those values.

For more information about using date/time data, see the articles Enter a date or time value and Insert, create, or delete a field that stores date values.

Enter criteria in the query design grid


1. In the Navigation Pane, right-click the query that you want to change, then and click Design View on the shortcut menu.

2.

Click in the Criteria cell in the column for which you want to enter your criteria.

3.

Type your criteria expression.

-or-

On the Design tab, in the Query Setup group, click Builder to start the Expression Builder and build your criteria.

NOTE

Do not precede the criteria expression with the = operator.

If you want a larger area in which to enter an expression, press SHIFT+F2 to display the Zoom dialog box.

Using expressions to create calculated fields in of a query


You use an expression to create a calculated field in a query. For example, suppose you want to display the year that an order was shipped as part of a query. To create the calculated field, you place the following expression in a blank cell in the Field row in your query:

Year Shipped: Format([ShippedDate],"yyyy")

In this case, the expression uses the Format function to extract the year from the values in a field called ShippedDate. The Format function then formats the year as four digits. Prefacing the expression with Year Shipped: names the resulting column Year Shipped.

Enter a calculated field in query Design view

1.

In the Navigation Pane, right-click the query that you want to change, and then click Design View on the shortcut menu.

2.

Click the Field cell in the column where you want to create the calculated field.

3.

Type your expression.

-or-

On the Design tab, in the Query Setup group, click Builder to start the Expression Builder and build your criteria.

NOTE

Do not precede the criteria expression with the = operator, but do start the expression with

a name followed by a colon. For example, you type ExtendedPrice: to start an expression that creates a calculated field called ExtendedPrice.

Using expressions in the Validation Rule property of a table field


Another place where an expression comes in handy is the Validation Rule property of a field in a table. Suppose you have a table called Inventory with a field called Units On Hand, and you want to set a rule that forces users to enter a value greater than or equal to zero. In other words, inventory can never be a negative number. You can do this by using the expression shown in the following illustration.

Enter a validation rule for a field in a table


1. In the Navigation Pane, right click the table that you want to change, and then click Design View on the shortcut menu.

2.

In the Field Name column, click the field that you want to change.

3.

On the General tab, click the Validation Rule property box.

4.

Type your expression.

-or-

Click the Build button your expression.

to the right of the property box to start the Expression Builder and create

-or-

On the Design tab, in the Tools group, click Builder to start the Expression Builder.

NOTE

Do not precede the expression with the = operator when you create a validation rule.

The key point to remember when you work with validation rule expressions is that they must resolve to True for the value to be accepted. So, in this example, the value for [Units On Hand] must be >=0. If it isn't, Access displays the text shown in the Validation Text property box. If you haven't entered any text in the Validation Text property box, Access displays its own message to indicate that the value you entered is prohibited by the validation rule for the field.

For more information about creating validation rules, see the article Create a validation rule to validate data in a field.

Using expressions in the Validation Rule property of a control


You can also set the Validation Rule property for a control. For example, suppose you use a form to enter the date range for a report, and you want to ensure that the beginning date isn't earlier than 1/1/2004. You can set the Validation Rule and ValidationText properties for the text box where you enter the beginning date to something like the following.

Property ValidationRule

Setting >=#1/1/2004#

ValidationText

You cannot enter a date earlier than 1/1/2004.

If you try to enter a date earlier than 1/1/2004, a message appears. After you click OK, Access returns you to the text box.

Enter a validation rule for a control


1. In the Navigation Pane, right-click the form or report that you want to change and click Design View on the shortcut menu.

-or-

If you already have the form or report open, right-click the document tab and click Design View on the shortcut menu.

-or-

On the Home tab, in the View group, click the View button to toggle between available views. Alternatively, you can click the arrow under View, and then select one of the available views from the menu.

2.

Right-click the control that you want to change and click Properties.

-or-

On the Design tab, in the Tools group, click Property Sheet.

Access displays the property sheet for the control.

3.

Click the All tab, and then click the Validation Rule property box.

4.

Type the expression, or click the Build button expression by using the Expression Builder.

to the right of the property box to create an

NOTE

Do not precede the expression with the = operator when you create a validation rule.

5.

Optionally, change the Validation Text property.

6.

Close the property sheet and save your changes.

When you enter a value that the validation rule prohibits, you can press ESC while the cursor is in the control to restore the original or default value. You can then enter a value that satisfies the validation rule.

If the Control Source property for your control is a field in a table, it's usually best to set the field's Validation Rule property, in addition to that of the control. That way, the rule is enforced all the time, no matter which form or query is used to update the field.

For more information about creating validation rules, see the article Create a validation rule to validate data in a field.

Using expressions to set default values for a table field


You can use an expression to store a default value for a field in a table. For example, suppose you want to automatically insert the date and time into a field called OrderDate when you add a new record. You can use an expression like the following.

The expression uses the Now function to insert the date and time into the OrderDate field.

Enter a default value for a field in a table


1. In the Navigation Pane, right-click the table that you want to change and click Design View on the shortcut menu.

2.

In the Field Name column, click the field that you want to change.

3.

On the General tab, click the Default Value property box.

4.

Type your expression, or click the Build button expression by using the Expression Builder.

to the right of the property box to create an

If you bind a control to a table field, and the control and field have a default value, the control's default value takes precedence.

For more information about setting default values, see the article Set default values for fields or controls.

Using expressions to set default values for controls


Another common place to use an expression is in the Default Value property of a control. The Default Value property of a control behaves similarly to the Default Value property of a field in a table. For example, if you want to enter the current date as the default value for a text box named OrderDate, you can use an expression like the following.

This expression uses the Date function to return the current date, but not the time. If you bind the text box to a table field, and the field has a default value, the control's default value takes precedence. It often makes better sense to set the Default Value property for the field in the table, because the default value is always applied to the control unless the control overrides it.

Enter a default value for a control


1. In the Navigation Pane, right-click the form or report that you want to change and click Design View on the shortcut menu.

-or-

If you already have the form or report open, right-click the document tab and click Design View on the shortcut menu.

-or-

On the Home tab, in the View group, click the View button to toggle between available views. Alternatively, you can click the arrow under View, and then select one of the available views from the menu.

2.

Right-click the control that you want to change, and then click Properties.

-or-

On the Design tab, in the Tools group, click Property Sheet.

Access displays the property sheet for the control.

3.

Click the All tab, and then click the Default Value property box.

4.

Type the expression, or click the Build button expression by using the Expression Builder.

to the right of the property box to create an

5.

Close the property sheet.

For more information about setting default values, see the article Set default values for fields or controls.

Using expressions to carry out macro actions


In some cases, you might want to carry out an action or series of actions in a macro only if a particular condition is true. For example, suppose you want a macro action to run only when the value in a text box equals 10. To do so, you use an expression to define the condition in the Condition column of the macro.

In this example, assume the text box is named "Items."

Enter a condition for a macro action


1. In the Navigation Pane, right-click the macro that you want to change and click Design View on the shortcut menu.

2.

If you do not see the Condition column in the macro designer, on the Design tab, in the Show/Hide group, click Conditions.

3.

In the Condition column, click the blank cell next to the macro action that you want to change, and then type your conditional expression.

4.

Save your changes and then close the macro.

As with the Validation Rule property, the expression in the Condition column must resolve to either True or False. The macro action runs only when the condition is True.

For more information about creating macros, see the articles Macro basics in Access 2007 and Create a macro.

Using expressions to group and sort data in reports


You use the Group, Sort, and Total pane to define grouping levels and sorting orders for the data in a report. The pane replaces the Sorting and Grouping dialog box provided by earlier versions of Access. You can display and use the pane only when you open a report in Design view the pane appears in the same window as your report.

The following figure illustrates the pane as it appears when it first opens:

If you are new to Access, grouping is the process of combining columns that contain duplicate values. For example, suppose your database contains sales information for offices in different cities. One of the most common reports in that type of database is "Sales by City," and the query that provides the data for the report groups the data by your city values. Grouping can make your information easier to read and understand.

In contrast, sorting is the process of imposing an order on the rows (the records) in your query results. For example, you can sort records by their primary key values (or another set of values in another field) in either ascending or descending order, or you can sort them by one or more characters in (for example) alphabetical order. As you proceed, remember that, by default, queries in Access return records by the fastest means possible. When you first create a query, Access might return your data in a way that makes sense, such as by the sequence of primary key values. However, as users change data and add or remove rows, Access might return your data in a different sequence because that new sequence is faster. You

impose a sort order when you need your queries to return data in the same sequence, regardless of changes to that data.

For more information about combining text values, see the Combining text values section.

Add grouping and sorting to a report


1. In the Navigation Pane, right-click the report that you want to change and click Design View on the shortcut menu.

-or-

If you already have the report open, right-click the document tab and click Design View on the shortcut menu.

-or-

On the Home tab, in the View group, click the View button to toggle between available views. Alternatively, you can click the arrow under View, and then select one of the available views from the menu.

2.

On the Design tab, in the Grouping & Totals group, click Group & Sort.

The Group, Sort, and Total pane appears at the bottom of the working area.

3.

Click Add a group to add a grouping level to the report.

-or-

Click Add a sort to add a sort order to the report.

A new group or sort order appears in the pane, plus a list of the fields that provide data for the report. This figure illustrates a typical new group and sort order, plus a window that contains the available fields:

4.

In the window that contains the available fields, click expression to start the Expression Builder.

5.

Enter your expression in the expression box (the upper box) of the Expression Builder. Make sure you start the expression with the equal (=) operator.

Add an expression to an existing group or sort


1. Repeat step 1 in the previous section to open your report in Design view.

2.

Click the group or sort that you want to change.

3.

Click the down arrow next to Group on (for grouping levels) or Sort by (for sort orders).

A window that contains the available fields appears.

4.

At the bottom of the window that contains the fields, click expression to start the Expression Builder.

5.

Type your expression in the expression box of the Expression Builder. Be sure to preface your expression with the equal (=) operator.

For more information about using the Expression Builder, see the next section.

For more information about grouping and sorting the data in reports, see the article Create a grouped or summary report.

Top of Page

Using the Expression Builder to create expressions


You can use the Expression Builder to help build expressions. The Expression Builder provides easy access to the names of the fields and controls in your database, and to many of the built-in functions that are available to you when you write expressions. If it helps, you can think of the Expression Builder as a way to look up and insert things that you might have trouble remembering, such as identifier names (for example, fields, tables, forms, and queries) and function names and arguments.

You can use the Expression Builder to create an expression from scratch, or you can select from some prebuilt expressions for displaying page numbers, the current date, and the current date and time.

You can start the Expression Builder from most of the places where you would write expressions manually, such as the Control Source property of a control or the Validation Rule property of a table field. As a rule, if you see the Build button ( ), you can click it to start the Expression Builder.

This figure and the text that follows illustrate the Expression Builder:

Expression box

The upper section of the builder contains an expression box where you construct your expression. You can type your expression in the box manually, or you can select elements from the three columns in the lower section of the Expression Builder and add them to your expression box. To add an element, double-click it or select it from one of the columns and then click Paste.

Operator buttons

The middle section of the Expression Builder displays buttons for inserting common arithmetical and logical operators into your expression. To insert an operator in the expression box, click the appropriate button. To display a longer list of operators that you can use in expressions, click the Operators folder in the lower-left column, and then click the category that you want in the middle column. The right column then lists all of the operators in the selected category. To insert an operator, double-click the operator, or select it and then click Paste.

Expression elements

The lower section contains three columns:

The left column displays folders that list the tables, queries, forms, and reports in your database, as well as the available built-in functions and user-defined functions, constants, operators, and common expressions.

The middle column lists specific elements or categories of elements for the folder that is selected in the left column. For example, if you click Built-In Functions in the left column, the middle column lists function categories.

The right column lists the values, if any, for the elements that you selected in the left and middle columns. For example, if you click Built-In Functions in the left column and then click a function category in the middle column, the right column lists all of the built-in functions in the selected category.

You construct your expression by typing text in the expression box and pasting elements from the other areas in the Expression Builder. For example, you can click in the lower-left column to see any of the objects in your database, and also the functions, constants, operators, and common expressions. When you click an item in the left column, the other columns change accordingly. For example, when you click the name of a table in the left column, the middle column lists the fields in that table. When you double-click Functions and then click Built-In Functions, the middle column lists all of the function categories, and the right column lists the functions in those categories. When you double-click a function to insert it into your expression, the function and the text that indicates the needed arguments

for that function appear as placeholder text in the expression box. You can then replace that text with the argument values.

When you paste an identifier (the name of a table field or control) into your expression, the Expression Builder inserts 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 a form called Customers, 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 of the context of the form, you must include the full identifier: Forms![Customers].Visible.

Start the Expression Builder in a table, form, or report


1. In the Navigation Pane, right-click the table, form, or report that you want to change and click Design View on the shortcut menu.

2.

If you open a table, in the Field Name column, click the field that you want to change, and then on the General tab, click the property that will contain the expression and click the Build button property. next to the

-or-

If you open a form or report, right-click the control that you want to change, click Properties, locate the property that will contain the expression, and then click the Build button next to the property.

Start the Expression Builder in a query


1. In the Navigation Pane, right-click the query that you want to change and click Design View on the shortcut menu.

-or-

If you have the query open, right-click the document tab for the query and click Design View on the shortcut menu.

2.

Click the cell in the design grid that will contain the expression. For example, click the Criteria cell for the column where you want to supply criteria, or click the Field cell for the column where you want to create a calculated field.

3.

On the Design tab, in the Query Setup group, click Builder.

For more information about creating expressions, including sample expressions and expression syntax, see the article A guide to expression syntax.

Top of Page

Use expressions for practical purposes


This section introduces some of the ways that you can use expressions to solve problems and calculate needed information for your forms, reports, and tables.

"Stamping" a new record with the current date and time


In some tables, it is important to keep track of ("stamp") the date or the date and time when you add a record. To have Access automatically fill in that value for you, you can create a field with the Date/Time data type and set the DefaultValue property for the field to Date() or Now(). The Date function returns the current date, as stored in your computer's system clock. The Now function returns the current date and time.

The following steps explain how to add a new field to a table, set the data type for the field to Date/Time, and then add the Now or Date functions to the field.

Add a Date/Time field and time stamp field


1. In the Navigation Pane, double-click the table that you want to change.

Access opens the table in Datasheet view.

2.

Click the first blank column, located at the far side of the table. If you can't find the blank column, look for the words Add New Field in the column header.

3.

Double-click in the column header and type a name for the field, such as Date Added, and then press ENTER.

-or-

Right-click the column, click Rename, type a name for the field, and then press ENTER.

4.

On the Datasheet tab, in the Data Type & Formatting group, click the down arrow next to the Data Type list and select Date/Time.

5.

Save your changes, keep the table open, and go to the next set of steps.

Add a date expression to a Date/Time field


1. Right-click the document tab for the table, and then click Design View on the shortcut menu.

2.

In the Field Name column, click your new field.

3.

On the General tab, click in the Default Value property box.

4.

Type Now() or Date().

5.

Click the Show Date Picker property box and set the value to Never.

6.

Save your changes and then close the table.

Now, when you add a new record to the table, Access automatically inserts the date or the date and time into the Date Added field.

Combining text values


When you want to combine the values in two or more text fields, you use the ampersand (&) operator. For example, suppose you have a form called Employees. You enter the employees first and last name in separate fields, but you want to display the employee's full name in the form header.

To display the full name, you can use this expression:

=[FirstName] & " " & [LastName]

The expression uses the & operator to combine the values in the FirstName and LastName fields. The expression also uses a pair of double quotation marks separated by a space character to insert a space between the first and last names. Remember that the spaces between the field names and the ampersand operators do not affect the appearance of your data (they only make the expression easier to read). When you want to insert something between fields, such as a space, punctuation, or literal text, you must enclose that additional value in quotation marks.

As another example, you can use this expression to display last names and first names, separated by a comma:

=[LastName] & ", " & [FirstName]

In this case, the values surround by quotation marks insert a comma and a space between the names.

The steps in this section assume you have a form, and they assume you have a table with fields called FirstName and LastName. If not, you can alter the expression in these steps to suit your own data.

Add a text box with an expression for full names


1. In the Navigation Pane, right-click the form or report that you want to change, and then click Design View on the shortcut menu.

2.

On the Design tab, in the Controls group, click Text Box.

3.

Drag the pointer on the form or report to create the text box.

4.

Right-click the text box and click Properties.

-or-

On the Design tab, in the Tools group, click Property Sheet.

5.

Click the Data tab.

6.

Change the value in the ControlSource property box to =[FirstName] & " " & [LastName], and then press TAB.

7.

Close the property sheet and save your changes.

At times, you may try to combine records that do not have a value entered in a field. The absent value is called a null value. When you use the & operator, and a field has no value, Access returns a zero-length string for that field. For example, if an employee's record has only a last name, the expression in the previous example returns a zero-length string for the First Name field, a space character, and the value in the Last Name field.

When you combine values, you might want to include a value, such as a comma, only when data exists in a particular field. To do that, you use the + operator instead of the & operator.

For example, suppose you have a table called Customer, and the table contains fields called City, Region, and Postal Code. You want to combine those fields for a report, and some records might not have a value in the Region field. In that case, you end up with an unwanted comma before the postal code value if you use the & operator.

To eliminate the unwanted comma, you can use the plus (+) operator, as shown in the following sample expression:

=([City] & (", " + [Region]) & " " & [PostalCode])

The + operator combines text in the same way as the & operator. However, the + operator also supports what is called Null propagation. This means that if any component of an expression is null, the entire expression is also null. In the previous example, consider the section that reads (", " + [Region]). Because the + operator is used, the expression within the inner parentheses includes a comma only if a value exists in the Region field. If a value does not exist, Null propagation goes into effect, and the entire expression within the inner parentheses evaluates to a null value, thus "hiding" the comma.

Creating calculated controls to perform arithmetic calculations


You can use expressions to add, subtract, multiply, and divide the values in two or more fields or controls. For example, suppose you record the date that a customer needs to receive an order and the date that the order is shipped. You can find out how many days early (or late) an order was shipped by subtracting the value in the ShippedDate field from the value in the RequiredDate field. You can do this because Access can perform arithmetic calculations on dates.

The result of a date calculation is called an interval. This value contains a days component on the left side of the decimal point, and a time component on the right side. If the value returned is a positive number, you know how many days early the order was shipped. If the value is negative, you know how many days late it was shipped. If the value is 0, you know the order was shipped on time.

The steps in this section assume that you have a form, and that form is bound to a table of data containing orders. In turn, the Orders table contains fields called RequiredDate and ShippedDate. You can alter the expression in the following steps to work with your database.

Add a text box that contains an expression to calculate the number of days early or late
1. In the Navigation Pane, right-click the form or report that you want to change and click Design View on the shortcut menu.

2.

On the Design tab, in the Controls group, click Text Box.

3.

Drag the pointer on the form or report to create the text box.

4.

Right-click the text box and then click Properties.

-or-

On the Design tab, in the Tools group, click Property Sheet.

5.

Click the Data tab.

6.

In the ControlSource property box, type =[RequiredDate]-[ShippedDate], and then press TAB.

NOTE

Remember to replace the RequiredDate and ShippedDate identifiers with the names of your own

table fields.

7.

Save your changes and then close the property sheet.

When you use the +, , *, /, or \ operators to perform a calculation on two values, and one of the values is null (that is, no value has been entered), the value of the expression evaluates to a null value. For example, if one of the dates in the previous expression is null, the value of the entire expression is also null. On a report, that results in blank space. If you want to replace the null value with 0, you can use the Nz function to convert the null value to zero. For example:

=Nz([RequiredDate]-[ShippedDate],0)

NOTE

You can also set the fields in your table so that users can't enter null values. When you design the table, set

the Required property for that field to Yes. You should also set the DefaultValue property for that field to a non-null value.

Adding the values in two controls


Often, you may want to add the values in two controls. For example, to calculate the total cost of an order, you add the values in the Subtotal and Freight controls, as shown in the following illustration.

The following steps assume you have a form with two controls that contain numeric data. In this case, the controls are called Subtotal and Freight. You can alter the control names in the following expression to work with your own data.

Add a text box with an expression that calculates a total


1. In the Navigation Pane, right-click the form or report that you want to change and click Design View on the shortcut menu.

2.

On the Design tab, in the Controls group, click Text Box.

3.

Drag the pointer on the form or report to create the text box.

4.

Right-click the text box and click Properties.

-or-

On the Design tab, in the Tools group, click Property Sheet.

5.

Click the All tab.

6.

Set the property values as shown in the following table.

Property Name ControlSource Format

Setting Total =[Subtotal]+[Freight] Currency

7.

NOTE

Remember to change the identifiers in the expression (Subtotal and Freight) to match the control

names on your form.

8.

Save your changes and then close the property sheet.

Multiplying two values to calculate the sales tax or value-added tax


Suppose you need to calculate the sales tax or value-added tax for an order. You can do this by using an expression that multiplies two existing values the sales tax rate and the subtotal amount of each order. You can place your expression in a text box control and display the results on a form or report.

For this exercise, assume that you have two table fields, SalesTaxRate and Subtotal. You could also store these values in other controls on a form or report, but for this exercise, assume they reside in a table.

Add a text box with an expression to calculate a tax amount


1. In the Navigation Pane, right-click the form or report that you want to change and click Design View on the shortcut menu.

2.

On the Design tab, in the Controls group, click Text Box.

3.

Drag the pointer on the form or report to create the text box.

4.

Right-click the text box and click Properties.

-or-

On the Design tab, in the Tools group, click Property Sheet.

5.

Click the All tab.

6.

Set the property values as shown in the following table.

Property Name ControlSource Format

Setting SalesTax =[Subtotal]*[SalesTaxRate] Currency

7.

NOTE

Remember to change the field identifiers (Subtotal and SalesTaxRate) to match the field names

in your own database.

8.

Close the property sheet.

Summing and counting groups of records


Often, you need to calculate a sum of the values stored in a group of records. For example, you might need to calculate a group total for the group footer in a report, or an order subtotal for the line items on a form. At other times, you might need to count the number of items, rather than sum them. To calculate a sum for a group of records, you use the Sum function, and to count a group of records, you use the Count function.

For example, to count the number of orders in a report that shows orders grouped by customer, you can use the following expression:

=Count([OrderID])

You can use field names in the argument expression for the Sum and Count functions, but not control names. The field names can come from a table or a query. You can even use the name of a calculated field from a query. However, when you want to total the values in a calculated control, you must repeat the expression that is used in the calculated control in the function.

When you want to refer to the same expression more than once on a form, or if you are going to use a function, such as Sum, you should consider whether you can include the expression in the form's underlying query. That way, the calculation can be performed in the query instead of on the form. It is often faster to perform a calculation in a query.

For more information about summing and counting, see the following articles:

Count the rows in a datasheet

Display column totals in a datasheet

Counting in reports

Summing in reports

Count Function

DCount Function

Sum Function

DSum Function

The following sections explain some of the ways you can use these functions.

Create a calculated control on one form and reference that control from another form
At times, you may need to create a calculated control a control that uses an expression as its data source and then reference the values in that control from a separate control located on another form. The steps in this section explain how to use the SUM function in a calculated control, and then reference that control from another form.

The steps assume the use of an orders database and an order-entry form made up of two components a main form and a subform. The main form contains data about the entire order such as such as "bill to" and "ship to" information. The subform contains details about the line items in the order, such as products, quantities of each product, and the unit prices of each product.

Separate queries supply data to each component, and the query for the subform has a calculated field called ExtendedPrice. In this example, the "extended price" is the quantity of product in each line item multiplied by the number of items, any discounts, and so on.

To calculate the subtotal amounts for each order, you need to sum the values in the ExtendedPrice field. You do that by adding the following expression to a text box. In this example, the text box is located in the footer of the subform:

The following steps explain how to add the calculated control to the subform. Information after these steps explains how to reference the control from another control.

Add a text box with an expression that calculates subtotals on a subform


1. In the Navigation Pane, right-click the subform that you want to change and click Design View on the shortcut menu.

2.

If you cannot see the form footer section of the form, click the Form Footer bar, and then drag the lower edge of the bar downward.

3.

On the Design tab, in the Controls group, click Text Box.

4.

In the form footer section, drag the pointer on the form to create the text box.

5.

Right-click the text box and then click Properties.

-or-

On the Design tab, in the Tools group, click Property Sheet.

6.

Click the All tab, and then set the property values as shown in the following table.

Property Name ControlSource Format

Setting OrderSubtotal =Sum([Extended Price]) Currency

7.

NOTE

If you are adapting these steps to work with your own data, remember to change the field name

(ExtendedPrice) to match the field name in your own database.

8.

Click the box in the upper left or right corner of the subform the box next to the ruler to display the properties for the entire subform.

9.

Locate the Default View property box and change its value to Datasheet.

10. Save your changes, close the property sheet, and go to the next steps.

Although the text box on the subform calculates the order subtotal, you might not want to display the resulting values in the subform because subforms often appear as datasheets. Adding a subtotal would, at the least, mean that users see the same value many times. For example, you could see this type of result:

Product Product 1 Product 2 Product 3

Quantity 4 5 6

Unit Price $8.00 $9.00 $10.00

Discount 0.00% 0.00% 0.00%

Extended Price $32.00 $45.00 $60.00

Subtotal $137.00 $137.00 $137.00

As you can see, a piece of summary data belongs in a single field, and it often makes sense to put that field on a main form. To do that, you add a control to the main form that references the control on the subform. The following illustration shows how you can do this:

The name of the subform control on the main form

The Form property, which provides access to the subform's controls and properties

The name of the text box control on the subform

The following steps explain how to create a text box that references the values in another control.

Create the control


1. In the Navigation Pane, right-click the main form that you want to change and click Design View on the shortcut menu.

2.

On the Design tab, in the Controls group, click Text Box.

3.

Locate the area on the form to which you want to add the control, and then drag the pointer on the form to create the text box.

4.

Right-click the text box and click Properties.

-or-

On the Design tab, in the Tools group, click Property Sheet.

5.

Click the All tab.

6.

Set the property values as shown in the following table.

Property Name ControlSource Format

Setting Subtotal =[Orders Subform].Form![OrderSubtotal] Currency

7.

NOTE

If you are adapting these steps to work with your own data, remember to change the identifiers

(the form and control names between the square brackets) to match the names in your own database.

8.

Save your changes and then close the property sheet.

Looking up a value in a table


When you design a form, you might want to display a value from a table or query other than the one that your form is bound to. For example, suppose that you have a Products form that is bound to a Products table. After you design the form, however, you decide that you want the form to display the name of the supplier contact for each product data that resides in a table called Suppliers.

Access provides two ways to do that type of task. You can use the Lookup Wizard to create a lookup field (the most common technique), or you can create an expression. A discussion of the Lookup Wizard is beyond the scope of this topic, so for more information, see the article Add or change a field to look up a value in another table.

To create an expression that looks up values in another table, you use the DLookup function. You supply three arguments to the DLookup function:

The name of the field whose value you want to look up

The table or query where the field is located

Optionally, the criteria to use to locate the record

To add the supplier contact, open the Products form in Design view and then add a text box with the label Contact Name. The expression to use for this text box is:

=DLookup("[ContactName]","[Suppliers]","[SupplierID]=" & Forms!Products!SupplierID)

Add the supplier contact text box


1. In the Navigation Pane, right-click the main form that you want to change and click Design View on the shortcut menu.

2.

On the Design tab, in the Controls group, click Text Box.

3.

Locate the area in the form to which you want to add the control, and then drag the pointer on the form to create the text box.

4.

Right-click the text box and click Properties.

-or-

On the Design tab, in the Tools group, click Property Sheet.

5.

Click the All tab.

6.

Set the property values, as shown in the following table.

Property Label ControlSource

Setting Contact Name =DLookup("[ContactName]","[Suppliers]","[SupplierID]=" & Forms!Products!SupplierID)

7.

Save your changes and then close the property sheet.

This expression searches in the Suppliers table and returns the contact name of the supplier whose supplier ID matches the value in the SupplierID control on the Products form. Note how the & operator is used to construct the third argument. A common error that you should avoid is placing quotation marks around the entire argument instead of around only the text before the & operator.

NOTE

As an alternative to using the DLookup function, you can alter the underlying query to include only the

information that you need. Using a query is often more efficient.

Add a printed date to a report


Report users often want to know when a report was printed. That small piece of information can tell them whether or not they have current data. To have Access fill in a date for you, use either the Now function or the Date function. The Now function returns the current date and time, as stored in your computer's clock. The Date function returns only the current date. You can use the Format function to format the result of either of these functions in any one of the available date and time formats.

Add the printed date to a report


1. In the Navigation Pane, right-click the report that you want to change and click Design View on the shortcut menu.

2.

If you cannot see the footer section of the report, click the Report Footer bar, and then drag the lower edge of the bar downward to expand the report.

3.

On the Design tab, in the Controls group, click Text Box.

4.

In the report footer section, drag the pointer to create the text box.

5.

Right-click the text box and click Properties.

-or-

On the Design tab, in the Tools group, click Property Sheet.

6.

Click the All tab, and then set the property values as shown in the following table.

Property Name ControlSource Format

Setting DatePrinted ="Printed " & Date() Medium Date

7.

Save your changes and then close the property sheet.

Printing the page number on a report


When you design a report that fills more than one printed page, you should add page numbers. You can add page numbers by using the Page property, which automatically numbers the pages when you preview or print the report. The Page property is available only when you preview or print a report, so it doesn't appear in the report's property sheet. To use the Page property, you place a text box in the header or footer of the report and then type Page in the ControlSource property of the text box.

This is the same procedure that you follow when using a function such as Now or Date, except that you don't include parentheses after the Page property.

This figure shows how you can add the Page property directly to a text box control:

In addition, you can also construct an expression that uses the Page and Pages properties. The Pages property returns the total number of pages in the report. For example, the following expression produces page numbering in the format Page 1 of 10.

="Page " & [Page] &" of " & [Pages]

The following steps explain how to add an expression that uses both properties to the footer of a report. The steps explain how to add page numbers in Design view, and by using Layout view.

Use Design view to add page numbering


1. In the Navigation Pane, right-click the report that you want to change and click Design View on the shortcut menu.

2.

If you cannot see the footer section of the report, click the Report Footer bar, and then drag the lower edge of the bar downward to expand the report.

3.

On the Design tab, in the Controls group, click Text Box.

4.

In the report footer section, drag the pointer to create the text box.

5.

Right-click the text box and click Properties.

-or-

On the Design tab, in the Tools group, click Property Sheet.

6.

Click the Data tab, and then change the value in the Control Source property box to: ="Page " & [Page] &" of " & [Pages].

7.

Save your changes and then close the property sheet.

Use Layout view to add page numbering


1. In the Navigation Pane, right-click the report that you want to change and click Layout View.

2.

On the Formatting tab, in the Controls group, click Page Numbers.

The Page Numbers dialog box appears.

3.

Under Format, click Page N of M.

4.

Under Position, select an option.

5.

Under Alignment, select an option from the list.

6.

Select or clear the Show Number on First Page check box, and then click OK.

NOTE

The Expression Builder includes some common expressions that you can use for page numbering. For

more information about using the Expression Builder, see the section Using the Expression Builder to create expressions.

Printing a portion of a value on a report


If the first or last few characters in a field have a special meaning, you can organize a report around them. For example, if the first two characters in a product identification code indicate the type of product, you can group the products by the first two characters in the code and then identify each group by printing the characters in a group header.

You use the Left function to extract the first n characters of a value in a Text field and the Right function to extract the last n characters. In both cases, the first argument is the field name or text expression, and the second argument is the number of characters that you want to extract.

The following table shows expressions that employ these functions. The functions assume that the data resides in a table field called PartID.

If the value in Part ID is AA105 AA105

This expression =Left([PartID],2) =Right([PartID],3)

Returns AA 105

For more information about the Left and Right functions, see the articles Left Function and Right Function.

Using letter separators in an alphabetical list


For fast identification in a list of products, you can group the products by the first letter of their names and print the letter in a group header, as shown in the following illustration.

To start a new group each time the first letter of the product name changes, and then sort the products within each group alphabetically, you create two groups in the Group, Sort, and Total pane and then set each group as shown in the following tables.

Group on ProductName

with A on top

by first character

with no totals

with title click to add

with a header section

without a footer section

keep whole group together on one page

Sort on ProductName

with A on top

by entire value

with no totals

with title click to add

with a header section

with a footer section

do not keep whole group together on one page

Display the Group, Sort, and Total pane


1. In the Navigation Pane, right-click the report that you want to change and click Design View on the shortcut menu.

2.

On the Design tab, in the Grouping & Totals group, click Group & Sort.

To print only the first letter of the name at the beginning of a new group, use this expression in the text box in the ProductName header:

=Left([ProductName],1)

Printing the numeric equivalent of a date


You can organize the records in a report by using numeric date values for a period of time a period such as a year, quarter, month, or week. For example, a year is divided into 53 calendar weeks (The first and last weeks of the year are often partial weeks). Using that numeric value, you can group the orders that were shipped by the week of the year.

To find a portion of a numeric date value, such as just the month or year, you use the DatePart function. The function uses the following syntax:

DatePart (interval, date[, firstdayofweek] [, firstweekofyear])

The interval argument is the abbreviation for the part of the date that you want returned. Examples of valid abbreviations are "yyyy" for a four-digit year, "q" for a calendar quarter, and "m" for a month. The date argument is a field name or a literal date, such as "1-Jul-07."

The firstdayofweek and firstweekofyear arguments are optional. The firstdayofweek argument returns Sunday, unless you specify otherwise. To specify a different day, enter a value between 2 and 7 (1 is the default value). The

firstweekofyear returns the week in which January 1 occurs. To specify a different week, enter 2 or 3. Use 2 to specify the first week that has at least four days in the new year; use 3 to specify the first full week of the year.

The following table lists examples of the results that are returned for a field named "Holiday." The Holiday field can store the holidays that are celebrated in the countries or regions where your company does business.

If the value in Holiday is 1-Jan-07 31-Dec-07 31-Dec-07

This expression =DatePart("w",[Holiday]) =DatePart("ww",[Holiday]) =DatePart("yyyy",[Holiday])

Returns 2 (day of week) 53 (week of year) 2007 (four-digit number of year)

For more information, see the article DatePart Function.

To learn more about creating grouped reports, see the article Create a grouped or summary report.

Comparing the results of multiple years


When you want to analyze the sales results from more than one year, it's convenient to group the results by a period of time, such as a quarter or month. That way, you can quickly see how the performance for a time period in one year compares with the same time period in another year. For example, suppose you want to see a Summary of Sales by Quarter report that shows the number of orders that were shipped and the sales totals.

To create the group headers and footers and specify the sort order for this report, you create two groups, each with its own sort order, and you set the properties in the Group, Sort, and Total pane for each group and sort order as shown in the following tables. Note that you use an expression to group by the quarter when the orders were shipped.

Group on expression Use this expression: =DatePart("q",[ShippedDate])

ascending

by entire value

with no totals

with title Quarter

with a header section

with a footer section

keep whole group together on one page

Group on ShippedDate

from oldest to newest without a header section

by year

with no totals

with title click to add

with a footer section

do not keep group together on one page

Display the Group, Sort, and Total pane


1. Open the report in Design view.

2.

On the Design tab, in the Grouping & Totals group, click Group & Sort.

To print the quarter number at the beginning of a new group, you place a text box in the group header by using the same expression that you used in the Sorting and Grouping box:

=DatePart("q", [ShippedDate])

Calculating line item totals


Suppose you want an invoice report that displays information about an order. You need to calculate the extended price (the total sales for each product) for line items. You first create a query that provides the data for the report. You include in that query all of the fields that you need from all of the tables that you need, such as the Orders table, the

Order Details table, and the Customers table. You can then create a calculated field in the query design grid that calculates the extended price for each product on the invoice.

Create a calculated field


1. In the Navigation Pane, right-click the query that you want to change and click Design View on the shortcut menu.

2.

Click the Field row of an empty column in the query design grid.

3.

Type a name, a colon (:), and an expression in the Field cell. The name and colon define a user-friendly name for you calculated field. To calculate an extended price, you can use an expression like this:

ExtendedPrice: CCur([Order Details].Unit Price*[Quantity]*(1-[Discount])/100)*100

Note that when you create a calculated field in the query design grid, do not precede your expression with the = operator.

Identifying orders that were shipped late


Under the best of circumstances, orders are shipped on time. Occasionally, some orders may go out after the required date, and you want to identify these on a report. To mark all orders that were shipped late on a report that tracks shipments, you can print a check mark in a check box that is labeled Shipped Late. Because most orders are shipped on time, the check mark is easier to spot than text that spells out On time or Late.

The expression for this report compares the value in the Shipped Date field to the value in the Required Date field. If the value in the Shipped Date field is greater (that is, a later date) than the value in the Required Date field, the expression returns the value True, and the report shows a check mark in the check box. If the value is False, the report leaves the check box empty.

Add the ShippedLate check box to a report


1. In the Navigation Pane, right-click the report that you want to change and click Design View on the shortcut menu.

2.

On the Design tab, in the Controls group, click Check Box.

3.

Drag the pointer in the detail section of the report to create the check box.

4.

Right-click the check box, click Properties on the shortcut menu, and then click the All tab in the property sheet.

5.

Set the properties for the check box as shown in the following table.

Property Name ControlSource Visible

Setting ShippedLate =[Shipped Date]>[Required Date] Yes

6.

NOTE

If you are adapting these steps to work with your own data, remember to change the field names

in the identifiers to match your own database.

7.

Save your changes and then close the property sheet.

Top of Page

Table of operators
Access supports a variety of operators, including arithmetic operators such as +, -, * (multiply), and / (divide), in addition to comparison operators for comparing values, text operators for concatenating text, logical operators for determining true or false values, and other operators specific to Access. For details about using these operators, see the following tables:

Arithmetic operators

You use the arithmetic operators to calculate a value from two or more numbers or to change the sign of a number from positive to negative.

Operator + -

Purpose Sum two numbers. Find the difference between two numbers or indicate the

Example [Subtotal]+[SalesTax] [Price]-[Discount]

negative value of a number. * / Multiply two numbers. Divide the first number by the second number. Round both numbers to integers, then divide the first number by the second number. Then, truncate the result to an integer. Divide the first number by the second number and return only the remainder. Raise a number to the power of an exponent. [Quantity]*[Price] [Total]/[ItemCount]

[Registered]\[Rooms]

Mod

[Registered] Mod [Rooms]

Number ^ Exponent

Comparison operators

You use the comparison operators to compare values and return a result that is true, false, or null.

Operator <

Purpose Determine if the first value is less than the second value. Determine if the first value is less than or equal to the second value. Determine if the first value is greater than the second value. Determine if the first value is greater than or equal to the second value. Determine if the first value is equal to the second value. Determine if the first value is not equal to the second value.

<=

>

>=

<>

In all cases, if either the first value or the second value is null, the result is then also null. Because null represents an unknown value, the result of any comparison with null is also unknown.

Logical operators

You use the logical operators to combine two values and return a true, false, or null result. You might also see the logical operators referred to as Boolean operators.

Operator And

Usage Expr1 And Expr2

Description True when Expr1 and Expr2 are true. True when either Expr1 or Expr2 is true. True when both Expr1 and Expr2 are true or both Expr1 and Expr2 are false. True when Expr is not true. True when either Expr1 is true, or Expr2 is true, but not both.

Or

Expr1 Or Expr2

Eqv

Expr1 Eqv Expr2

Not Xor

Not Expr Expr1 Xor Expr2

Concatenation operators

You use the concatenation operators to combine two text values into one.

Operator &

Usage string1 & string2

Description Combines two strings to form one string. Combines two strings to form one string and propagates null values.

string1 + string2

Special operators

You use the special operators as described in the following table.

Operator Is Null or Is Not Null

Description Determines whether a value is Null or Not Null. Matches string values by using wildcard operators ? and *. Determines whether a numeric or date value falls within a range. Determines whether a string value is found within a set of string values.

For More Information

Like "pattern"

Like Operator

Between val1 And val2

Between...And Operator

In(string1,string2...)

In Operator

Introduction to filters
A filter changes the data that a form or report displays in a view without altering the design of the form or report. You can think of a filter as a criterion or a rule that you specify for a field. The criterion identifies the field values that you are interested in viewing. When you apply the filter, only records that contain the values that you are interested in are included in the view. The rest are hidden until you remove the filter.

NOTE

Columns or controls that are bound to expressions do not support filtering.

Filters are easy to apply and remove. In Microsoft Office Access 2007, common filters are built into every view that displays data, including Layout view. The availability of filter commands depends on the type and values of the field.

For example, you can view the records of only those people whose birthdays fall during a specific month by clicking the appropriate menu commands.

The filters that are available to you depend on the type of data that is in the selected column.

All Dates in Period filters ignore the day and year portion of the date values.

When a filter is applied, the view is updated to show only the records that match your criteria. In this case, you see only those customer records in which the month portion of the BirthDate field is set to April. All other records are hidden.

Icons in the column header and the record navigator bar indicate that the current view is filtered on the BirthDate column.

Hovering the mouse over the column heading displays a tip showing the current filter criterion.

When you apply a filter to a column that is already filtered, the previous filter is removed before the new filter is applied. For example, if the BirthDate field is already filtered to show birthdays that fall in April, when you apply a filter to see birthdays that fall in February, the result will include only birthdays that fall in February. Access automatically removes the filter that returned only birthdays in April before applying the second filter.

Though only a single filter will be in effect for any one field at any one time, you can specify a different filter for each field that is present in the view. For example, to see the names of those contacts who live in the UK whose birthdays fall in April, you can filter the Contacts table on the CountryRegion field and also on the BirthDate field.

When you filter multiple fields in a single view, the filters are combined by using the AND operator, like this:

CountryRegion = UK AND month of BirthDate = April

You can work with the filtered results in the same way that you work with the initial view for example, you can edit the data, and you can navigate to other records.

You can revert to the unfiltered view by removing the filters. Removing a filter temporarily removes it from the view, so that you can switch back to the original, unfiltered view. In the Sort & Filter group on the Home tab, you can click Toggle filter to switch between filtered and unfiltered views.

You can also permanently remove a filter from a view by clearing the filter. To learn how to clear filters, see the section Clear or save a filter.

Filter settings will be in effect until you close the object, even if you switch to another view of the object. In other words, if you filter a form in Datasheet view, the filter settings will still be in effect if you switch to Form view or Layout view, and will remain in effect until you close the form. If you save the object while the filter is applied, it will be available the next time that you open the object.

Whether the filter settings will be in effect when you open the object the next time depends on the FilterOnLoad property setting for the object. If you set the FilterOnLoad property of a table, query, form, or report to Yes, the filter settings that were last applied will be applied when you reopen the object.

NOTE

The FilterOnLoad property setting is only applied when the object loads. Setting this property for an object in

Design view and then switching to another view will not cause the setting to be applied. You must close and reopen the object for changes to the FilterOnLoad property setting to take effect.

Top of Page

Types of filters

Common filters Filter based on selection Filter by form Advanced filters

Office Access 2007 offers several ready-to-use filters for each data type. These filters are available as menu commands in the following views: Datasheet, Form, Report, and Layout. In addition to these filters, you can also filter a form or datasheet by completing a form (called Filter by Form).

If you want more flexibility, and if you are comfortable writing expressions, you can create your own filters by using the options on the Filter document tab.

Following is a little more information about each type of filter that is available to you in Access.

Common filters
Several popular filters are available as context menu commands, so that you don't have to spend time constructing the correct filter criteria. To access these commands, right-click the field you want to filter.

NOTE

If you select two or more columns or controls, the filter options will not be available. If you want to filter the

view on multiple columns or controls, you must either select and filter each column or control separately, or use an advanced filter option. See the Filter by form and Advanced filters sections in this article for more information.

Except for OLE Object fields and fields that display calculated values, all field types offer common filters. The list of filters that are available depends on the selected field's data type and values.

For example, to see the filters available for the BirthDate field:

On the Home tab, in the Sort & Filter group, click Filter.

Common date filters

To filter for specific values, use the check box list. The list displays all the values that are currently displayed in the field.

To filter for a range of values, click one of these filters, and specify the required values.

For example, to see birthdays that fall between the current date and the end of the year, click Between, and then specify the appropriate start and end dates in the Between dialog box.

To see all birthdays that fall on a specific date, use the value list. In an unfiltered view, the value list for each field presents all of the unique values that are stored in that field.

NOTE

When a view is filtered, the value list for each field shows only the unique values that are visible in the view.

For example, if the CountryRegion field is filtered to show only records that have the value USA, the value list of the Full Name field will show only the names of those who live in the USA. To see more values in the value list, remove some or all filters from the view.

It is important to note that the values in a date field have an impact on the list of type-specific filters. If the most recent date value in a date field falls within the past two years, you see a longer, more detailed filter list. If none of the dates in a field is less than two years old, you see the shorter filter list.

Long and short common date filter lists

NOTE

Type-specific filters are not available for Yes/No, OLE object, and attachments fields. The values list is not

available for memo fields, or for fields that contain rich text.

Filter based on selection


If the value that you want to use as the basis for filtering is currently selected, you can quickly filter the view by clicking one of the Selection commands. The commands that are available will vary, depending on the data type of the selected value. These commands are also available on the context menu of the field, accessed by right-clicking the field.

For example, if the value 2/21/1967 is currently selected in the BirthDate field, on the Home tab, in the Sort & Filter group, click Selection to display the filter by selection commands.

The command list automatically includes the current value, so that you don't have to type it.

The list of commands also depends on how much of the value is selected. For example, if you select only some of the characters in the value, you see a different list of commands, depending on which part of the field you selected.

Filter using the beginning of a field value...

...the middle of a field value...

...or the end of a field value.

NOTE

Filtering on a partial selection is not available for multivalued fields.

The Selection command is not available for attachments.

Filter by form
This technique is useful when you want to filter on several fields in a form or datasheet, or if you are trying to find a specific record. Access creates a blank form or datasheet that is similar to the original form or datasheet, and then

allows you to complete as many of the fields as you want to. When you are done, Access finds the records that contain the specified values.

NOTE

You cannot specify field values for multivalued fields using filter by form, nor for fields with Memo, Hyperlink,

Yes/No, or OLE Object data type, although you can specify values for other fields in the recordset.

For example, if you want to find all Customer records where the contact person's title is Owner, and that person is located either in Portland or in Eugene, open the Customers form and, on the Home tab, in the Sort & Filter group, click Advanced Filter/Sort, and then click Filter by Form.

Enter the first set of values, then click the Or tab, and then enter the next set of values. Note that if you want a field value to operate as a filter independently of other field values, you must enter that value on the Look for tab and each Or tab. Each Or tab represents an alternate set of filter values.

To toggle the filter:

On the Home tab, in the Sort & Filter group, click Toggle Filter.

Access shows only those records that match your input.

Advanced filters
On occasion, you might want to apply a filter that is not in the common filters list. For example, if you want to find records that contain dates that occur during the past seven days or the past six months, you might have to write the filter criterion yourself.

Using this feature requires that you are familiar with writing expressions. Expressions are similar to formulas that you write in Excel, and to the criteria that you specify when designing a query.

For example, if you want to find the names of those contacts whose birthdays occurred during the past seven days, you can use an advanced filter.

On the Home tab, in the Sort & Filter group, click Advanced and then click Advanced Filter/Sort on the shortcut menu.

You add the filter fields to the design grid, and specify the filter criteria in the Criteria row.

When you click Toggle Filter in the Sort & Filter group on the Home tab, Access displays the filtered records.

Continuing with the same example, if you want to further limit the results to those whose country/region is USA, switch back to the Filter object tab, add the CountryRegion field to the grid, and then specify a criterion.

Top of Page

Apply a filter

Apply a common filter Apply a filter based on selection Apply a filter by filling out a form Apply an advanced filter

NOTE

If you do not see the filter commands in any of the views, the designer of the form or database might have

disabled filtering. Contact the designer for further assistance.

Apply a common filter


1. Open a table, query, form, or report in any of the following views: Datasheet, Form, Report, or Layout.

2.

Make sure that the view is not already filtered. On the record selector bar, verify that either the Unfiltered or the dimmed No Filter icon is present.

TIP

To remove all the filters for a particular object, on the Home tab, in the Sort & Filter group, click

Advanced, and then click Clear All Filters.

3.

Click anywhere in the column or control that corresponds to the first field that you want to filter.

4.

On the Home tab, in the Sort & Filter group, click Filter.

5.

Do one of the following:

To apply a common filter, point to Text (or Number or Date) Filters, and then click the filter that you want. Filters such as Equals and Between prompt you to enter the necessary values.

TIP

Certain characters, such as *, %, and ?, have a special meaning when specified in a filter text

box. For example, * represents a string of characters, so the string a* will match any string that begins with a, and not only the literal string a*. To disregard the special meaning of a character, enclose it in square brackets [], like this: a[*]. Databases that use the ANSI-89 standard treat *, ?, [, ], !, -, and # as special characters. Databases that use the ANSI-92 standard treat %, _, [, ], ^, and - as special characters. You can use either standard with Access, but you cannot mix the two standards (e.g., ?a*) in a particular expression.

To apply a filter based on field values, clear the check boxes next to the values on which you do not want to filter, and then click OK.

Hint If you have a large list of values, and if you want to filter on one or only a few of those values, first clear the (Select All) check box and then select the values you want.

To filter for null values (a null value indicates the absence of data) in text, number, and date fields, in the check box list, clear the (Select All) check box, and then select the check box next to (Blanks).

6.

Repeat the previous three steps for each field that you want to filter.

Apply a filter based on a selection


1. Open a table, query, form, or report in any of the following views: Datasheet, Form, Report, or Layout.

2.

Make sure that the view is not already filtered. On the record selector bar, verify that either the Unfiltered or the dimmed No Filter icon is present.

3.

Move to the record that contains the value that you want to use as part of the filter, and then click inside the column (in Datasheet view) or control (in Form, Report, or Layout view). To filter based a partial selection, select the characters that you want.

4.

On the Home tab, in the Sort & Filter group, click Selection, and then click the filter you want to apply.

5.

To filter other fields based on a selection, repeat the preceding two steps.

Apply a filter by filling out a form


1. Open a table or query in Datasheet view, or a form in Form view.

2.

Make sure the view is not already filtered. On the record selector bar, verify that either the Unfiltered or the dimmed No Filter icon is present.

3.

On the Home tab, in the Sort & Filter group, click Advanced, and then click Filter by Form on the shortcut menu.

4.

Depending on whether you are working in Datasheet view or in Form view, do one of the following:

In Datasheet view, click the first row in the column on which you want to filter. Click the arrow that appears, and select a value. You can add additional values by clicking the Or tab at the bottom of the datasheet and selecting another value.

In Form view, click the arrow that appears in the control, and select a value on which to filter. You can add additional values by clicking the Or tab at the bottom of the form and selecting another value. Click the Or tab to add even more values.

NOTE

You cannot specify field values for multivalued fields using filter by form, although you can specify

values for any non-multivalued field in the recordset.

If you do not see a list of field values when you click the drop-down arrow for a field

Verify that the data type for the field is not Memo, Hyperlink, Yes/No, or OLE Object. Fields of these data types cannot be made to display field values on the Filter By Form object tab. Multivalued fields similarly cannot display values on the Filter By Form object tab.

If the number of records read is more than the number specified in the Default max records box in the Filter lookup options for Database section in the Access Options dialog box, Access doesn't display values for that field on the list. To open the Access Options dialog box, click the Microsoft Office Button , and then click Access Options. Click Editing, then change the Default max

records setting to work around this problem.

In the Access Options dialog box, click Editing. In the Filter lookup options for Database section, select the Local indexed fields and Local nonindexed fields check boxes.

Switch back to Datasheet view or Form view.

To specify a list of possible values for a field, use the or operator. For example, you can specify "Portland" or "Oregon" in the City field to filter for records containing either value.

To filter based on the status of a control, such as a check box or button, click the control so that it is in the state that you want. To return the control to a neutral position, so that it won't be used as a criterion for filtering records, ensure that it is unavailable (appears dimmed).

To filter for records that have null (missing), non-null, blank (empty or ""), or nonblank values, type Is Null, Is Not Null, "", or Not "" in the field.

5.

Sometimes, you might want to specify two alternate sets of criteria. For example, you might want to see the names of only those contacts whose CountryRegion value is USA and whose birthdays fall in April, or the names of only those contacts whose CountryRegion value is Asia and whose birthdays fall in May.

To retrieve all records that meet any one of multiple sets of criteria, you need to specify the criteria somewhat differently.

Enter the first set of criteria, then click the Or tab, and then enter the next set of criteria. Note that if you want a field value to operate as a filter independently of other field values, you must enter that value on the Look for tab and each Or tab. In other words, the Look for tab and each Or tab represents an alternate set of filter values.

Note that each time you add a field criterion to the Or tab, Access creates another Or tab. This enables you to specify several "or" criteria. The filter returns any record that contains all of the values specified on the Look for tab, or all of the values specified on the first Or tab, or all of the values specified on the second Or tab, and so on.

6.

To remove the filter and show all records, click Toggle Filter again.

7.

To modify the filter, click Filter By Form again.

The current filter criteria set is displayed.

Apply an advanced filter


1. Open a table, query, form, or report in any of the following views: Datasheet, Form, Report, or Layout.

2.

Make sure that the view is not already filtered. On the record navigator bar, verify that No Filter appears dimmed (is unavailable). If the record navigator bar is not visible, click Advanced in the Sort & Filter group on the Home tab, and then click Clear All Filters (if Clear All Filters appears dimmed, there are no filters in effect).

3.

On the Home tab, in the Sort & Filter group, click Advanced and then click Advanced Filter/Sort on the shortcut menu.

4.

Add the fields on which you want to filter to the grid.

5.

In the Criteria row of each field, specify a criterion. The criteria are applied as a set, and only records that match all of the criteria in the Criteria row are displayed. To specify alternate criteria for a single field, type the first criterion in the Criteria row and the second criterion in the Or row, and so on.

NOTE

The entire set of criteria in the Or row is applied as an alternative to the set of criteria in the

Criteria row. Any criterion that you want to be applied for both sets of criteria must be typed in both the Criteria row and the Or row.

6.

Click Toggle Filter to see the filtered rows.

TIP

A good way to learn to write criteria is to apply a common filter or a filter based on selection that produces a

result that is close to what you are looking for. Then, with the filter applied to the view, display the Filter object tab:

On the Home tab, in the Sort & Filter group, click Advanced and then click Advanced Filter/Sort on the shortcut menu.

Review the result, and then revise the criteria displayed in the Criteria row to produce the desired result.

NOTE

Two special commands are available to you on the Filter document tab. When you right-click anywhere

above the design grid on the tab, the Load from Query and Save As Query commands are available on the shortcut menu.

The Load from Query command loads the design of a selected query into the grid. This lets you use the query critieria as filter criteria. The Save As Query command lets you save the filter settings as a new query.

Top of Page

Remove or reapply a filter


If you want to switch to the unfiltered view of data, remove the filters.

Click Filtered on the record navigator bar to revert to the full view.

When you remove the current filters, the filters are temporarily removed from all of the fields in the view. For example, if you first apply filters on the CountryRegion and BirthDate fields, and then remove the filters, you see all of the records again.

Click Unfiltered on the record navigator bar to reapply the most recent filters.

The most recent filter settings are reapplied to the view. To continue the previous example, the previously applied filters on the CountryRegion and BirthDate fields are reapplied.

Top of Page

Clear or save a filter


Clear a filter when you no longer need it. Clearing a filter deletes it from the view, and you can no longer reapply it by clicking Unfiltered on the status bar.

You can clear a single filter from a single field, or clear all filters from all fields in the view.

To clear a single filter from a single field, right-click the filtered column or control, and then click Clear filter from field name.

To clear all filters from all fields:

On the Home tab, in the Sort & Filter group, click Advanced, and then click Clear All Filters on the shortcut menu.

It is easy to save filters for future use. The filter settings that are in effect at the time when you close a table, query, form, or report are automatically saved along with the object, and they are available to you for reapplying. However, by default, the filter settings are not automatically applied for you when you next open the object.

To ensure that the current filters are automatically applied when you next open a table, query, form, or report, set the object's FilterOnLoad property to Yes. You set this property in the object's property sheet. The FilterOnLoad property is applied when you open the object; when you change this setting, you must close the object and reopen it in order to apply the new setting.

Introduction
A select query is a type of database object that shows information in Datasheet view (Datasheet view: A window that displays data from a table, form, query, view, or stored procedure in a row-and-column format. In Datasheet view, you can edit fields, add and delete data, and search for data.). A query can get its data from one or more tables, from existing queries, or from a combination of the two. The tables or queries from which a query gets its data are referred to as its recordsource.

Whether you create simple select queries by using a wizard or by working in Design view, the steps are essentially the same. You choose the recordsource that you want to use and the fields that you want to include in the query and, optionally, you specify criteria to refine the results.

After you have created a select query, you run it to see the results. Running a select query is simple you just open it in Datasheet view. You can then reuse it whenever you need, for example, as a recordsource for a form, report, or another query.

NOTE

For more information about using a query as a recordsource for a form or report, see the article Use a query

as a recordsource for a form or report.

There are several types of query, each serving a different purpose. For example, a select query displays data. An action query changes the data in its datasource, or creates a new table. A parameter query prompts you to supply criteria when you run it. This topic only covers select queries.

NOTE

This topic describes how to create select queries that return data from a single table. If you want to create

queries that return data from two or more tables, see the article Create a query based on multiple tables.

Top of Page

Create a query
In this exercise, you will create the London Contacts select query. You can create this query either in Design view or by using a wizard. In addition, if you are familiar with writing SQL statements (SQL string/statement: An expression that defines an SQL command, such as SELECT, UPDATE, or DELETE, and includes clauses such as WHERE and ORDER BY. SQL strings/statements are typically used in queries and in aggregate functions.), you can create a query while working in SQL view by writing a simple SELECT statement.

Before you begin, you need to have a table that contains data. Sample data is provided below in HTML table form.
Custom erID 1 Addre ss 1 Main St. StateOrPro vince NY PostalC ode 12345 CountryOrR egion USA Pho ne (202 ) 555012 2 (201 ) 555012 3 (206 ) 555004 2 (171 ) 555012 5 (171 ) 555016 5 (206 ) 555000 7 (171 ) 555017 8 (503 ) 555008 6 Cont act Steve Riley BirthD ate 03Dec-45

Company Baldwin Museum of Science

City New York

Blue Yonder Airways

52 1st St.

Bosto n

MA

01234

USA

Walee d Heloo

21Mar-59

Coho Winery

3122 75th Ave. S.W.

Seattl e

WA

98100

USA

Guido Pica

01-Apr73

Contoso Pharmaceu ticals

1 Contos o Blvd.

Lond on

NS1 EW2

UK

Zolta n Harm uth

16-Jun67

Fourth Coffee

Lond on

W1J 8QB

UK

Julian Price

09Aug-71

Consolidate d Messenger

3123 75th St. S

Seattl e

WA

98100

USA

Christ ine Hugh es

27May-48

Graphic Design Institute

151 Strand

Lond on

WC2R 0ZA

UK

Dana Birkb y

12Aug-61

Litware, Inc.

3 Macrof irm Parkw ay 22 Wicklo w Street 37 Lothbu ry

Portla nd

OR

97200

USA

Jespe r Aaber g

01Sep-75

Tailspin Toys

Lond on

WC1 0AC

UK

Phil Gibbi ns

15-Feb53

10

Woodgrove Bank

Lond on

EC2R 7ED

UK

(171 ) 555010 1

Tom Perha m

25Sep-38

You can either enter the data in this sample table manually, or you can copy this table to a spreadsheet program, such as Microsoft Office Excel 2007, and then import the resulting worksheet into a table in Microsoft Office Access 2007.

Enter the sample data manually

1.

On the Create tab, in the Tables group, click Table.

Office Access 2007 adds a new, blank table to your database.

NOTE

You do not need to follow this step if you open a new, blank database, but you will need to follow it

whenever you need to add a table to the database.

2.

Double-click the first cell in the header row and type the name of the field in the sample table.

By default, Access denotes blank fields in the header row with the text Add New Field, like so:

3.

Use the arrow keys to move to the next blank header cell and then type the second field name (you can also press TAB or double-click the new cell). Repeat this step until you enter all field names.

4.

Enter the data in the sample table.

As you enter the data, Access infers a data type for each field. Each field in a table has a specific data type, such as Number, Text, or Date/Time. Data types help ensure accurate data entry and help to prevent mistakes, such as using a telephone number in a calculation. You can specify the data type for each field in a table, and can change a field's data type under certain circumstances. For this sample table, you should let Access infer the data type.

5.

When you finish entering the data, click Save

Keyboard shortcut Press CTRL+S.

The Save As dialog box appears.

6.

In the Table Name box, enter Customers, and then click OK.

Copy the table to a spreadsheet program and then import it into Access

1.

Start your spreadsheet program and create a new, blank file. If you use Excel, a new, blank workbook is created by default.

2.

Copy the sample table provided in the previous section and paste it into the first cell of the first worksheet.

3.

Using the technique provided by your spreadsheet program, name the worksheet Customers.

4.

Save the spreadsheet file to a convenient location and go to the next steps.

1.

In a new or existing database:

On the External Data tab, in the Import group, click Excel.

-or-

Click More, and then select a spreadsheet program from the list.

The Get External Data - Program Name Spreadsheet dialog box appears.

2.

Click Browse, open the spreadsheet file that you created in the previous steps, and then click OK.

The Import Spreadsheet Wizard starts.

3.

By default, the wizard selects the first worksheet in the workbook (Customers, if you followed the steps in the previous section), and data from the worksheet appears in the lower section of the wizard page. Click Next.

4.

On the next page of the wizard, select First row contains column headings, and then click Next.

5.

The next page of the wizard offers you an opportunity to change field names and data types or to omit fields from the import operation, by using the text boxes and lists under Field Options. You should not do this for this example. Click Next.

6.

On the next page of the wizard, in the Field Options box, select Yes (No Duplicates) from the Indexed list, and select Long Integer from the Data Type list. Click Next to continue.

7.

On the next page of the wizard, select the Choose my own primary key option, choose CustomerID from the list, and then click Next.

8.

By default, Access applies the name of the worksheet to your new table. Make sure that the table is named Customers, and then click Finish.

9.

On the last page of the wizard, you have the option of saving the import steps for later reuse. Because you are importing a sample table, it is not recommended that you save the import steps.

Build the query


First, you will use a wizard to create the query, based on the sample table that you just created. Then, you will enhance the query in Design view. At each step, you can review the SQL statement that is automatically generated by the steps that you take.

1.

On the Create tab, in the Other group, click Query Wizard.

2.

In the New Query dialog box, click Simple Query Wizard, and then click OK.

3.

Under Tables/Queries, click the table that has the data that you want to use. In this case, click Table: Customers. Note that a query can also use another query as a recordsource.

4.

Under Available Fields, double-click the Contact, Address, Phone, and City fields. This adds them to the Selected Fields list. When you have added all four fields, click Next.

5.

Name the query London Contacts, and then click Finish.

Access displays all of the contact records in Datasheet view. The results show all of the records, but show only the four fields that you specified in the query wizard.

Review the initial SQL statement

6.

Close the query, and note that your query is automatically saved.

Top of Page

Add criteria to the query

To restrict the records that are returned in the query results, you can specify one or more criteria.

You can think of a query criterion as a condition that you specify for a field. The criterion specifies a condition, based on field values, that expresses what you want to include in the query, such as "show only those records where the value of City is London".

Open the query in Design view. You will add a criterion to the City field so that you see only those contacts who are from London in the query results. You will also add criteria to the Address field and the Phone field, to further refine your query results.

1.

In the Criteria row of the City field, type london.

Now, add two more criteria to make the results even more meaningful. Suppose that you only want to see the records in which both the address and the phone number are present.

2.

In the Criteria row of the Address field, type Is Not Null AND <>"". Do the same in the Criteria row of the Phone field.

NOTE

The criterion, Is Not Null AND <>"", is true whenever there is any known, non-empty value for the

field for which it is a criterion. It is false whenever there is no known value (Null), or when the value is known to be empty (""). You can use this expression to check a field for a known, non-empty value.

3.

Switch to Datasheet view to see the results.

Review the SQL statement with criteria

What if you don't want the conditions to get combined by using the AND operator? In other words, how do you specify two or more criteria but include the records that satisfy one or both of them?

Specify alternate criteria sets by using OR


Suppose you want to see all the records where City equals London and where at least one kind of contact information either the address or the phone number is available. You want to combine the criteria by using the OR operator, like this:

To specify alternate criteria, use both the Criteria and Or rows in the design grid. All records that meet the criteria defined either in the Criteria row or in the Or row are included in the result.

Now you will modify the query by entering alternate criteria in the Criteria and Or rows.

1.

Switch back to Design view.

2.

Remove the Is Not Null AND <>"" string from the Criteria row of the Phone field.

3.

In the Or row of the Phone field, type Is Not Null AND <>"".

4.

In the Or row of the City field, type london.

5.

Switch to Datasheet view to see the results. All records that include either an address, a phone number, or both, and where City is London, are displayed in the query results.

NOTE

To specify more than two alternate criteria sets, use the rows below the Or row. Each row

represents an independent set of criteria.

Review the SQL statement with revised criteria

To learn more about how to specify criteria for various types of fields, see Examples of query criteria.

Top of Page

Add calculations to the query


A well designed database does not store simple calculated values in tables. For example, a table might store a person's date of birth but not their current age. If you know both today's date and the person's date of birth, you can always calculate their current age, so there is no need to store that in the table. Instead, you create a query that calculates and displays the pertinent value. The calculations are made every time you run the query, so if the underlying data changes, so do your calculated results.

In this exercise, you will modify the London Contacts query so that it displays each contact's date of birth and current age.

1.

Open the query in Design view.

2.

From the Customers table window, drag the BirthDate field to the first blank column in the design grid. You can also double-click the field name to automatically add it in the first blank column.

3.

In the next column, in the Field row, type the expression that will calculate the age for each record. Type Age: DateDiff ("yyyy", [BirthDate], Date()).

Age is the name you are using for the calculated field. If you do not supply a name, Access will use a generic name for the field, for example, EXPR1. The string following the colon (:) is the expression that supplies the values for each record. The DateDiff function calculates the difference between any two dates, and returns that difference in the specified format. The format, yyyy, returns the difference in years, and the [BirthDate] and Date() elements of the expression supply the two date values. Date is a function that returns the current date, and [BirthDate] refers to the BirthDate field in the underlying table.

NOTE

The calculation used for Age in this example is an approximation that may be slightly inaccurate,

depending on the current month.

Switch to Datasheet view. You see two additional fields, BirthDate and Age, in the result.

Review the SQL statement with calculations

For more information about how to write expressions that calculate values in a query, see the article Create an expression.

Top of Page

Summarize query values


Summarizing the columns in a query is easier in Office Access 2007, compared to the same task in earlier versions of Access. You can add, count, or calculate other aggregate values, and display them in a special row (called the Total row) that appears below the asterisk (*) row in Datasheet view.

You can use a different aggregate function for each column. You can also choose not to summarize a column.

In this exercise, you will modify the London Contacts query so that it displays the Total row.

1.

Open the query in Datasheet view.

2.

On the Home tab, in the Records group, click Totals.

3.

Click the Total row in the Contact column.

In the drop-down list, you can choose between None and Count. Because the Contact column displays text values, other functions, such as Sum and Average, are not relevant, and are therefore not available.

4.

Select Count to count the number of contacts that are displayed in the result.

The number 5 is displayed in the Total row.

5.

In the Age field, select Average. Because the Age field evaluates to a number, it supports the Sum,Average, Count, Maximum, Minimum, Standard Deviation and Variance functions.

Access displays the average age in the Total row.

To clear the total for a column, click in the Total row under that column, then select None from the drop-down list. To hide the Total row, on the Home tab, in the Data Type & Formatting group, click Totals.

Understand ways to count data


You can count the number of items in a field (a column of values) by using the Count function. The Count function belongs to a set of functions called aggregate functions. You use aggregate functions to perform a calculation on a column of data and return a single value. Access provides a number of aggregate functions in addition to Count, such as:

Sum, for summing a column of numbers.

Average, for averaging a column of numbers.

Maximum, for finding the highest value in a field.

Minimum, for finding the lowest value in a field.

Standard Deviation , for measuring how widely values are dispersed from an average value (a mean).

Variance, for measuring the statistical variance of all values in the column.

Office Access 2007 provides two ways to add Count and other aggregate functions to a query. You can:

Open your query in Datasheet view and add a Total row. The Total Row, a new feature in Office Access 2007, allows you to use an aggregate function in one or more columns of a query result set without having to change the design of your query.

Create a totals query. A totals query calculates subtotals across groups of records. For example, if you want to subtotal all sales by city or by quarter, you use a totals query to group your records by the category you want and then sum the sales figures. In contrast, a Total row calculates grand totals for one or more columns (fields) of data.

NOTE

The how-to sections in this document emphasize using the Count function, but remember that you can use

other aggregate functions in your Total rows and queries. For more information about using the other aggregate functions, see Aggregate function reference later in this article.

For more information about ways to use the other aggregate functions, see the article Display column totals in a datasheet.

The steps in the following sections explain how to add a Total row and how to use a totals query to count data. As you proceed, remember that the Count function works on a larger number of data types than do the other aggregate functions. For example, you can run a Count function against any type of field except one containing complex, repeating scalar data, such as a field of multivalued lists.

In contrast, many of the aggregate functions work only on data in fields set to a specific data type. For example, the Sum function works only with fields set to the Number, Decimal, or Currency data types. For more information about the data types that each function requires, see Aggregate function reference, later in this article.

For general information about data types, see the article Modify or change the data type set for a field.

Top of Page

Count data by using a Total row


You add a Total row to a query by opening your query in Datasheet view, adding the row, and then selecting the Count function or another aggregate function, such as Sum, Minimum, Maximum, or Average. The steps in this section explain how to create a basic select query and add a Total row.

Create a basic select query


1. On the Create tab, in the Other group, click Query Design.

2.

In the Show Table dialog box, double-click the table or tables that you want to use in your query, and then click Close.

The selected table or tables appear as windows in the upper section of the query designer. This figure shows a typical table in the query designer:

3.

Double-click the table fields that you want to use in your query.

You can include fields that contain descriptive data, such as names and descriptions, but you must include the field that contains the values that you want to count.

Each field appears in a column in the query design grid.

4.

On the Design tab, in the Results group, click Run.

The results of the query are displayed in Datasheet view.

5.

Optionally, go back to Design view and adjust your query. To do so, right-click the document tab for the query and click Design View. You can then adjust the query as needed by adding or removing table fields. To remove a field, select the column in the design grid and press DELETE.

6.

Optionally, save your query.

Add a Total row


1. Open your query in Datasheet view. To do so for a database in the Access 2007 format, right-click the document tab for the query and click Datasheet View.

-or-

For a database created with an older version of Access, on the Home tab, in the Views group, click the arrow below View and click Datasheet View.

-or-

In the Navigation Pane, double-click the query. Doing this runs the query and loads the results into a datasheet.

2.

On the Home tab, in the Records group, click Totals.

A new Total row appears below the last row of data in your datasheet.

3.

In the Total row, click the field that you want to sum, and then select Count from the list.

Hide a Total row


On the Home tab, in the Records group, click Totals.

For more information about using a Total row, see the article Display column totals in a datasheet.

Top of Page

Count data by using a totals query


You count data by using a totals query instead of a Total row when you need to count some or all of the records returned by a query. For example, you can count the number of sales transactions, or the number of transactions in a single city.

Typically, you use a totals query instead of a Total row when you need to use the resulting value in another part of your database, such as a report.

Count all the records in a query

1.

On the Create tab, in the Other group, click Query Design.

2.

In the Show Table dialog box, double-click the table that you want to use in your query, and then click Close.

The table appears in a window in the upper section of the query designer.

3.

Double-click the fields that you want to use in the query, and make sure you include the field that you want to count. You can count fields of most data types, the exception being fields that contain complex, repeating scalar data, such as a field of multivalued lists.

4.

On the Design tab, in the Show/Hide group, click Totals.

The Total row appears in the design grid and Group By appears in the row for each field in the query.

5.

In the Total row, click the field that you want to count and select Count from the resulting list.

6.

On the Design tab, in the Results group, click Run.

The results of the query are displayed in Datasheet view.

7.

Optionally, save the query.

Count records in a group or category


1. On the Create tab, in the Other group, click Query Design.

2.

In the Show Table dialog box, double-click the table or tables that you want to use in your query, and then click Close.

The table or tables appear in a window in the upper section of the query designer.

3.

Double-click the field that contains your category data, and also the field that contains the values that you want to count. Your query cannot contain other descriptive fields.

4.

On the Design tab, in the Show/Hide group, click Totals.

The Total row appears in the design grid and Group By appears in the row for each field in the query.

5.

In the Total row, click the field that you want to count and select Count from the resulting list.

6.

On the Design tab, in the Results group, click Run.

The results of the query are displayed in Datasheet view.

7.

Optionally, save the query.

Top of Page

Aggregate function reference


The following table lists and describes the aggregate functions that Access provides for use in the Total row and in queries. Remember that Access provides more aggregate functions for queries than it does for the Total row. Also, if you work with an Access project (an Access front end connected to a Microsoft SQL Server database), you can use the larger set of aggregate functions that SQL Server provides. For more information about that set of functions, see Microsoft SQL Server Books Online.
Function Sum Description Adds the items in a column. Works only on numeric and currency data. Calculates the average value for a column. The column must contain numeric, currency, or date/time data. The function ignores null values. Counts the number of items in a column. Use with the data type(s) Number, Decimal, Currency

Average

Number, Decimal, Currency, Date/Time

Count

All data types except those containing complex repeating scalar data, such as a column of multivalued lists. For more information about multivalued lists, see the articles Guide to multivalued fields and Add or change a lookup field that lets you store multiple

values.

Maximum

Returns the item with the highest value. For text data, the highest value is the last alphabetic value and Access ignores case. The function ignores null values. Returns the item with the lowest value. For text data, the lowest value is the first alphabetic value and Access ignores case. The function ignores null values. Measures how widely the values are dispersed from an average value (a mean). For more information about using this function, see the article Display column totals in a datasheet.

Number, Decimal, Currency, Date/Time

Minimum

Number, Decimal, Currency, Date/Time

Standard Deviation

Number, Decimal, Currency

Variance

Measures the statistical variance of all values in the column. You can use this function only on numeric and currency data. If the table contains less than two rows, Access returns a null value. For more information about variance functions, see the article Display column totals in a datasheet.

Number, Decimal, Currency

Run a select or a crosstab query


You use select queries (select query: A query that asks a question about the data stored in your tables and returns a result set in the form of a datasheet, without changing the data.) and crosstab queries (crosstab query: A query that calculates a sum, average, count, or other type of total on records, and then groups the result by two types of information: one down the left side of the datasheet and the other across the top.) to retrieve and present data, and to supply forms and reports with data. When you run a select or a crosstab query, Microsoft Office Access 2007 displays the results in Datasheet view (Datasheet view: A window that displays data from a table, form, query, view, or stored procedure in a row-and-column format. In Datasheet view, you can edit fields, add and delete data, and search for data.).

Run the query


1. Locate the query in the Navigation Pane.

2.

Do one of the following:

Double-click the query you want to run.

Click the query you want to run, and then press ENTER.

If the query you want to run is currently open in Design view (Design view: A window that shows the design of these database objects: tables, queries, forms, reports, macros, and data access pages. In Design view, you can create new database objects and modify the design of existing ones.), you can also run it by clicking Run in the Results group on the Design tab of the ribbon.

Top of Page

Run an action query


There are four types of action queries: append queries (append query: An action query that adds the records in a query's result set to the end of an existing table.), delete queries (delete query: A query (SQL statement) that removes rows matching the criteria that you specify from one or more tables.), update queries (update query: An action query (SQL statement) that changes a set of records according to criteria (search conditions) that you

specify.), and make-table queries (make-table query: A query (SQL statement) that creates a new table and then creates records (rows) in it by copying records from an existing table.). Except for make-table queries (which create new tables), action queries make changes to the data in tables they are based on. These changes cannot be easily undone, for example, by pressing CTRL+Z. If you make changes using an action query that you later decide you didn't want to make, usually you will have to restore the data from a backup copy. For this reason, you should always make sure you have a fresh backup of the underlying data before running an action query.

You can mitigate the risk of running an action query by first previewing the data that will be acted upon. There are two ways to do this:

View the action query in Datasheet view before you run it. To do this, open the query in Design view, click View on the Access status bar (status bar: A horizontal bar at the bottom of the screen that displays information about the current condition of the program, such as the status of items in the window, the progress of the current task, or information about the selected item.), and then click Datasheet View on the shortcut menu. To switch back to Design view, click View again, and then click Design View on the shortcut menu.

Change the query to a select query, and then run it.

NOTE

Make sure to note what type of action query (append, update, make-table, or delete) you are

starting with, so you can change the query back to that type after you preview the data with this method.

Run an action query as a select query


1. Open the action query in Design view.

2.

On the Design tab, in the Query Type group, click Select.

3.

On the Design tab, in the Results group, click Run.

Run the query


When you are ready to run an action query, double-click it in the Navigation Pane, or click it and then press ENTER.

Top of Page

Run a parameter query


A parameter query (parameter query: A query in which a user interactively specifies one or more criteria values. A parameter query is not a separate kind of query; rather, it extends the flexibility of a query.) prompts you for a value when you run it. When you supply the value, the parameter query applies it as a field criterion. Which field it applies the criterion to is specified in the query design. If you do not supply a value when prompted, the parameter query interprets your input as an empty string.

A parameter query is always also another type of query. Most parameter queries are select queries or crosstab queries, but append, make-table, and update queries can also be parameter queries.

You run a parameter query according to its other query type, but, in general, use the following procedure.

Run the query


1. Locate the query in the Navigation Pane.

2.

Do one of the following:

Double-click the query you want to run.


3.

Click the query you want to run, then press ENTER.

When the parameter prompt appears, enter a value to apply as a criterion.

Top of Page

Run a SQL-specific query


There are three main types of SQL-specific query (SQL-specific query: A query that consists of an SQL statement. Subqueries and pass-through, union, and data-definition queries are SQL-specific queries.): union queries (union query: A query that uses the UNION operator to combine the results of two or more select queries.), pass-through queries (pass-through query: An SQL-specific query you use to send commands directly to an ODBC database server. By using pass-through queries, you work directly with the tables on the server instead of having the Microsoft Jet database engine process the data.), and data-definition queries (data-definition query: An SQL-specific query that

contains data definition language (DDL) statements. These statements allow you to create or alter objects in the database.).

Union queries combine data from two or more tables, but not in the same manner as other queries. Whereas most queries combine data by concatenating rows, union queries combine data by appending rows. Union queries differ from append queries in that union queries do not change the underlying tables. Union queries append the rows in a recordset that does not persist after the query is closed.

Pass-through queries are not processed by the database engine that comes with Access; rather, they are passed directly to a remote database server that does the processing and then passes the results back to Access.

Data-definition queries are a special type of query that does not process data; instead, data-definition queries create, delete or modify other database objects (database objects: An Access database contains objects such as tables, queries, forms, reports, pages, macros, and modules. An Access project contains objects such as forms, reports, pages, macros, and modules.).

SQL-specific queries cannot be opened in Design view. They can only be opened in SQL view, or run. Except for data-definition queries, running a SQL-specific query opens it in Datasheet view.

Run the query


1. Locate the query in the Navigation Pane.

2.

Do one of the following:

Double-click the query you want to run.

Click the query you want to run, and then press ENTER.

Top of Page

Troubleshoot an error message

The following table shows some common error messages you may encounter. These errors can appear either as a message in a cell (instead of an expected value), or as an error message. The sections that follow the list include procedures you can use to resolve these errors.

NOTE

This content of this table is not exhaustive. If it does not include the error message you received, you can

submit feedback by using the form at the end of this article and including specific information about the error message in the comment box provided.

Error message Type mismatch in expression

Problem The query may be joining fields that have different data types.

Solution Check the query design and ensure that the joined fields have the same data type. For instructions, see the section Check the joined fields in your query. Compact and repair the database. For instructions, see the section Compact and repair your database. Change the alias. For instructions, see the section Change a field alias.

Record is Deleted

This can occur if either the object or the database is damaged.

Circular reference caused by alias

The alias assigned to a field is the same as a component of the expression for that field. An alias is a name that is given to any expression in the Field row of the query design grid that is not an actual field. Access assigns the alias for you if you do not do so yourself; for example, EXPR1. An alias is immediately followed by a colon (:) and then by the expression. When you run the query, the alias becomes the column name in the datasheet.

#Error

This error can occur when the value of a calculated field is greater than the value allowed by the field's FieldSize property setting. This also occurs when the denominator of a calculated field is or evaluates to zero (0). The record being referred to has been deleted.

Ensure that the calculated field's denominator does not evaluate to zero (0). If appropriate, change the FieldSize property. If the record was deleted accidentally, it must be restored from a backup. If the deletion was intentional, you can dismiss this error message by pressing SHIFT+F9 to refresh the query.

#Deleted

Check the joined fields in your query


To check the data types of fields in a query, you look at the source tables in Design view and inspect the properties for the fields you are checking.

1.

Open the query in Design view. Joins appear as lines that connect fields in the source tables. Note the table and field names for each join.

2.

In the Navigation Pane, right-click each table that has one or more fields joined in your query, and then click Design View.

Joined fields with different data types.

Right-click the table, then click Design View.

3.

For each join, compare the values in the Data Type column of the table design grid for the fields involved in that join.

Check the data type of the joined fields in table Design view.

4.

To switch to a table so that you can see its fields, click the tab with that table's name.

Top of Page

Compact and repair your database

Running the Compact and Repair Database utility within Access can improve the performance of your database. This utility makes a copy of the database file and, if it is fragmented, rearranges how the database file is stored on disk. After the compact and repair process has completed, the compacted database will have reclaimed wasted space, and is usually smaller than the original. By compacting the database frequently, you can help ensure optimal performance of the database application, and also resolve errors that arise from hardware problems, power failures or surges, and similar causes.

After the compact operation has completed, query speed is enhanced because the underlying data has been rewritten to the tables in contiguous pages. Scanning contiguous pages is much faster than scanning fragmented pages. Queries are also optimized after each database compaction.

During the compact operation, you can use the original name for the compacted database file, or you can use a different name to create a separate file. If you use the same name and the database is compacted successfully, Access automatically replaces the original file with the compacted version.

Set an option that automates this process


1. Click the Microsoft Office Button , and then click Access Options.

2.

Click Current Database and, under Application Options, select the Compact on Close check box.

This causes Access to automatically compact and repair the database every time it is closed.

Manually compact and repair your database


1. Click the Microsoft Office Button Compact and Repair Database. , point to Manage, and then, under Manage this database, click

NOTE

For the compact operation to succeed, you must have enough storage space on your hard disk for both the

original and the compacted database.

Top of Page

Change a field alias

1.

Open the query in Design view.

2.

In the query design grid, look for fields that have aliases. These will have a colon at the end of the field name, as in Name:.

3.

Check each alias to ensure that the alias does not match the name of any field that is part of the alias' expression. If it does, change the alias.

Understand append queries


An append query adds a set of records (rows) from one or more source tables (or queries) to one or more destination tables. Typically, the source and destination tables reside in the same database, but they don't have to. For example, suppose that you acquire some new customers and a database that contains a table of information about those customers. To avoid entering that new data manually, you can append it to the appropriate table in your database. You can also use append queries to:

Append fields that are based on criteria. For example, you might want to append only the names and addresses of customers who have outstanding orders.

Append records when some of the fields in one table don't exist in the other table. For example, suppose that your Customers table has 11 fields, and the fields in the Clients table in another database match 9 of your 11 fields. You can use an append query to add only the data in the matching fields and ignore the others.

Remember that you cannot use append queries to change the data in individual fields in existing records. To do that type of task, you use an update query you can only use append queries to add rows of data.

For more information about update queries, see the article Create an update query. For general information about other ways to add records to a database or change existing data, see the article Add one or more records to a database.

Top of Page

Create and run an append query

The process of creating an append query follows these basic steps:

Create a select query.

Convert the select query to an append query.

Choose the destination fields for each column in the append query.

Run the query to append the records.

NOTE

Remember that you cannot undo the results of an append query, so proceed carefully. Also remember that

the data types that you set for the fields in the source table must be compatible with the data types that you set for the table fields in the destination table. For example, you can append numbers to a text field, but you cannot append text into a number field unless you use an expression, such as (Val(TextField)), to first convert the data to the Number data type.

For more information about data types and how to use them, see the article Modify or change the data type set for a field.

Create a select query


1. Open the database that contains the records that you want to append.

2.

On the Create tab, in the Other group, click Query Design.

The query designer opens, and the Show Table dialog box appears.

3.

Select any combination of tables or queries that contain the records that you want to append, click Add, and then click Close.

The tables or or queries appear as one or more windows in the upper section of the query design grid. These windows list all the fields in each table or query. This figure shows a typical table in the query designer.

4.

Double-click the fields that you want to append. The selected fields appear in the Field row in the design grid (the lower section of the query designer).

You can add an expression such as =Date() to automatically return today's date, or you can add table or query fields to the cells in the design grid. You can add one table or query field per cell.

To quickly add all the fields in a table, double-click the asterisk (*) at the top of the list of table fields. This figure shows the design grid with all fields added.

5.

Optionally, you can enter one or more criteria in the Criteria row of the design grid. The following table shows some example criteria and explains the effect they have on a query.
Criteria > 234 >= "Callahan" Between #2/2/2007# And #12/1/2007# Effect Returns all numbers greater than 234. To find all numbers less than 234, use < 234. Returns all records from Callahan through the end of the alphabet. Returns dates from 2-Feb-07 through 1-Dec-07 (ANSI-89). If your database uses the ANSI-92 wildcard characters, use single quotation marks (') instead of pound signs. Example: Between '2/2/2007' And '12/1/2007'. Finds all records where the exact contents of the field are not exactly equal to "Germany." The criterion will return records that contain characters in addition to "Germany," such as "Germany (euro)" or "Europe (Germany)". Finds all records except those beginning with T. If your database uses the ANSI-92 wildcard character set, use the percent sign (%) instead of the asterisk (*). Finds all records that do not end with t. If your database uses the ANSI-92 wildcard character set, use the percent sign instead of the asterisk. In a list, finds all records containing Canada or UK. In a Text field, finds all records that start with the letters A through D. If your database uses the ANSI-92 wildcard character set, use the percent sign instead of the asterisk. Finds all records that include the letter sequence "ar". If your database uses the ANSI-92 wildcard character set, use the percent sign instead of the asterisk. Finds all records that begin with "Maison" and that also contain a 5-letter second string in which the first 4 letters are "Dewe" and the last letter is unknown (indicated by a question mark). If your database uses the ANSI-92 wildcard character set, use the underscore (_) instead of the question mark. Finds all records for February 2, 2007. If your database uses the ANSI-92 wildcard character set, surround the date with single quotation marks instead of pound signs (#). Example: '2/2/2007'. Returns all dates more than 30 days old. Returns all records containing today's date. Returns all records between today's date and three months from today's date.

Not "Germany"

Not "T*"

Not "*t"

In(Canada,UK) Like "[A-D]*"

Like "*ar*"

Like "Maison Dewe?"

#2/2/2007#

< Date() - 30 Date() Between Date() And DateAdd("M", 3, Date()) Is Null Is Not Null ""

Returns all records that contain a null (blank or undefined) value. Returns all records that contain a value. Returns all records that contain a zero-length string. You use zero-length strings when you need to add a value to a required field, but you don't yet know what that value is. For example, a field may require a fax number, but some of your customers may not have fax machines. In that case, you enter a pair of double quotation marks with no space between them ("") instead of a number.

6.

On the Design tab, in the Results group, click Run.

7.

Verify that the query returned the records that you want to update. If you need to add or remove fields from the query, switch back to Design view and add fields as described in the preceding step, or select the fields that you don't want and press DELETE to remove them from the query.

8.

Continue to the next procedure, in which you will convert the select query to an append query.

Convert the select query to an append query


1. Right-click the document tab for the open query and click Design View on the shortcut menu.

-or-

In the Navigation Pane, right-click the query and then click Design View on the shortcut menu.

2.

On the Design tab, in the Query Type group, click Append.

The Append dialog box appears.

3.

At this point, you can choose whether to append records from one table to an existing table in the same database, or to an existing table in a different database.

NOTE

If you want to copy records to a new table, you must use a make-table query.

Show me how to create a make-table query

1.

Follow the steps in this section to create a select query. Modify the select query as needed until it returns the records that you want to place in the new table.

2.

Switch to query Design view. Right-click the document tab for the query, and then click Design View.

-or-

Right-click the query in the Navigation Pane, and then click Design View.

3.

On the Design tab, in the Query Type group, click Make Table.

The Make Table dialog box appears.

4.

In the Table Name combo box, enter a name for the new table.

5.

Do one of the following:

  

Place the new table in the open database.

Leave Current Database selected and click OK.

Place the new table in another database.

1.

Click Another Database.

2.

Enter the file path and name of the other database, or click Browse to locate the database, and then click OK after you locate the database.

3.

In the Table Name combo box, enter a name for the new table.

4.

Click OK.

Now that you have converted the query, you need to decide whether you want to append the records to a table in the same database or to a table in a different database. Depending on your choice, use the steps in one of the two following procedures:

Append records to a table in the same database


1. In the Append dialog box, click Current Database (if it isn't already selected), and then select the destination table from the Table Name combo box.

2.

Click OK.

What you see depends on how you created your select query. For example, if you added all the fields from your source table or query, Access now adds all the fields in the destination table to the Append to row in the design grid.

-or-

If you added individual fields to the query, and the field names in the source and destination tables match, Access automatically adds the names of the destination fields to the Append to row in the query.

-or-

If you added individual fields, and any of the names in the source and destination tables don't match, Access leaves those fields blank. You can click a cell in the Append to row and select a destination field.

This figure illustrates how you click a cell in the Append to row and select a destination field.

NOTE

If you leave the destination field blank, the query will not append data to that field.

3.

To preview your changes, switch to Datasheet view. To do so, right-click the document tab for the query, and then click Datasheet View.

-or-

In the Navigation Pane, right-click the query and then click Datasheet View.

4.

Return to Design view, and then click Run

to append the records.

Reminder You cannot undo the results of an append query, so make very sure that you want to append the records.

Append records to a table in another database


1. In the Append dialog box, click Another Database.

2.

In the File Name box, enter the location and name of the destination database.

3.

In the Table Name combo box, enter the name of the destination table, and then click OK.

or Click Browse and use the subsequent Append dialog box to locate the destination database. Click OK after you locate and select the destination database. This closes the subsequent Append dialog box. In the first Append dialog box, in the Table Name combo box, enter the name of the destination table, and then click OK.

What you see depends on how you created your select query. For example, if you added all the fields from your source table or query, Access now adds all the fields in the destination table to the Append to row in the design grid.

-or-

If you added individual fields to the query, and the field names in the source and destination tables match, Access automatically adds the names of the destination fields to the Append to row in the query.

-or-

If you added individual fields, and any of the names in the source and destination tables don't match, Access leaves those fields blank. You can click a cell in the Append to row and select a destination field.

This figure illustrates how you click a cell in the Append To row and select a destination field.

NOTE

If you leave the destination field blank, the query will not append data to that field.

4.

Return to Design view (right-click the tab at the top of the query, and then click Design View), and then click Run Yes. to append the records. When you are prompted to confirm the operation, click

Understand update queries


You use update queries to add, change, or delete the data in one or more existing records. You can think of update queries as a powerful form of the Find and Replace dialog box. You enter a select criterion (the rough equivalent of a search string) and an update criterion (the rough equivalent of a replacement string). Unlike the Find and Replace dialog box, update queries can accept multiple criteria, allow you to update a large number of records in one pass, and allow you to change records in more than one table at one time.

Remember these rules as you proceed:

You cannot use an update query to add new records to a table, but you can change existing null values to non-null values. To add new records to one or more tables, you use an append query.

For more information about append queries, see the article Create an append query.

You cannot use an update query to delete entire records (rows) from a table, but you can change existing non-null values to null. To delete entire records (a process that also deletes the primary key value), you must use a delete query.

For more information about delete queries, see the article Use a delete query to delete one or more records from a database.

You can use an update query to change all the data in a set of records.

In addition, you cannot run an update query against several types of table fields:

Fields that result from calculations. The values in calculated fields do not permanently reside in tables. They only exist in your computer's temporary memory after Access calculates them. Because calculated fields do not have a permanent storage location, you cannot update them.

Fields that use totals queries or crosstab queries as their record source.

AutoNumber fields. By design, the values in AutoNumber fields change only when you add a record to a table.

Fields in union queries.

Fields in unique-values queries and unique-records queries queries that return non-duplicate values or records. This rule applies when you use an update query and also when you try to update data manually by entering values in a form or a datasheet.

Primary keys that participate in table relationships, unless you set the relationships to automatically cascade updates through the key field and any related fields. When you cascade updates, Access automatically updates any foreign key values in a child table (the table on the many side of a one-to-many relationship) when you change a primary key value in a parent table (the table on the one side of a one-tomany relationship).

NOTE

You cannot cascade updates for records that use an AutoNumber field to generate primary key

values.

For information about turning on and off cascading updates, see Enable cascading updates, later in this article.

For general information about other ways to add records to a database or change existing data, see the article Add one or more records to a database.

Top of Page

Back up your data


You should back up your database before you run an update query. You cannot undo the results of an update query, so making a backup ensures that you can always reverse your changes.

1.

Click the Microsoft Office Button Back Up Database.

, point to Manage, and then, under Manage this database, click

2.

In the Save Backup As dialog box, specify a name and location for the backup copy, and then click Save.

Access closes the original file, creates a backup, and then reopens the original file.

To revert to a backup, close and rename the original file so that the backup copy can use the name of the original version. Assign the name of the original version to the backup copy, and then open the renamed backup copy in Access.

Top of Page

Stop Disabled Mode from blocking a query


By default, Access disables all action queries (update, append, delete, or make table queries) unless your database resides in a trusted location, or unless the database is signed and trusted. If you have not taken either of these actions, you can still enable the query for the current database session only by clicking Enable Content on the Message Bar.

If you try to run an action query and it seems like nothing happens, check the Access status bar for the following message:

This action or event has been blocked by Disabled Mode.

When you see that message, take the following steps:

Enable blocked content


On the Message Bar, click Options.

The Microsoft Office Security Options dialog box appears.

Click Enable this content, and then click OK.

Run your query again.

If you don't see the Message Bar


Click the Database Tools tab, and in the Show/Hide group, click Message Bar.

For more information about Disabled mode and Access security, see the article Secure an Access 2007 database.

Top of Page

Create and run an update query


The safest way to use an update query is to first create a select query that tests your selection criteria. For example, suppose that you want to update a series of Yes/No fields from No to Yes for a given customer. To do so, you can add criteria to your select query until it returns all of the records that contain No in the records for that customer. When you are sure that the query returns the correct records, you then convert it to an update query, enter your update criteria, and then run the query to change the selected values. The steps in this section explain how to create a select query and then convert it to an update query.

Create a select query


1. Open the database that contains the records you want to update.

2.

On the Create tab, in the Other group, click Query Design.

The query designer opens, and the Show Table dialog box opens.

3.

Select the table or tables that contain the records you want to update, click Add, and then click Close.

The table or tables appear as one or more windows in the query designer, and the windows list all the fields in each table. This figure shows the query designer with a typical table.

4.

Double-click the fields that you want to update. The selected fields appear in the Field row in the query design grid.

You can add one table field per column in the query design grid.

To add all the fields in a table quickly, double-click the asterisk (*) at the top of the list of table fields. This figure shows the query design grid with all fields added.

5.

Optionally, you can enter one or more criteria in the Criteria row of the query design grid. The following table shows some example criteria and explains the effect they have on the results of a query.

NOTE

Many of the examples in this table use wildcard characters to make the query more flexible or

powerful.

For more information about using wildcards in your queries, see the article Access wildcard character reference.
Criteria >234 >="Cajhen" Between #2/2/2007# And #12/1/2007# Effect Returns all numbers greater than 234. To find all numbers less than 234, use < 234. Returns all records from Cajhen through the end of the alphabet. Returns dates from 2-Feb-07 through 1-Dec-07 (ANSI-89). If your database uses the ANSI-92 wildcard characters, use single quotation marks (') instead of pound signs (#). Example: Between '2/2/2007' And '12/1/2007' . Finds all records where the exact contents of the field are not exactly equal to "Germany." The criterion will return records that contain characters in addition to "Germany," such as "Germany (euro)" or "Europe (Germany)". Finds all records except those beginning with T. If your database uses the ANSI-92 wildcard character set, use the percent sign (%) instead of the asterisk (*). Finds all records that do not end with t. If your database uses the ANSI-92 wildcard character set, use the percent sign (%) instead of the asterisk (*). In a list, finds all records containing Canada or UK.

Not "Germany"

Not "T*"

Not "*t"

In(Canada,UK)

Like "[A-D]*"

In a text field, finds all records that start with the letters A through D. If your database uses the ANSI-92 wildcard character set, use the percent sign (%) instead of the asterisk (*). Finds all records that include the letter sequence "ar". If your database uses the ANSI-92 wildcard character set, use the percent sign (%) instead of the asterisk (*). Finds all records that begin with "Maison" and contain a 5-letter second string in which the first 4 letters are "Dewe" and the last letter is unknown. If your database uses the ANSI-92 wildcard character set, use the underscore (_) instead of the question mark (?). Finds all records for February 2, 2007. If your database uses the ANSI-92 wildcard character set, surround the date with single quotation marks (') instead of pound signs (#); for example, ('2/2/2007'). Uses the Date function to return all dates more than 30 days old. Uses the Date function to return all records containing today's date. Uses the Date and DateAdd functions to return all records between today's date and three months from today's date.

Like "*ar*"

Like "Maison Dewe?"

#2/2/2007#

< Date() - 30 Date() Between Date() And DateAdd("M", 3, Date()) Is Null Is Not Null ""

Returns all records that contain a null (blank or undefined) value. Returns all records that contain a value. Returns all records that contain a zero-length string. You use zero-length strings when you need to add a value to a required field, but you don't yet know what that value is. For example, a field might require a fax number, but some of your customers might not have fax machines. In that case, you enter a pair of double quotation marks with no space between them ("") instead of a number.

6.

On the Design tab, in the Results group, click Run.

Verify that the query returns the records that you want to update. As needed, you can select fields you don't want included in the query design and press DELETE to remove them. In addition, you can drag additional fields to the query design grid.

7.

Go to the next steps.

Update records
1. On the Design tab, in the Query Type group, click Update.

This procedure shows how to change the select query to an update query. When you do so, Access adds the Update to row in the query design grid. The following illustration shows an update query that returns all assets purchased after January 5, 2005 and changes the location to "Warehouse 3" for all records that meet that criterion.

2.

Locate the field that contains the data you want to change, and type your expression (your change criteria) in the Update to row for that field.

You can use any valid expression in the Update to row. This table shows some example expressions and explains how they change data.
Expression "Salesperson" #8/10/07# Yes "PN" & [PartNumber] [UnitPrice] * [Quantity] [Freight] * 1.5 DSum("[Quantity] * [UnitPrice]", "Order Details", "[ProductID]=" & [ProductID]) Right([ShipPostalCode], 5) Result In a Text field, changes a text value to Salesperson. In a Date/Time field, changes a date value to 10-Aug-07. In a Yes/No field, changes a No value to Yes. Adds "PN" to the beginning of each specified part number. Multiplies the values in fields named UnitPrice and Quantity. Increases the values in a field named Freight by 50 percent. Where the ProductID values in the current table match the ProductID values in table named Order Details, this expression updates sales totals by multiplying the values in a field named Quantity by the values in a field named UnitPrice. The expression uses the DSum function because it can operate against more than one table and table field.

Truncates (removes) the leftmost characters in a text or numeric string and leaves the 5 rightmost characters. Changes a null (unknown or undefined) value to a zero (0) value in a field named UnitPrice.

IIf(IsNull([UnitPrice]), 0, [UnitPrice])

3.

On the Design tab, in the Results group, click Run.

An alert message appears.

4.

Click Yes to run the query and update the data.

5.

NOTE

When you run the query, you might notice that some fields are missing from your result set. If your

query contains fields that you don't update, Access does not display those fields in the results, by default. For example, you might include ID fields from two tables to help ensure that your query returns and

operates on the correct records. If you don't update those ID fields, Access does not display them in the results.

Top of Page

Update data from one table to another


A large number of database users find that they have to update the data in one table with data from another and many of those users often find the task hard to complete. When you need to update data from one table to another, keep this rule in mind: the data types for the source and destination fields must either match or be compatible.

Also, when you update data from one table to another and use compatible data types instead of matching data types, Access converts the data types of those fields in the destination table. As a result, some of the data in the destination fields might be truncated (deleted). The section Restrictions on data type conversions lists the ways in which you can and cannot convert data types. The table also explains when converting a data type can change or eliminate some or all of the data in a field and what data might be eliminated.

The process of updating data from one table to another follows these broad steps:

Create an update query and add both the source and destination tables to the query.

Join those tables on the fields that contain the related information.

Add the names of your destination fields to the Field row of the query design grid.

Add the names of your source fields to the Update To row of the query design grid by using the following syntax: [source_table].[source_field].

The steps in this section assume the use of two similar tables. In this example, the Clients table resides in a database that you just inherited, and it contains more recent data than the Customers table. You can see that some of the manager names have changed and, in addition, some of the addresses. For that reason, you decide to update the Customers table with the data from the Clients table.

The Clients table


Clien t ID Addres s State/Provinc e Country/Regio n Phon e Contac t

Name

City

Posta l

Code 1 Baldwin Museum of Science Blue Yonder Airlines 1 Main St. New York NY 12345 USA (505) 5552122 (104) 5552123 (206) 5552124 Josh Barnhill

52 1st St.

Boston

MA

23456

USA

Waleed Heloo

Coho Winery

3122 75th Ave. S.W. 1 Contoso Blvd. Calle Smith 2

Seattle

WA

34567

USA

Pica Guido

Contoso Pharmaceutical s Fourth Coffee

London

Bucks

NS1 EW2

England

(171) 5552125 (7) 5552126 (206) 5552125 (916) 5552128 (503) 5552129 (503) 5552233

Zoltan Harmut h Julian Price

Mexico City

56789

Mexico

Consolidated Messenger

3123 75th St. S. 1587 Office Pkwy 3 Microsof t Way 4 Microsof t Way

Seattle

WA

34567

USA

Miles Reid

Graphic Design Institute

Tampa

FL

87654

USA

Tzipi Butnaru

Litware, Inc.

Portlan d

OR

31415

USA

Brian Smith

Tailspin Toys

Portlan d

OR

31415

USA

Phil Gibbins

The Customers table


Country or Region USA

Customer ID 1

Name Baldwin Museum of Science Blue Yonder Airlines

Address 1 Main St.

City New York

State/Province NY

Postal Code 12345

Phone (505) 5552122 (104) 5552123 (206) 5552124

Manager Steve Riley

52 1st St.

Boston

MA

23456

USA

Waleed Heloo

Coho Winery

3122 75th Ave. S.W. 1 Contoso Blvd.

Seattle

WA

34567

USA

Pica Guido

Contoso Pharmaceuticals

London

Bucks

NS1 EW2

England

(171) 5552125

Zoltan Harmuth

Fourth Coffee

Calle Huevos 134 3123 75th St. S. 67 Big St.

Mexico City

56789

Mexico

(7) 5552126 (206) 5552125 (916) 5552128 (503) 5552129 (503) 5552233

Julian Price

Consolidated Messenger

Seattle

WA

34567

USA

Christine Hughes

Graphic Design Institute

Tampa

FL

87654

USA

Dana Birkby

Litware, Inc.

3 Microsoft Way 4 Microsoft Way

Portland

OR

31415

USA

Jesper Aaberg

Tailspin Toys

Portland

OR

31415

USA

Phil Gibbins

As you proceed, remember that although the data types for each table field do not have to match, they must be compatible, mean that Access must be able to convert the data in the source table into a type that the destination table can use. In some cases, the conversion process might delete some data. For more information about restrictions on converting data types, see the section Restrictions on data type conversions.

The following steps assume the use of the two preceding sample tables. You can adapt the steps to fit your data.

Create and run the update query


1. On the Create tab, in the Other group, click Query Design.

2.

In the Show Table dialog box, double click your source and destination tables to add them to the query. Each table appears in a window in the query designer. When you have finished adding tables, click Close to close the Show Table dialog box.

3.

Join the tables on the fields that contain the related information. To do so, drag the related field from one table and drop it on the equivalent field in the other table.

For example, if you use the sample tables shown earlier, you drag the Client ID field to the Customer ID field. When you do so, Access creates a relationship between those fields in the two tables and uses that relationship to join any related records.

4.

On the Design tab, in the Query Type group, click Update.

5.

In the destination table, double-click the fields that you want to update. Each field appears in the Field row in the query design grid.

If you use the sample tables, you add all fields except the Customer ID field. Notice that the name of the destination table appears in the Table row of the design grid.

6.

In the Update To row of the query, in each of the columns that contains a destination field, add the name of the source table and the field in the source table that corresponds to the field in the destination table, and be sure to use this syntax: [Table].[Field], where you surround table and field names with square brackets, and you separate table and field names with a period.

This figure shows part of the design grid, using the sample tables. Note the syntax for the table and field names in the Update To row.

As you proceed, remember that you must spell the table and field names in the Update To row correctly, and you must match any punctuation in the original table and field names. However, you do not need to match capitalization.

7.

On the Design tab, in the Results group, click Run.

8.

When asked to confirm the update, click Yes.

Restrictions on data type conversions


This table lists the data types that Access provides, explains any restrictions on converting data types, and briefly describes any data losses that might occur during conversion.

Convert to this type Text

From this type Memo Number Date/Time Currency AutoNumber Yes/No

Changes or restrictions Access deletes all but the first 255 characters. No restrictions. No restrictions. No restrictions. No restrictions. The value -1 (Yes in a Yes/No field) converts to Yes. The value 0 (No in a Yes/No fields) converts to No. Access truncates links longer than 255 characters. No restrictions. No restrictions. No restrictions. No restrictions. No restrictions. The value -1 (Yes in a Yes/No field) converts to Yes. The value 0 (No in a Yes/No fields) converts to No. No restrictions. Text must consist of numbers and valid currency and decimal separators. The number of characters in the Text field must fall within the size set for the Number field. For more information about the sizes of number fields, see the article Insert, create, or delete a field to store numeric values.

Hyperlink Memo Text Number Date/Time Currency AutoNumber Yes/No

Hyperlink Number Text

Memo

The Memo field must contain only text and valid currency and decimal separators. The number of characters in the Memo field must fall within the size set for the Number field. For more information about the sizes of number fields, see the article Insert, create, or delete a field to store numeric values.

Number, but with a different field size or precision Date/Time

Values must not be larger or smaller than what the new field size can store. Changing precision might cause Access to round some values.

The dates that you can convert depend on the size of the number field. Remember that Access stores all dates as serial dates, and it stores the date values as double-precision floating integers. Access uses December 30, 1899 as date 0. Dates outside of the range April 18, 1899 and September 11, 1900 exceed the size of a Byte field. Dates outside the range April 13, 1810 and September 16, 1989 exceed the size of an Integer field. To accommodate all possible dates, set the Field Size property of your Number field to Long Integer or greater.

For more information about serial dates, and how Access uses and stores date values, see the article Enter a date or time value.

Currency

Values must not exceed (or fall below) the size limit set for the field. For example, you can convert a Currency field to an Integer field only when those values are greater than 255 and do not exceed 32,767. Values must fall within the size limit set for the field. "Yes" values convert to -1. "No" values convert to 0. N/A Original text must be a recognizable date or date/time combination. For example, 18-Jan2007. Original text must be a recognizable date or date/time combination. For example, 18-Jan2007. Value must fall between -657,434 and 2,958,465.99998843. Value must fall between -$657,434 and $2,958,465.9999. Value must exceed -657,434 and be less than 2,958,466. The value -1 (Yes) converts to December 29, 1899. The value 0 (No) converts to midnight (12:00 AM). N/A Text must consist of numbers and valid separators. Text must consist of numbers and valid separators. No restrictions. No restrictions, but Access might round the value No restrictions. The value -1 (Yes) converts to $1, and the value 0 (No) converts to 0$. N/A Not allowed if the AutoNumber field serves as a primary key. Not allowed if the AutoNumber field serves as a primary key. Not allowed if the AutoNumber field serves as a primary key. Not allowed if the AutoNumber field serves as a primary key. Not allowed if the AutoNumber field serves as a primary key. Not allowed if the AutoNumber field serves as a primary key. N/A Original text must consist only of Yes, No, True, False, On, or Off.

AutoNumber Yes/No Hyperlink Date/Time Text

Memo

Number Currency AutoNumber Yes/No

Hyperlink Currency Text Memo Number Date/Time AutoNumber Yes/No Hyperlink AutoNumber Text Memo Number Date/Time Currency Yes/No Hyperlink Yes/No Text

Memo Number Date/Time Currency AutoNumber Hyperlink Hyperlink Text

Original text must consist only of Yes, No, True, False, On, or Off. Zero or Null converts to No, all other values convert to Yes. Null or 12:00:00 AM converts to No, all other values convert to Yes. Zeroes and Nulls convert to No, all other values to Yes. Access coverts all values to Yes. N/A If the original text contains a valid Web address, such as adatum.com, www.adatum.com, or http://www.adatum.com , Access converts the text to a hyperlink. Access tries to convert other values, meaning that you see underlined text, and the cursor changes when you point at the link, but the links don't work. The text can contain any valid Web protocol: http://, gopher://, telnet://, ftp://, wais://, and so on. See the previous entry. The same restrictions apply. Not allowed when a Number field is part of a relationship. If the original value is in the form of a valid Internet Protocol (IP) address (four number triplets separated by a period: nnn.nnn.nnn.nnn) and the numbers happen to coincide with a Web address, the conversion results in a valid link. Otherwise, Access appends http:// to the beginning of each value, and the resulting links are not valid. Access appends http:// to the beginning of each address, but the resulting links will almost never work. Access appends http:// to the beginning of each value, but like dates, the resulting links will almost never work. Not allowed when the AutoNumber field is part of a relationship. Access appends http:// to the beginning of each value, but the resulting links will almost never work. Access converts all Yes values to -1 and all No values to 0, and appends http:// to the beginning of each value. The resulting links do not work.

Memo Number

Date/Time

Currency

AutoNumber

Yes/No

Understand make table queries


A make table query retrieves data from one or more tables, and then loads the result set into a new table. That new table can reside in the database that you have open, or you can create it in another database.

Typically, you create make table queries when you need to copy or archive data. For example, suppose you have a table (or tables) of past sales data, and you use that data in reports. The sales figures cannot change because the transactions are at least one day old, and constantly running a query to retrieve the data can take time especially if you run a complex query against a large data store. Loading the data into a separate table and using that table as a data source can reduce workload and provide a convenient data archive. As you proceed, remember that the data in your new table is strictly a snapshot; it has no relationship or connection to its source table or tables.

The process of creating a make table query follows these broad steps:

Enable the database, if it is not signed or if it does not reside in a trusted location. You cannot run action queries (append, update, and make table queries) otherwise.

In query Design view, create a select query and then modify that query until it returns the records you want. You can select data from more than one table and, in a real sense, you can de-normalize your data. For example, you can place customer, shipper, and supplier data in a single table, something you would not do in a production database with properly normalized tables. You can also use criteria in the query to further customize or narrow your result set.

For more information about normalizing your data, see the article Database design basics.

Convert the select query to a make table query, choose a location for the new table, and then run the query to create the table.

Do not confuse a make table query with an update or append query. You use an update query when you need to add or change data in individual fields. You use an append query when you need to add records (rows) to an existing set of records in an existing table.

For more information about update queries, see the article Create an update query. For more information about append queries, see the article Create an append query.

Top of Page

Create a make table query


You create a make table query by first creating a select query, and then converting it to a make table query. Your select query can use calculated fields and expressions to help return the data that you need. The following steps explain how to create and convert the query. If you already have a select query that fits your needs, you can skip ahead to the steps for converting the select query and running the make table query.

Enable the database


NOTE

Follow these steps only when your database does not reside in a trusted location or is not signed. Access

displays the Message Bar whenever you open an untrusted or unsigned database.

1.

On the Message Bar, click Options.

2.

In the Microsoft Office Security Options dialog box, click Enable this content, and then click OK.

If you don't see the Message Bar


On the Database Tools tab, in the Show/Hide group, click Message Bar.

Create the select query


NOTE

If you already have a select query that produces the data that you need, go to the next steps.

1.

On the Create tab, in the Other group, click Query Design.

2.

In the Show Table dialog box, double-click the tables from which you want to retrieve data. Each table appears as a window in the upper section of the query designer. Click Close when have finished adding the tables.

3.

In each table, double-click the field or fields that you want to use in your query. Each field appears in a blank cell in the Field row of the design grid. This figure shows the design grid with several table fields added.

4. 5. Optionally, add any expressions to the Field row.

6.

Optionally, add any criteria to the Criteria row of the design grid.

7.

Click Run

to run the query and display the results in a datasheet.

8.

Optionally, change your fields, expressions, or criteria and rerun the query until it returns the data that you want to place in your new table.

Convert the select query


1. Open your select query in Design view, or switch to Design view. Access provides several ways to do this:

If you have the query open in a datasheet, right-click the document tab for your query and click Design View.

If the query is closed, in the Navigation Pane, right-click the query and click Design View on the shortcut menu.

2.

On the Design tab, in the Query Type group, click Make Table.

The Make Table dialog box appears.

3.

In the Table Name box, enter a name for the new table.

-or-

Click the down-arrow and select an existing table name.

4.

Do one of the following:

Place the new table in the current database

1.

If it isn't already selected, click Current Database, and then click OK.

2.

Click Run

, and then click Yes to confirm the operation.

NOTE

If you are replacing an existing table, Access first deletes that table and asks you to

confirm the deletion. Click Yes, and then click Yes again to create the new table.

Place the new table in another database

1.

Click Another Database.

2.

In the File Name box, enter the location and file name of the other database.

-or-

Click Browse, use the new Make Table dialog box to locate the other database, and click OK.

3.

Click OK to close the first Make Table dialog box.

4.

Click Run

, and then click Yes to confirm the operation.

NOTE

If you replace an existing table, Access first deletes that table and asks you to confirm

the deletion. Click Yes, and then click Yes again to create the new table.

Top of Page

Learn more about query criteria and expressions


The steps in this article mentioned query criteria and expressions. A query criterion is a rule that identifies the records that you want to include in a query, and you use criteria when you do not want to see all the records in a given set of data. For example, the criterion >25 AND <50 returns values greater than 25 and less than 50. A criterion such as "Chicago" OR "Paris" OR "Moscow" returns only the records for those cities.

For more information about using criteria, see the article Examples of query criteria.

An expression is a combination of mathematical or logical operators, constants, functions, and names of fields, controls, and properties that evaluates to a single value. You use an expression when you need data that does not reside directly in a table. For example, the expression [UnitPrice]*[Quantity] multiplies the value in the UnitPrice field by the value in the Quantity field. You can use expressions in a wide variety of ways, and the process of creating and using them can become quite complex.

For more information about creating and using expressions, see the article Create an expression.

Top of Page

Stop Disabled mode from blocking a query


By default, if you open a database that does not reside in a trusted location, or if you have not chosen to trust the database, Access prevents all action queries append, update, delete, or make-table queries from running.

If you try to run an action query and it seems like nothing happens, check the Access status bar for the following message:

This action or event has been blocked by Disabled Mode.

When you see that message, do the following:

Enable blocked content


On the Message Bar, click Options.

The Microsoft Office Security Options dialog box appears.

Click Enable this content, and then click OK.

Run your query again.

Understand make table queries


A make table query retrieves data from one or more tables, and then loads the result set into a new table. That new table can reside in the database that you have open, or you can create it in another database.

Typically, you create make table queries when you need to copy or archive data. For example, suppose you have a table (or tables) of past sales data, and you use that data in reports. The sales figures cannot change because the transactions are at least one day old, and constantly running a query to retrieve the data can take time especially if you run a complex query against a large data store. Loading the data into a separate table and using that table as a data source can reduce workload and provide a convenient data archive. As you proceed, remember that the data in your new table is strictly a snapshot; it has no relationship or connection to its source table or tables.

The process of creating a make table query follows these broad steps:

Enable the database, if it is not signed or if it does not reside in a trusted location. You cannot run action queries (append, update, and make table queries) otherwise.

In query Design view, create a select query and then modify that query until it returns the records you want. You can select data from more than one table and, in a real sense, you can de-normalize your data. For example, you can place customer, shipper, and supplier data in a single table, something you would not do in a production database with properly normalized tables. You can also use criteria in the query to further customize or narrow your result set.

For more information about normalizing your data, see the article Database design basics.

Convert the select query to a make table query, choose a location for the new table, and then run the query to create the table.

Do not confuse a make table query with an update or append query. You use an update query when you need to add or change data in individual fields. You use an append query when you need to add records (rows) to an existing set of records in an existing table.

For more information about update queries, see the article Create an update query. For more information about append queries, see the article Create an append query.

Top of Page

Create a make table query


You create a make table query by first creating a select query, and then converting it to a make table query. Your select query can use calculated fields and expressions to help return the data that you need. The following steps explain how to create and convert the query. If you already have a select query that fits your needs, you can skip ahead to the steps for converting the select query and running the make table query.

Enable the database


NOTE

Follow these steps only when your database does not reside in a trusted location or is not signed. Access

displays the Message Bar whenever you open an untrusted or unsigned database.

1.

On the Message Bar, click Options.

2.

In the Microsoft Office Security Options dialog box, click Enable this content, and then click OK.

If you don't see the Message Bar


On the Database Tools tab, in the Show/Hide group, click Message Bar.

Create the select query


NOTE

If you already have a select query that produces the data that you need, go to the next steps.

1.

On the Create tab, in the Other group, click Query Design.

2.

In the Show Table dialog box, double-click the tables from which you want to retrieve data. Each table appears as a window in the upper section of the query designer. Click Close when have finished adding the tables.

3.

In each table, double-click the field or fields that you want to use in your query. Each field appears in a blank cell in the Field row of the design grid. This figure shows the design grid with several table fields added.

4.

5.

Optionally, add any expressions to the Field row.

6.

Optionally, add any criteria to the Criteria row of the design grid.

7.

Click Run

to run the query and display the results in a datasheet.

8.

Optionally, change your fields, expressions, or criteria and rerun the query until it returns the data that you want to place in your new table.

Convert the select query


1. Open your select query in Design view, or switch to Design view. Access provides several ways to do this:

If you have the query open in a datasheet, right-click the document tab for your query and click Design View.

If the query is closed, in the Navigation Pane, right-click the query and click Design View on the shortcut menu.

2.

On the Design tab, in the Query Type group, click Make Table.

The Make Table dialog box appears.

3.

In the Table Name box, enter a name for the new table.

-or-

Click the down-arrow and select an existing table name.

4.

Do one of the following:

Place the new table in the current database

1.

If it isn't already selected, click Current Database, and then click OK.

2.

Click Run

, and then click Yes to confirm the operation.

NOTE

If you are replacing an existing table, Access first deletes that table and asks you to

confirm the deletion. Click Yes, and then click Yes again to create the new table.

Place the new table in another database

1.

Click Another Database.

2.

In the File Name box, enter the location and file name of the other database.

-or-

Click Browse, use the new Make Table dialog box to locate the other database, and click OK.

3.

Click OK to close the first Make Table dialog box.

4.

Click Run

, and then click Yes to confirm the operation.

NOTE

If you replace an existing table, Access first deletes that table and asks you to confirm

the deletion. Click Yes, and then click Yes again to create the new table.

Top of Page

Learn more about query criteria and expressions


The steps in this article mentioned query criteria and expressions. A query criterion is a rule that identifies the records that you want to include in a query, and you use criteria when you do not want to see all the records in a given set of data. For example, the criterion >25 AND <50 returns values greater than 25 and less than 50. A criterion such as "Chicago" OR "Paris" OR "Moscow" returns only the records for those cities.

For more information about using criteria, see the article Examples of query criteria.

An expression is a combination of mathematical or logical operators, constants, functions, and names of fields, controls, and properties that evaluates to a single value. You use an expression when you need data that does not reside directly in a table. For example, the expression [UnitPrice]*[Quantity] multiplies the value in the UnitPrice field by the value in the Quantity field. You can use expressions in a wide variety of ways, and the process of creating and using them can become quite complex.

For more information about creating and using expressions, see the article Create an expression.

Top of Page

Stop Disabled mode from blocking a query


By default, if you open a database that does not reside in a trusted location, or if you have not chosen to trust the database, Access prevents all action queries append, update, delete, or make-table queries from running.

If you try to run an action query and it seems like nothing happens, check the Access status bar for the following message:

This action or event has been blocked by Disabled Mode.

When you see that message, do the following:

Enable blocked content


On the Message Bar, click Options.

The Microsoft Office Security Options dialog box appears.

Click Enable this content, and then click OK.

Run your query again.

Aggregate function reference


This table lists and describes the aggregate functions that Access provides in the Total row and in queries. Remember that Access provides more aggregate functions for queries than it does for the Total row. Also, if you work with an Access project (an Access front end connected to a Microsoft SQL Server database), you can use the larger set of aggregate functions that SQL Server provides. For more information about that set of functions, see Microsoft SQL Server Books Online.
Function Average Description Calculates the average value for a column. The column must contain numeric, currency, or date/time data. The function ignores null values. Counts the number of items in a column. Use with the data type(s) Number, Currency, Date/Time

Count

All data types except complex repeating scalar data, such as a column of multivalued lists. For more information about multivalued lists, see the articles Guide to multivalued fields and Add or change a lookup field that lets you store multiple values.

Maximum

Returns the item with the highest value. For text data, the highest value is the last alphabetic value Access ignores case. The function ignores null values. Returns the item with the lowest value. For text data, the lowest value is the first alphabetic value Access ignores case. The function ignores null values. Measures how widely values are dispersed from an average value (a mean). For more information about using this function, see the article Display column totals in a datasheet.

Number, Currency, Date/Time

Minimum

Number, Currency, Date/Time

Standard Deviation

Number, Currency

Sum

Adds the items in a column. Works only on numeric and currency data. Measures the statistical variance of all values in the column. You can use this function only on numeric and currency data. If the table contains less than two rows, Access returns a null value. For more information about variance functions, see the article

Number, Currency

Variance

Number, Currency

Display column totals in a datasheet.

Create a form by using the Form Wizard


To be more selective about what fields appear on your form, you can use the Form Wizard instead of the various form-building tools previously mentioned. You can also define how the data is grouped and sorted, and you can use fields from more than one table or query, provided that you specified the relationships between the tables and queries beforehand. For more information about creating relationships, see the links in the See Also section of this article.

1.

On the Create tab, in the Forms group, click More Forms, and then click Form Wizard.

2.

Follow the directions on the pages of the Form Wizard.

NOTE

If you want to include fields from multiple tables and queries on your form, do not click Next or

Finish after you select the fields from the first table or query on the first page of the Form Wizard. Instead, repeat the steps to select a table or query, and click any additional fields that you want to include on the form. Then click Next or Finish to continue.

3.

On the last page of the wizard, click Finish.

Top of Page

Create a form by using the Blank Form tool


If the wizard or the form-building tools don't fit your needs, you can use the Blank Form tool to build a form. This can be a very quick way to build a form, especially if you plan to put only a few fields on your form.

1.

On the Create tab, in the Forms group, click Blank Form.

Access opens a blank form in Layout view, and displays the Field List pane.

2.

In the Field List pane, click the plus sign (+) next to the table or tables that contain the fields that you want to see on the form.

3.

To add a field to the form, double-click it or drag it onto the form. To add several fields at once, hold down CTRL and click several fields, and then drag them onto the form at the same time.

NOTE

The order of the tables in the Field List pane can change, depending on which part of the form is

currently selected. If you are not able to add a field to the form, try selecting a different part of the form and then try adding the field again. For more information about using the Field List pane, see the article Add a field to a form or report.

4.

Use the tools in the Controls group on the Formatting tab to add a logo, title, page numbers, or the date and time to the form.

5.

If you want to add a wider variety of controls to the form, switch to Design view by right-clicking the form and then clicking Design View . You can then use the tools in the Controls group on the Design tab.

Top of Page

Understand controls
Controls are objects that display data, perform actions, and let you view and work with information that enhances the user interface, such as labels and images. The most commonly used control is the text box, but other controls include labels, check boxes, and subform/subreport controls.

Controls can be bound, unbound, and calculated:

Bound control A control whose source of data is a field in a table or query is called a bound control. You use bound controls to display values that come from fields in your database. The values can be text, dates, numbers, Yes/No values, pictures, or graphs. For example, a text box on a form that displays an employee's last name might get this information from the Last Name field in the Employees table.

Unbound control A control that doesn't have a source of data (such as a field or expression) is called an unbound control. You use unbound controls to display information, lines, rectangles, and pictures. For example, a label that displays the title of a form is an unbound control.

Calculated control A control whose source of data is an expression, rather than a field, is called a calculated control. You specify the value that you want to use as the source of data in the control by

defining an expression. An expression can be a combination of operators (such as = and + ), control names, field names, functions that return a single value, and constant values. For example, the following expression calculates the price of an item with a 25 percent discount by multiplying the value in the Unit Price field by a constant value (0.75).

=[Unit Price] * 0.75

An expression can use data from a field in the form's underlying table or query, or data from another control on the form.

For more information about expressions, see the links in the See Also section.

When you create a form, it is probably most efficient to add and arrange all the bound controls first, especially if they make up the majority of the controls on the form. You can then add the unbound and calculated controls that complete the design by using the tools in the Controls group on the Design tab in Design view.

You bind a control to a field by identifying the field from which the control gets its data. You can create a control that is bound to the selected field by dragging the field from the Field List pane to the form. The Field List pane displays the fields of the form's underlying table or query. To display the Field List pane, press ALT+F8, or on the Design tab, in the Tools group, click Add Existing Field. When you double-click a field in the Field List pane, Access adds the appropriate type of control for that field to the form.

Alternatively, you can bind a field to a control by typing the field name in the control itself or in the box for the Control Source value in the control's property sheet. The property sheet defines the characteristics of the control, such as its name, the source of its data, and its format. To open the property sheet, press F4.

Using the Field List pane is the best way to create a bound control for two reasons:

Access automatically fills in the control's attached label with the name of the field (or the caption defined for that field in the underlying table or query), so you don't have to type the control's label yourself.

Access automatically sets many of the control's properties to the appropriate values according to the properties of the field in the underlying table or query (such as the Format, Decimal Places, and Input Mask properties).

If you already created an unbound control and want to bind it to a field, set the value in the control's Control Source property box to the name of the field. For details about the Control Source property, press F1 while the cursor is in the property's drop-down list.

Top of Page

Understand control layouts


Control layouts are guides that align your controls horizontally and vertically to give your form a uniform appearance. You can think of a control layout as a table, where each cell of the table contains a control. The following procedures show you how to add, remove, or rearrange controls in control layouts.

Control layouts come in two varieties: tabular and stacked.

In tabular control layouts, controls are arranged in rows and columns like a spreadsheet, with labels across the top. Tabular control layouts always span two sections of a form; whichever section the controls are in, the labels are in the section above.

In stacked layouts, controls are arranged vertically like you might see on a paper form, with a label to the left of each control. Stacked layouts are always contained within a single form section.

You can have multiple control layouts of either type on a form. For example, you might have a tabular layout to create a row of data for each record, and then one or more stacked layouts underneath, containing more data from the same record.

Create a new control layout


Access automatically creates stacked control layouts in either of the following circumstances:

You create a new form by clicking Form in the Forms group on the Create tab.

You create a new form by clicking Blank Form in the Forms group on the Create tab, and then dragging a field from the Field List pane to the form.

On an existing form, you can create a new control layout by doing the following:

1.

Select a control that you want to add to the layout.

2.

If you want to add other controls to the same layout, hold down the SHIFT key and also select those controls.

3.

Do one of the following:

 

On the Arrange tab, in the Control Layout group, click Tabular

or Stacked

Right-click the selected control or controls, point to Layout, and then click Tabular .

or Stacked

Access creates the control layout and adds the selected controls to it.

Switch a control layout from tabular to stacked, or from stacked to tabular

To switch an entire layout from one type of layout to the other:

Select the control layout by clicking the orange layout selector at the top left corner of the layout. All of the cells in the layout are selected.

Do one of the following:

On the Arrange tab, in the Control Layout group, click the layout type you want (Tabular Stacked ).

or

Right-click the control layout, point to Layout, and then click the layout type you want.

Access rearranges the controls into the layout type you want.

Split one control layout into two layouts


You can split a control layout into two layouts by doing the following:

1.

Hold down the SHIFT key and click the controls you want to move to the new control layout.

2.

Do one of the following:

On the Arrange tab, in the Control Layout group, click the layout type you want for the new layout (Tabular or Stacked ).

Right-click the selected controls, point to Layout, and then click the layout type you want for the new layout.

Access creates a new control layout and adds the selected controls to it.

Rearrange controls in a control layout


You can move a control within a control layout by dragging it to the location you want. As you drag the field, a horizontal or vertical bar indicates where it will be placed when you release the mouse button.

You can move a control from one control layout to another control layout of the same type. For example, you can drag a control from one stacked layout to another stacked layout, but not to a tabular layout.

Add controls to a control layout


To add a new field from the Field List pane to an existing control layout

Drag the field from the Field List pane to the layout. A horizontal or vertical bar indicates where the field will be placed when you release the mouse button.

To add existing controls to an existing control layout

1.

Select the first control you want to add to the control layout.

2.

If you want to add other controls to the same layout, hold down the SHIFT key and also select those controls. You can select controls in other control layouts.

3.

Do one of the following:

If the form is open in Design view, drag the selected fields to the layout. A horizontal or vertical bar indicates where the fields will be placed when you release the mouse button.

If the form is open in Layout view:

1.

On the Arrange tab, in the Control Layout group, click the type of the layout to which you are adding the controls. If you are adding controls to a tabular layout, clickTabular adding controls to a stacked layout, click Stacked . . If you are

Access creates a new layout and adds the selected controls to it.

2.

Drag the new layout to the existing layout. A horizontal or vertical bar indicates where the fields will be placed when you release the mouse button.

Remove controls from a control layout


Removing a control from a control layout allows you to place it anywhere on the form without affecting the positioning of any other controls.

Select the control you want to remove from the layout. To select multiple controls, hold down the SHIFT key and then click the controls you want to remove. To select all of the controls in the layout, click the layout selector box at the top left corner of the layout.

Do one of the following:

On the Arrange tab, in the Control Layout group, click Remove

Right-click one of the selected controls, point to Layout, and then click Remove

Access removes the selected controls from the layout.

Top of Page

Understand Layout view and Design view


Layout view Layout view is the most intuitive view to use for form modification, and it can be used for nearly all the changes you would want to make to a form in Office Access 2007. In Layout view, the form is actually running, so you can see your data much as it will appear in Form view. However, you can also make changes to the form design in this view. Because you can see the data while you are modifying the form, this is a very useful view for setting the size of controls or performing almost any other task that affects the appearance and usability of the form.

Certain tasks cannot be performed in Layout view and require switching to Design view. In certain situations, Access displays a message telling you that you must switch to Design view to make a particular change.

Design view Design view gives you a more detailed view of the structure of your form. You can see the Header, Detail, and Footer sections for the form. The form is not actually running when it is shown in Design view, so you cannot see the underlying data while you are making design changes; however, there are certain tasks you can perform more easily in Design view than in Layout view. You can:

Add a wider variety of controls to your form, such as labels, images, lines, and rectangles.

Edit text box control sources in the text boxes themselves, without using the property sheet.

Resize form sections, such as the Form Header or the Detail section.

Change certain form properties that cannot be changed in Layout view (such as Default View or Allow Form View).

Top of Page

Fine-tune your form in Layout view


After you create a form, you can easily fine-tune its design by working in Layout view. Using the actual form data as your guide, you can rearrange the controls and adjust their sizes. You can place new controls on the form and set the properties for the form and its controls.

To switch to Layout view, right-click the form name in the Navigation Pane and then click Layout View

Access shows the form in Layout view.

You can use the property sheet to modify the properties for the form and its controls and sections. To display the property sheet, press F4.

You can use the Field List pane to add fields from the underlying table or query to your form design. To display the Field List pane, do one of the following:

On the Formatting tab, in the Controls group, click Add Existing Fields.

Press ALT+F8.

You can then drag fields directly from the Field List pane onto your form.

To add a single field, double-click it or drag it from the Field List pane to the section on the form where you want it displayed.

To add several fields at once, hold down CTRL and click the fields that you want to add. Then drag the selected fields onto the form.

Top of Page

Fine-tune your form in Design view

You can also fine-tune your form's design by working in Design view. You can add new controls and fields to the form by adding them to the design grid. The property sheet gives you access to a large number of properties that you can set to customize your form.

To switch to Design view, right-click the form name in the Navigation Pane and then click Design View

Access shows the form in Design view.

You can use the property sheet to modify the properties for the form and its controls and sections. To display the property sheet, press F4.

You can use the Field List pane to add fields from the underlying table or query to your form design. To display the Field List pane, do one of the following:

On the Formatting tab, in the Controls group, click Add Existing Fields.

Press ALT+F8.

You can then drag fields directly from the Field List pane onto your form.

To add a single field, double-click it or drag it from the Field List pane to the section on the form where you want it displayed.

To add several fields at once, hold down CTRL and click the fields that you want to add. Then drag the selected fields onto the form.

To add a single field, double-click it or drag it from the Field List pane to the section on the form where you want it displayed.

To add several fields at once, hold down CTRL and click the fields that you want to add. Then drag the selected fields onto the form.

Top of Page

Add controls to your form

Some controls are created automatically, such as the bound control that is created when you add a field from the Field List pane to your form. Many other controls can be created in Design view by using the tools in the Controls group on the Design tab.

NOTE

Many of the tools in the Controls group are accessible only while your form is open in Design view. To .

switch to Design view, right-click the form name in the Navigation Pane and then click Design View

Determine the name of a tool


Place the mouse pointer over the tool.

Access displays the name of the tool.

Use Control Wizards


You can use wizards to help you create command buttons, list boxes, subforms, combo boxes, and option groups. On the Design tab, in the Controls group, if Use Control Wizards is not selected, click it to select it.

If you prefer to create controls without the help of the wizard, click Use Control Wizards so that it is not selected.

Create a control by using the tools in the Controls group


1. Click the tool for the type of control that you want to add. For example, to create a check box, click the Check Box tool.

2.

Click in the form design grid where you want to position the upper-left corner of the control. Click once to create a default-sized control, or click the tool and then drag the mouse pointer in the form design grid to create a control of the size that you want.

3.

If you selected Use Control Wizards and the control that you are placing has a wizard associated with it, the wizard starts and guides you through the settings for the control.

4.

If you don't position the control perfectly on the first try, you can move it by doing the following:

1.

Click the control to select it.

2.

Position the mouse pointer over the control until the pointer turns into a four-headed arrow

3.

Click and drag the control to the location that you want.

If you use a Control Wizard, the wizard might contain steps to help you bind the control to a field. Otherwise, this procedure creates an unbound control. If the control is of the type that can display data (a text box or check box, for example), you must enter a field name or expression in the Control Source property box for the control before it will display any data. To display the properties for a control, select the control and then press F4. For more information, see the Understand controls section.

Top of Page

Save your work


After you save your form design, you can run the form as often as you want. The design stays the same, but you see current data every time you view the form. If your needs change, you can modify the form design or create a new form that is based on the original.

Save your form design

1.

Click the Microsoft Office Button

, and then click Save.

Alternatively, click Save

on the Quick Access Toolbar, or press CTRL+S.

2.

If the form is untitled, type a name in the Form Name box, and then click OK.

Save your form design under a new name

1.

Click the Microsoft Office Button

, and then click Save As.

2.

In the Save As dialog box, type a name in the Save Form To box, select Form in the As list, and then click OK.

Add a field to a form or report by using the Field List pane


1. Open your report in Layout view or Design view.

If the Field List pane is not displayed, do one of the following:

On the Formatting tab, in the Controls group, click Add Existing Fields.


2.

Press ALT+F8.

In the Field List pane, find the table containing the field you want to add. To show or hide the list of fields in each table, click the plus (+) or minus sign (-) next to the table name.

NOTE

If the database does not contain any tables, the Field List pane is empty.

3.

When you find the field you want to add, do one of the following to add it to the form or report:

Double-click the field.

Drag the field from the Field List pane to the form or report.

Hold the CTRL key and click several fields, and then drag them all to the form or report at the same time.

NOTE

This technique can be used only on fields in the Fields available for this view section of

the Field List pane.

Add a range of fields from the Field List pane to the form or report by doing the following:

1.

Click the first field in the range.

2.

Press and hold the SHIFT key, and then click the last field in the range.

Access selects the fields you clicked, as well as all the fields in between.

3.

Drag all the selected fields to the form or report.

NOTE

This technique can only be used on fields in the Fields available for this view section of

the Field List pane.

4.

Office Access 2007 creates the appropriate control to display each field, and also binds the control to the field. In addition, Access creates an attached label for the control. You can edit the label by clicking it once to select it, and then clicking it again to place the insertion point in the label. Then, you can edit the label in the same way that you would edit text in a document.

5.

If you want a field displayed in a different type of control other than the one that Access creates automatically, you can change the control to another type. However, you can only change it to a control type that is appropriate for that field. For example, you can change a combo box to a text box or a list box, but you can't change a combo box to a command button.

6. Change a control from one type to another


1. Open the form or report in Design view by right-clicking it in the Navigation Pane and then clicking Design View .

2.

Right-click the control you want to change, and then click Change To.

If the Change To menu item is unavailable, there are no other control types that are appropriate for this field. Otherwise, Access displays a list of control types.

3.

Click one of the available control types to change the control to that type.

The control remains bound to the field, but you might have to set some properties to make the new control type work the way you want. To display the property sheet for a control, click the control to select it, and then press F4.

Top of Page

Add a field to a form or report in Design view


In general, using the Field List pane is the easiest way to add a field to a form or report. However, you can also add a field by creating a control and then binding it to a field. The following procedure shows you how.

1.

Open the form or report in Design view by right-clicking it in the Navigation Pane and then clicking Design View.

Control Wizards You can use the Control Wizards to help you create command buttons, list boxes, subforms, combo boxes, and option groups. A Control Wizard asks you a series of questions about how you want the control to look and operate, and then it creates the control and sets the control's properties based on your answers. On the Design tab, in the Controls group, if Use Control Wizards is not highlighted, click it to highlight it.

If you would rather create controls without the help of the wizards, click Use Control Wizards so that it is not selected.

2.

On the Design tab, in the Controls group, click the tool for the type of control you want to add.

To determine the name of a tool, position the pointer over it. Access displays the name of the tool.

3.

Click in the form or report design grid where you want to position the upper-left corner of the control. Click once to create a default-sized control, or click the tool and then drag in the form design grid to create a control of the size that you want.

4.

If you have selected Use Control Wizards and the control you are placing has a wizard associated with it, the wizard starts and guides you through the settings for the control.

5.

If you don't position the control perfectly on the first try, you can move it by doing the following:

1.

Click the control to select it.

2.

Position the pointer over the control until it turns into a move pointer

3.

Click and drag the control to the location that you want.

If you use a control wizard, the wizard might contain steps to help you bind the control to a field. If the wizard does not bind the control to a field, and control is of the type that can display data (a text box or combo box, for example), you must enter a field name or expression in the Control Source property for the control before it will display any data. Use the following procedure to bind a control to a field.

1.

Display the property sheet for the control by clicking the control, and then pressing F4.

2.

On the Data tab of the property sheet, click the drop-down arrow next to the Control Source property and select the field you want displayed in the control. You can also type an expression in the Control Source box.

For more information about expressions, see the article Create an expression.

Top of Page

Learn more about the Field List pane


The following list contains tips about working with the Field List pane that may be helpful to you as you add fields to your form or report. To display the Field List pane, open a form or report in Layout view or Design view, and then press ALT+F8.

If the form or report's Record Source property is empty, and you drag a field from the Field List pane to the form or report, Access automatically fills in the form or report's Record Source property for you.

If the form or report's Record Source property is a SELECT statement or a table name, you can toggle the Field List pane display between the following two states:

All database fields Displays the Fields available for this view section, the Fields available in related tables section (if such tables exist), and the Fields available in other tables section (if such tables exist).

Record source fields only Displays only the Fields available for this view section.

To switch between the two modes, click either Show only fields in the current record source or Show all tables at the bottom of the Field List pane.

NOTE

If you have set the form or report's Record Source property to a saved query, the Field List

pane displays only the Fields available for this view section (there is no Show all tables option at the bottom of the Field List pane). To edit the record source, right-click any one of the fields, and then click Edit Record Source.

If you have set the form or report's Record Source property to a table, and you then drag a field from the Fields available in related tables section of the Field List pane to the form or report, Access changes the Record Source of the form or report to a SELECT statement that includes the field you are adding. If Access cannot determine how to relate the tables, it displays the Choose Relationship dialog box so you can choose the appropriate relationship.

If you drag a field from the Fields available in other tables section of the Field List pane to the form or report, Access displays the Specify Relationship dialog box. You must use this dialog box to specify a relationship between the other table and the form or report's record source. If you are not sure which fields to enter in this dialog box, you might want to click Cancel and then examine your table relationships.

For more information about relationships, see Guide to table relationships or Create, edit, or delete a relationship.

It is possible that a field in the Fields available in other tables section of the Field List pane is indirectly related to the record source of the form or report through one of the tables in the Fields available in related tables section. If this is the case, dragging a field from one of the related tables to the form or report may cause one or more tables to move from the Fields available in other tables section to the Fields available related tables section.

If the record source of the form or report is a SELECT statement or a saved query, you can view and edit the record source in the Query Builder by right-clicking any field in the Field List pane and then clicking Edit Record Source. If the record source is a table, this command invokes the Query Builder on the table. Access asks you if you want to create a query based on the table; click Yes to change the record source to a query, or No to leave the record source unchanged.

You can open a table in Datasheet view by clicking Edit Table next to the table name, or by right-clicking the table name in the Field List pane and then clicking Open Table in Datasheet View.

You can use the Field List pane to add a Lookup field (Lookup field: A field, used on a form or report in an Access database, that either displays a list of values retrieved from a table or query, or stores a static set of values.) to a table by doing the following:

1.

Click Edit Table next to the table in which you want to add the Lookup field.

The table is displayed in Datasheet view.

2.

Drag a field from the Field List pane to the datasheet.

3.

The Lookup Wizard starts. Follow the instructions in the wizard. On the last page, click Finish.

You can undock the Field List pane from the right side of the Access work area by positioning the pointer in the title bar of the Field List pane until it turns into a move pointer , and then dragging the

Field List pane to the left. You can position the list anywhere in the work area, or you can dock it to the left side of the work area by dragging it all the way to the left.

Insert a title into a form or report


Show All

1.

Open the form or report in Layout view.

How?

2.

On the Formatting tab, in the Controls group, click Title.

A new label is added to the form or report header, and the form or report name is displayed as the title.

3.

When the label is created, the text in the label is automatically selected so that you can change the text by typing the title you want.

4.

Press ENTER when you have finished.

Edit an existing form or report title


1. Place the cursor in the label that contains the title by double-clicking the label.

2.

Type the text you want to use as the title, and then press ENTER when you have finished.

Insert page numbers into a form or report


Show All

Insert page numbers into a form


1. Open the form in Design view.

How?

2.

On the Design tab, in the Controls group, click Page Numbers.

The Page Numbers dialog box appears.

3.

Choose the format, position, and alignment that you want for the page numbers.

4.

Clear the Show Number on First Page check box if you do not want a number on the first page.

5.

Click OK.

The page numbers will be added to the Page Header section of the form, but they will be visible only when the form is printed (or when you click the Microsoft Office Button Print Preview ). , point to Print, and then click

Insert page numbers into a report


1. Open the report in Layout view.

How?

2.

On the Formatting tab, in the Controls group, click Page Numbers.

The Page Numbers dialog box appears.

3.

Choose the format, position, and alignment that you want for the page numbers.

4.

Clear the Show Number on First Page check box if you do not want a number on the first page.

5.

Click OK.

The page numbers will be added to the report. To see how the page numbers will look when the report is run, switch to Print Preview .

Insert the date and time into a form or report


Show All

1.

Open the form or report in Layout view.

How?

2.

On the Formatting tab, in the Controls group, click Date and Time.

The Date and Time dialog box appears.

3.

Clear the Include Date check box if you do not want to include the date.

4.

If you want to include the date, click the date format that you want to use.

5.

Clear the Include Time check box if you do not want to include the time.

6.

If you want to include the time, click the time format that you want to use.

A sample of the date and time information in the formats you have chosen appears in the Sample area of the dialog box.

7.

Click OK.

The date and time information is added to the form or report.

Create a grouped or summary report


Show All

Information is often easier to understand when it is divided into groups. For example, a report that groups sales by region can highlight trends that otherwise might go unnoticed. In addition, placing totals at the end of each group in your report can replace a lot of manual interaction with a calculator.

Microsoft Office Access 2007 makes working with grouped reports easy. You can create a basic grouped report by using the Report Wizard, you can add grouping and sorting to an existing report, or you can revise grouping and sorting options that have already been defined.

Build a new grouped report by using the Report Wizard


The Report Wizard presents you with a series of questions, and then generates a report based on your answers. Among those questions is one that asks for the field or fields to use to group your report. After the report is created, you can use it as-is or modify it to better suit your needs. Before you begin with the Report Wizard, you need to decide upon a data source.

Choose a record source


A report consists of information pulled from a table or query, and information stored with the report design, such as labels, headings, and graphics. The table or query that provides the underlying data is also known as the report's record source. Before you start creating your report, you should first think about the information you want to include. Among the fields you choose must be those you wish to group on or summarize. If the fields you want to include all exist in a single table, use that table as the record source. If the fields are pulled from more than one table, you'll want to use a query as the record source. That query may already exist in your database, or you may need to create a query specifically to fit the needs of your report.

To learn more about queries, follow the links in the See Also section of this article.

Start the Report Wizard


1. On the Create tab, in the Reports group, click Report Wizard.

Access starts the Report Wizard.

2.

Click the Tables/Queries drop-down list and choose the table or query that contains the fields you want on your report.

3.

Double-click fields in the Available Fields list to choose them.

Access moves them to the Selected Fields list. Alternatively, you can click the buttons located between the Available Fields box and the Selected Fields box to add or remove the selected field or to add all or remove all of the fields.

4.

If there are fields in another table or query that you also want to put on your report, click the Tables/Queries drop-down list again and choose the other table or query, and continue to add fields.

5.

After you've finished adding fields, click Next.

Group records in the Report Wizard


Grouping lets you organize and arrange records by group, such as by Region or SalesPerson. Groups can be nested so that you can easily identify the relationships among the groups and find the information you want quickly. You can also use grouping to calculate summary information, such as totals and percentages.

When you include more than one table in a report, the wizard examines the relationships between the tables and determines how you might want to view the information.

1.

On the page of the Report Wizard that asks Do you want to add any grouping levels?, click one of the field names in the list, and then click Next.

2.

To add grouping levels, double-click any of the field names in the list to add them to your report.

You can also remove a grouping level by double-clicking it in the page display on the right side of the dialog box. Use the arrow buttons to add and remove grouping levels, and adjust the priority of a grouping level by selecting it and clicking the up or down priority buttons. Access adds each grouping level and shows it nested within its parent grouping level.

3.

Click Grouping Options to display the Grouping Intervals dialog box.

4.

Optionally, for each group-level field, choose a grouping interval.

The grouping interval lets you customize how records are grouped. In the previous illustration, records are grouped on the ShippedDate field, which is a Date/Time data type. The Report Wizard offers choices appropriate to the field type in the Grouping intervals list. Thus, because ShippedDate is a Date/Time type, you can choose to group by actual value (Normal), Year, Quarter, Month, Week, Day, Hour and Minute. If the field were a Text data type, you could choose to group by the entire field (Normal), or perhaps by the first one to five characters. For a numeric data type, you can choose to group by value (Normal), or by range in selected increments.

After selecting a grouping interval, click OK.

5.

Click Next to navigate to the next page of the wizard.

Sort and summarize records


You can sort records by up to four fields, in either ascending or descending order.

1.

Click the first drop-down list and choose a field on which to sort.

You can click the button to the right of the list to toggle between ascending and descending order (Ascending is the default). Optionally, click the second, third, and fourth drop-down lists to choose additional sort fields.

2.

Click Summary Options if you want to summarize any of the numeric fields.

Note that the Summary Options button will only be visible if you have one or more numeric fields in the Detail section your report. The wizard displays the available numeric fields.

3.

Select the check box under your choice of Sum, Avg, Min or Max to include those calculations in the group footer.

You can also choose to show the details and summary or the summary only. In the latter case, totals for each ShippedDate value are shown (if you selected the check box for Sum, for example), but the order detail is omitted. You can also choose to show percent of total calculations for sums.

4.

Click OK.

5.

Follow the directions on the remaining pages of the Report Wizard. On the last page, you can edit the title of the report. This title will be displayed on the first page of the report, and Access will also save the report, using the title as the document name. You can edit both the title and the document name later.

6.

Click Finish. Access automatically saves the report and displays it in Print Preview, which shows you the report as it will look when printed.

You can use the navigation buttons at the bottom of the preview pane to view the pages of the report sequentially or jump to any page in the report. Click one of the navigation buttons or type the page number that you want to see in the page number box, and then press ENTER.

In Print Preview, you can zoom in to see details or zoom out to see how well data is positioned on the page. With the mouse pointer positioned over the report, click once. To reverse the effect of the zoom, click again. You can also use the zoom control in the status bar.

Top of Page

Fine-tune your report


It is likely that the Report Wizard will not produce the exact results that you are looking for in your report. For example, you may want to add text, adjust column widths, add a logo, etc. Access provides two views in which you can make modifications to your report: Layout view and Design view. These are discussed briefly in this section.

About Layout view


Layout view is the most easy-to-use view for making report changes, and provides most of the tools you need to finetune your report. You can adjust column widths, rearrange columns, and add or modify grouping levels and totals. You can place new fields on the report design and set the properties for the report and its controls. The advantage of Layout view is that you can see your data while making changes to the report format, so you can immediately see how your changes affect the display of the data.

To open a report in Layout view, right-click the report in the Navigation Pane, and then click Layout view

You can use the property sheet to modify the properties for the report and its controls and sections. To display the property sheet, press F4.

You can use the Field List pane to add fields from the underlying table or query to your report design. To show the Field List pane:

On the Formatting tab, in the Controls group, click Add Existing Fields.

About Design view


If you are unable to make a specific change to your report in Layout view, try Design view. Design view shows you the underlying structure of the report, and provides a few more design tools and capabilities than Layout view. For example, you can place a wider variety of controls on the report, you can adjust the alignment of controls more precisely, and you have the ability to set more properties than you do in Layout view.

To open a report in Design view, right-click the report in the Navigation Pane, then click Design View

Top of Page

Add fields or other controls to an existing report


Every field, label, line, or picture you see on your report is created using some type of control. The most frequentlyused control on a report is the text box. This is what is normally used to display data from the report's underlying record source. You can create text boxes that are already bound to fields in the record source by adding fields from the Field List pane, or you can add them to the report while working in Design view (but then you must "bind" them to fields in the record source yourself). The advantage of Design view is that you can add many other types of controls besides bound text boxes, such as rectangles, page breaks, and charts. This section describes both methods of adding controls to a report.

Add fields to an existing report


Layout view is the recommended view for adding fields to a report, but it can also be done in Design view. To add a field, first make sure that the Field List pane is displayed. The Field List pane contains a list of all of the fields that are available to be placed on the report. To display the Field List pane, press ALT+F8.

Add fields from the Field List pane


To add a single field, drag the field from the Field List pane to the section on the report where you want it displayed.

To add several fields at once, click the first field that you want, and then hold down CTRL and click each additional field that you want. Then, drag the selected fields onto the report.

When you drop the fields, Access creates a bound text box control for each field and automatically places a label control beside each field.

NOTES

If you add a field from a related table, Access will add the appropriate grouping level for you.

If you add a field from another (non-related) table, Access will display a dialog box where you can specify how to relate the table to the existing data source for the report.

To see what table relationships have already been specified for your database, or to add new ones:

On the Database Tools tab, in the Show/Hide group, click Relationships.

For more information, see the article Create, edit or delete a relationship.

Add other controls to an existing report


When you add a field from the Field List pane to your report, a bound text box control for it is created automatically. Other controls such as labels, lines, and images can be added by switching to Design view and using the tools in the Controls group on the Design tab.

Determine the name of a tool


Place the mouse pointer over the tool.

Access displays the name of the tool.

Create a control by using the tools in the Controls group


Click the tool for the type of control that you want to add. For example, to create a check box, click the Check Box tool .

Click in the report design where you want to position the upper-left corner of the control. Click once to create a default-sized control, or click and drag in the report to create a control of the size that you want.

If you don't position the control perfectly on the first try, you can move it by using the following procedure:

Click the control to select it.

Position the pointer over the control until it turns into a four-headed arrow control to the desired location.

, and then drag the

This process creates an "unbound" control. If the control is the type that can display data (a text box or check box, for example), you will need to enter a field name or expression in the Control Source property for the control before it will display any data.

Display the property sheet


Press F4.

NOTE

When your new report is complete, be sure to save your work.

Top of Page

Add or modify grouping and sorting in an existing report


If you have an existing report and you want to add sorting or grouping to it, or if you want to modify the report's existing sorting or grouping, this section helps you get started.

Add grouping, sorting, and totals in Layout view


You can perform simple sorting, grouping and totaling operations by right-clicking fields in Layout view and then choosing the operation you want from the shortcut menu. To switch to Layout view, right-click the report in the Navigation Pane and then click Layout view .

NOTE

Although the instructions in this section don't use the Group, Sort, and Total pane directly, it is a good idea

to open the pane and observe how it changes as you work. You will get a better idea of what Access is doing and, as you get more comfortable working with the Group, Sort, and Total pane, you can use it to make additional adjustments to your report. To display the Group, Sort, and Total pane:

On the Formatting tab, in the Grouping & Totals group, click Group & Sort.

Sort on a single field


Right-click any value in the field that you want to sort.

On the shortcut menu, click the sort option you want. For example, to sort a text field in ascending order, click Sort A to Z . To sort a numeric field in descending order, click Sort Largest to Smallest .

Access sorts the report as you specified. If the Group, Sort, and Total pane is open, you can see that a new Sort by line for the field has been added.

Sort on multiple fields


NOTE

When you apply sorting by right-clicking a field in Layout view, you can only sort one field at a time. Applying

sorting to another field removes the sorting on the first field. This differs from the sorting behavior in forms, where multiple sort orders can be established by right-clicking each field in turn and the choosing the sort order you want. To create multiple sorting levels, see the section Add grouping, sorting, and totals by using the Group, Sort, and Total pane.

Group on a field
Right-click any value in the field on which you want to group.

On the shortcut menu, click Group On

Access adds the grouping level and creates a group header for it. If the Group, Sort, and Total pane is open, you can see that a new Group on line for the field is added.

Add a total to a field


This option lets you calculate a sum, average, count, or other aggregate for a field. A grand total is added to the end of the report, and group totals are added to any groups that exist on the report.

Right-click any value in the field that you want to total.

Click Total.

Click the operation you would like to perform: Sum, Average, Count Records (to count all records), Count Values (to count only the records with a value in this field), Max, Min, Standard Deviation, or Variance.

Access adds a calculated text box control to the report footer, which creates a grand total. Also, if your report has any grouping levels, Access adds group footers (if not already present) and places the total in each footer.

NOTE

You can also add totals by clicking the field that you want totaled and then, on the Formatting tab, in the .

Grouping & Totals group, click Totals

Add grouping, sorting, and totals by using the Group, Sort, and Total pane
Working in the Group, Sort, and Total pane gives you the most flexibility when you want to add or modify groups, sort orders, or totals options on a report. Again, Layout view is the preferred view in which to work because it is much easier to see how your changes affect the display of the data.

Display the Group, Sort, and Total pane


In Layout view:

On the Formatting tab, in the Grouping & Totals group, click Group & Sort.

In Design view:

On the Design tab, in the Grouping & Totals group, click Group & Sort.

Access displays the Group, Sort, and Total pane.

To add a new sorting or grouping level, click Add a group or Add a sort.

A new line is added to the Group, Sort, and Total pane, and a list of available fields is displayed.

You can click one of these field names or you can click expression below the list of fields to enter an expression. Once you choose a field or enter an expression, Access adds the grouping level to the report. If you are in Layout view, the display changes immediately to show the grouping or sort order.

NOTES

If there are already several sorting or grouping levels defined, you may need to scroll down in the Group, Sort, and Total pane before you can see the Add a group and Add a sort buttons.

You can define up to 10 grouping and sorting levels in a report.

Change grouping options


Each sorting or grouping level has a number of options that can be set to obtain the results you want.

To display all the options for a grouping or sorting level, click More on the level that you want to change.

To hide the options, click Less.

Sort order You can change the sort order by clicking the sort order drop-down list, then clicking the option you want.

Group interval This setting determines how the records are grouped together. For example, you can group on the first character of a text field so that all that start with "A" are grouped together, all that start with "B" are grouped together, and so on. For a date field, you can group by day, week, month, quarter, or you can enter a custom interval.

Totals To add totals, click this option. You can add totals on multiple fields, and you can do multiple types of totals on the same field.

Click the Total On drop-down arrow and select the field you want to have summarized.

Click the Type drop-down arrow and select the type of calculation to perform.

Select Show Grand Total to add a grand total to the end of the report (in the report footer).

Select Show group totals as % of Grand Total to add a control to the group footer that calculates the percentage of the grand total for each group.

Select Show in group header or Show in group footer to display the total in the desired location.

Once all the options have been chosen for a field, you can repeat the process and summarize another field by selecting the other field from the Total On drop-down list. Otherwise, click outside the Totals pop-up window to close it.

Title This allows you to change the title of the field being summarized. This is used for the column heading and for labeling summary fields in headers and footers.

To add or modify the title:

Click the blue text following with title.

The Zoom dialog box appears.

Type the new title in the dialog box, and then click OK.

With/without a header section Use this setting to add or remove the header section that precedes each group. When adding a header section, Access moves the grouping field to the header for you. When you remove a header section that contains controls other than the grouping field, Access asks for confirmation to delete the controls.

With/without a footer section Use this setting to add or remove the footer section that follows each group. When you remove a footer section that contains controls, Access asks for confirmation to delete the controls.

Keep group together This setting determines how groups are laid out on the page when the report is printed. You may want to keep groups together as much as possible to reduce the amount of page turning that is needed to see the entire group. However, this usually increases the amount of paper needed to print the report, because most pages will have some blank space at the bottom.

Do not keep group together on one page Use this option if you are not concerned about groups being broken up by page breaks. For example, a group of 30 items may have 10 items on the bottom of one page and the remaining 20 items at the top of the next page.

Keep whole group together on one page This option helps minimize the number of page breaks in a group. If a group cannot fit in the remaining space on a page, Access leaves that space blank and begins the group on the next page instead. Large groups may still span multiple pages, but this option minimizes the number of page breaks within the group as much as possible.

Keep header and first record together on one page For groups with group headers, this ensures that the group header will not print by itself at the bottom of a page. If Access determines that there is not enough room for at least one row of data to be printed after the header, the group begins on the following page.

Change the priority of grouping and sorting levels


To change the priority of a grouping or sorting level, click the row in the Group, Sort, and Total pane and then click the up arrow or the down arrow on the right side of the row.

Delete grouping and sorting levels


To delete a grouping or sorting level, click the row you want to delete in the Group, Sort, and Total pane, and then press DELETE or click the Delete button on the right side of the row. When you delete a grouping level, if the

grouping field was in the group header or footer, Access moves it to the report's Detail section. Any other controls that were in the group header or group footer are deleted.

Top of Page

Create a summary report (without record details)


If you want to show only totals (that is, just the information in header and footer rows), on the Formatting tab, (or on the Design tab in Design view), in the Grouping & Totals group, click Hide Details. Doing this hides the records at the next lower level of grouping, resulting in a much more compact presentation of the summary data. Although the records are hidden, the controls in the hidden section are not deleted. Click Hide Details again to restore the Detail rows to the report.

Create a grouping effect without using headers


You can achieve a grouping effect on your report without the use of headers. Removing headers creates a more compact report because less vertical space is used by the header lines.

The general procedure involves removing the header for each group, which moves each grouping field into the Detail section of the report. To restore the visual grouping effect, you set the Hide Duplicates property of each grouping field to Yes.

Example
Consider this typical grouped report that uses group headers:

As you can see, each company name takes up an entire line, as does each order ID.

In this example, you will edit the report so that it looks like the following illustration:

1.

Open the report in Layout view by right-clicking it in the Navigation Pane, and then clicking Layout View .

2.

On the Formatting tab, in the Grouping & Totals group, click Group & Sort.

NOTE

It is a good idea to start with the lowest-level group and work your way up; otherwise, the display

of the report can become confusing while you are working.

3.

Click the lowest grouping level in the list, and then click More.

4.

From the header section drop-down list, select without a header section.

When you remove a header, Access preserves the text box for the grouping field by moving it to the Detail section. However, any other controls in the group header might be deleted. Access warns you if any controls are going to be deleted as a result of this action. If there are controls in the group header that you want to preserve, be sure to move them to another report section before performing this step. You will need to switch to Design view to move the controls to other sections.

The resulting report is shown in the following illustration. Notice that the first OrderID is on the same line as the first detail record, instead of on its own line.

Unfortunately, the OrderID repeats on every detail line, and this makes it hard to see exactly how many orders there are. At this point, setting the text box control's Hide Duplicates property is useful. Follow these steps to set this property:

  

Select one of the repeating values.

If the property sheet is not currently displayed, press F4 to display it.

On the Format tab of the property sheet, click the drop-down list for Hide Duplicates and then click Yes.

The duplicate order IDs are hidden. Note that you can see how many orders there are, and how many products there are per order.

5.

For this example, we repeat step 4 for the Company Name grouping level. The final report looks like the following illustration:

The Company Name value is now on the same line as the first detail record, and the Hide Duplicates property prevents the Company Name value from repeating on every line. For a long report that uses several grouping levels, this can result in a significant paper savings.

Top of Page

Save, print, or send your report


After you save your report design, you can use it multiple times. The report's design stays the same, but you see current data every time you print the report. If your reporting needs change, you can modify the report design or create a new, similar report that is based on the original.

Save your report


1. Click the Microsoft Office Button , and then click Save.

Alternatively, you can click Save

on the Quick Access Toolbar.

2.

If the report is untitled, type a name in the Report Name box and then click OK.

Save your report design under a new name


1. Click the Microsoft Office Button , and then click Save As.

2.

In the Save As dialog box, type a name in the Save Report To box, click Report in the As box, and then click OK.

Print your report

You can print a report from Print Preview, Layout view, Design view, Report view, or from the Navigation Pane. Before you print, you should double check page settings, such as margins and page orientation. Access saves the page settings with the report, so you need to set them only once. You can save the settings later, if your needs change.

Change the page settings


1. Open the report in any view.

2.

On the Page Layout tab, in the Page group, click an option:

   

Size

allows you to select from a number of paper sizes, or to enter a custom paper size.

Portrait

orients the page vertically.

Landscape

orients the page horizontally.

Margins

allows you to select from several predefined margin widths, or you can click Advanced

to enter custom margin widths by using the Page Setup dialog box.

 

Show Margins toggles the display of margins on and off (Layout view only).

Columns displays the Page Setup dialog box. Enter the number of columns you want, set your desired column size, and then click OK.

Print Data Only suppresses the printing of any labels you have placed on your report. Only the controls that are bound to data in the underlying table or query will be printed. This feature can be helpful on reports that you occasionally print on pre-printed forms. You can suppress the printing of labels in those situations, and then enable the printing of labels when you are printing the report on blank paper.

NOTE

To use more detailed page settings, click the Page Setup button at the lower right corner of the Page

Layout group to display the Page Setup dialog box. You can use the Page Setup dialog box to adjust all the settings that are available on the Page Layout tab, and also to select a specific printer for the report.

Send your report to a printer

1.

Open the report in any view, or just select the report in the Navigation Pane.

2.

Click the Microsoft Office Button

, and then click Print.

3.

In the Print dialog box, enter your choices for options such as printer, print range, and number of copies.

4.

Click OK.

Top of Page

Send your report as an e-mail message


You can send your report to users as an e-mail message instead of printing a paper copy.

1.

In the Navigation Pane, click the report to select it, click the Microsoft Office Button E-mail .

, and then click

2.

In the Send Object As dialog box, click the file format that you want to use.

3.

Complete any remaining dialog boxes.

4.

When your e-mail program appears, type the message details and send the message.

Top of Page

Remarks

A problem can arise if you have a report in an .accdb file that sorts or groups on a lookup field, and you want to import that report into an .mdb file and then open it with an earlier version of Access.

The internal method by which lookup fields are sorted and grouped in .accdb files is incompatible with .mdb files. If you create a report in an .accdb file that uses grouping or sorting on a lookup field, and you then export it into an .mdb file (or use the Save As command to save the database as an .mdb file) and then try to open the report with an earlier version of Access, the report will fail to load.

To revise the report so that you can import it into an .mdb file and open it in an earlier version of Access, do the following:

1.

In the .accdb file, create a copy of the report.

2.

Open the copy of the report in Layout view.

3.

If the Group, Sort, and Total pane is not displayed:


4.

On the Formatting tab, in the Grouping & Totals group, click Group & Sort.

Delete all the lines in the Group, Sort, and Total pane by clicking the Delete button to the right of each line.

5.

Click the Microsoft Office Button

, and then click Save.

6.

Click the Microsoft Office Button

, and then click Close Database.

7.

Click the Microsoft Office Button

, and then click Open.

8.

Browse to the .mdb file into which you want to import the report, and then click Open.

9.

Import the report copy into the .mdb file.

How?

1.

On the External Data tab, in the Import group, click Access.

2.

Click Browse.

3.

Browse to the .accdb file containing the report, and click Open.

4.

You are not importing any tables at this time, so it does not matter whether you choose to import or link to the source data. Click OK to continue.

5.

In the Import Objects dialog box, click the Reports tab.

6.

Click the report you want to import, and then click OK.

7.

If the import operation is successful, Access asks if you want to save the import steps for later use. If you want to save the steps, select the Save import steps check box, enter the requested information, and click Save Import. If you do not want to save the steps, click Close.

Open the report in Layout view.

If the Field List pane is not displayed:

On the Formatting tab, in the Controls group, click Add Existing Fields.

In the Fields available in related tables pane, find the table that contains the field you want displayed on the report. This field will contain the same values that you currently see displayed by the lookup field on the report.

Drag the field to the report.

You now have two columns displaying the same information.

Right-click the display field you just added, and click the sorting option you want to use.

Delete the display field that you just added and sorted.

If the Group, Sort, and Total pane is not displayed:

On the Formatting tab, in the Grouping & Totals group, click Group & Sort.

Click Add a group.

In the Field/Expression pop-up window, click the name of the lookup field on the report.

The report is now sorted and grouped as it was in the .accdb file. Save and close the report.

Print a report
Follow the steps in this section when you need to print some of the pages in a report and when you need to select a printer or change options, such as margins or columns.

1.

In the Navigation Pane, select the report that you want to print. You do not need to open the report, although you can if you need to check for any issues, such as layout problems, or to ensure that you are printing current data.

2.

Click the Microsoft Office Button

, and then click Print.

Keyboard shortcut Press CTRL+P.

The Print dialog box appears.

3.

Set or change the options in the dialog box as needed, and then click Print to print your report.

For help with an option, click the Help button, and then click the field or control for which you need help.

Top of Page

Print a whole report quickly


If you know that your report will be printed correctly, and you want to print all the pages in the report without having to use the Print dialog box or the commands on the Print tab, you can print directly from the Quick Access Toolbar. When you follow these steps, Access prints the entire report by using the margins, headers, footers, and orientation (portrait or landscape) specified for the report. You cannot change any of those properties by following the steps in this section. If you need to change the margins or other properties before you print, see the next section, Preview a report.

Print the report quickly


1. In the Navigation Pane, right-click your report and click Print.

-or-

On the Quick Access Toolbar, click Quick Print

-or-

Click the Microsoft Office Button

, point to the arrow next to Print, and then click Quick Print.

NOTE

You might need to add the Quick Print button to the Quick Access Toolbar. To do so, click the

down-arrow at the end of the toolbar and click Quick Print.

Access prints all of the pages in your report.

Top of Page

Preview a report
You use Print Preview to ensure that your report will be printed correctly. You can use Print Preview to view reports that were created in Office Access 2007 and also in earlier versions of Access. If you preview a report that was created in an earlier version of Access, the report appears in a separate window. That window provides the record navigation buttons. If you preview a report that was created in Office Access 2007, the record navigation buttons appear in the default location, at the bottom of the Access window.

Start Print Preview


1. In the Navigation Pane, right-click the report that you want to preview, and then click Print Preview the shortcut menu. on

-or-

Click the Microsoft Office Button

, point to the arrow next to Print, and then click Print Preview.

-or-

If the report is open, right-click the document tab for the report and click Print Preview.

2.

Click the record navigation buttons to move among the pages in the report.

For more information about using the navigation buttons, see the article Learn how to find records.

Preview two or more pages


1. In the Navigation Pane, right-click the report that you want to preview, and then click Print Preview on the shortcut menu.

-or-

Click the Microsoft Office Button

, point to the arrow next to Print, and then click Print Preview.

-or-

If the report is open, right-click the document tab for the report and click Print Preview.

2.

On the Print Preview tab, in the Preview group, click Two Pages to preview your report two pages at a time.

-or-

In the Preview group, click More Pages, and then select an option.

3.

Click the record navigation buttons to move among the pages in the report.

4.

To revert to previewing a single page, in the Preview group, click One Page.

For more information about using the record navigation buttons, see the article Learn how to find records.

Refresh the data in a preview


On the Print Preview tab, in the Data group, click Refresh All.

NOTE

Refreshing the data in a preview switches the preview back to one page.

Cancel Print Preview


On the Print Preview tab, in the Close Preview group, click Close Preview.

Top of Page

Change the page setup

You use the Page Setup dialog box to change a variety of print options, including the top and bottom margins and whether Access prints just the data in your report. Access provides two ways to display the Page Setup dialog box. You can start it from within the Print dialog box, or you can start it from the Print Preview tab, which appears when you start Print Preview.

The steps in this section explain how to display the Page Setup dialog box. For help with the commands and options that the dialog box provides, click the Help button, and then click the command or option.

Start the Page Setup dialog box from the Print dialog box
1. In the Navigation Pane, select the report that you want to change. You do not need to open the report, although you can if you need to check for any issues, such as layout problems, or to ensure that the data you are about to print is current.

2.

Click the Microsoft Office Button

, and then click Print.

Keyboard shortcut Press CTRL+P.

The Print dialog box appears.

3.

Click Setup to display the Page Setup dialog box.

4.

Set or change the options in the dialog box, as needed.

For help with an option, click the Help button, and then click the field or control for which you need help.

Start the Page Setup dialog box from the Print Preview tab
1. In the Navigation Pane, right-click the report that you want to change and click Print Preview.

Access opens the report in Print Preview.

2.

On the Print Preview tab, in the Page Layout group, click the Page Setup button, located in the lower left or right corner of the group. The location of the button depends on your Windows Regional and Language settings.

3.

Set or change the options in the dialog box, as needed.

Vous aimerez peut-être aussi