Microsoft Access 2007
Microsoft Access 2007
Microsoft Access 2007
April, 2008
The Maricopa County Community College District is an EEO/AA institution. This training manual may be duplicated or put on the Internet for instructional purposes. Please give credit to the Maricopa Community Colleges and to the author(s). This training manual is not to be sold for profit.
Technology Training Services Maricopa Community Colleges 2411 West 14th Street Tempe, Arizona 85281-6942 http://www.maricopa.edu/training
(480) 731-8287
Mission
TABLE OF CONTENTS
Access 2007 Objectives .................................................................. 1 Database Concepts .......................................................................... 2 Start Access..................................................................................... 4 The Access User Interface .............................................................. 6 Database Objects............................................................................. 8 Exploring An Existing Database................................................... 10 Tables Getting Familiar With Datasheet View.......................... 12 Displaying Records In A Subdatasheet ........................................ 14 Finding And Editing Records ....................................................... 16 Replace Or Edit Data .................................................................... 18 Sorting Records............................................................................. 20 Applying And Removing Filters................................................... 23 Filtering By Selection ................................................................... 24 Filter By Form............................................................................... 25 Previewing & Printing Formatting The Datasheet .................... 27 Tables Taking Control With Design View ................................ 31 Relationships................................................................................. 33 Deleting Objects In Access........................................................... 35 Designing The Database ............................................................... 37 Create A New Database ................................................................ 44 Create A Table .............................................................................. 46 Defining Fields ............................................................................. 49 Primary Key .................................................................................. 53
TABLE OF CONTENTS
Field Properties ............................................................................. 55 Input Masks................................................................................... 57 Default Value ................................................................................ 59 Validation Rule ............................................................................. 61 Lookup Field................................................................................. 63 Import Data From An External Source......................................... 67 Importing From An Excel Spreadsheet......................................... 68 Importing Data From An Access Database .................................. 73 Creating Relationships.................................................................. 77 Creating One-To-One Relationships ............................................ 78 Creating One-To-Many Relationships.......................................... 79 Creating Many-To-Many Relationships ....................................... 81 Cascade Options ........................................................................... 87 Queries .......................................................................................... 91 Query Wizard (Simple)................................................................. 92 Query Wizard (Find Duplicates)................................................... 93 Query Wizard (Find Unmatched) ................................................. 94 Select Queries In Design View..................................................... 95 Select Queries (Adding Criteria) .................................................. 96 Select Queries (Conditional - And/Or) ......................................... 98 Select Queries (Calculations)...................................................... 101 Action Queries In Design View.................................................. 104 Action Queries (Update) ............................................................. 105
TABLE OF CONTENTS
Action Queries (Make-Table)..................................................... 107 Action Queries (Delete) .............................................................. 110 Calculating Aggregates............................................................... 112 Calculating Aggregates (On Tables)........................................... 113 Calculating Aggregates (In Queries) .......................................... 114 Forms .......................................................................................... 116 Forms Creation Tools ................................................................. 117 Create A Form (Form Tool)........................................................ 118 Create A Form (Split Form Tool) ............................................... 116 Create A Form (Blank Form Tool) ............................................. 121 Create A Form (Form Wizard) ................................................... 124 Create A Form (Adding Controls) .............................................. 125 Subforms ..................................................................................... 124 Subforms (Enhance The Appearance) ........................................ 131 Control Layouts .......................................................................... 133 Conditional Formatting............................................................... 135 Reports ........................................................................................ 132 Create A Report (Report Tool) ................................................... 138 Group Reports............................................................................. 139 Controls....................................................................................... 143 Adding Totals To A Report In Design View .............................. 145 Modifying The Report (Property Sheet)..................................... 148 Add A Custom Field To A Report.............................................. 149
TABLE OF CONTENTS
Apply An Autoformat To A Report............................................ 151 Print A Report ............................................................................. 153 Use Msword Mail Merge With Access Data .............................. 155 Create Mailing Labels................................................................. 159 Integrate Programs Exporting Data ......................................... 163 Export A Table To Excel ............................................................ 164 Export A Report To Ms Word .................................................... 165 Export 2007 Database To Access 2003 ...................................... 166 Clone The Database .................................................................... 167 Appendix A - On-Line Help ....................................................... 171 Appendix B - Database Templates ............................................. 172 Appendix C - Link To An External Table .................................. 173 Appendix D - Compact And Repair............................................ 174 Index ........................................................................................... 175
DATABASE CONCEPTS
Access 2007 Microsoft Access 2007 is a Database Management System that assists in the creation of a relational database to satisfy the diverse data-tracking needs of an organization. Access 2007 provides the user with various features for creating and editing data organized into tables, forms, and reports. It also allows the import and export of data to and from various applications. A database is a collection of logically related data that can be organized and accessed quickly. The data can be stored as text, numbers, or graphics and can be searched, retrieved, and manipulated. If you have large amounts of data, data that is updated frequently, have many people accessing the data, and want to retrieve data in different formats, a database will work best. The database not only contains data but also a definition of the data which serves as the documentation for your database structure. You wont need to go looking for the database manual to learn how your database was created. That information is contained within the database itself. This is one of the greatest advantages of database management systems. Relational Databases Relational databases store data in a collection of related tables. Each table contains one specific type of information. This table structure ensures that data is stored only once, greatly reducing the amount of duplicate data contained within the database. The limited data duplication that occurs is through the primary and foreign key fields needed to relate the tables. This relational structure helps to preserve the integrity of the data when changes to the data occur.
Database Definition
Description
A group of records for one specific type of information. A group of fields. A single component that describes the record. An allowable entry for a field.
DATABASE CONCEPTS
Excel Table:
Table: Workshops
Value: An allowable value for this field is a number that is at least $50.
3
START ACCESS
Getting Started At the Windows Desktop, click the start button on the Taskbar. Choose Microsoft Office Access 2007 from the start menu. The Getting Started With Microsoft Office Access window opens. The Getting Started screen is divided into three sections. The Template Categories section at the left is used to preview and download predefined templates. In the center, the New Blank Database section is used to start a new database. The section at the right, Open Recent Database, is used to open an existing database file. Click the More hyperlink in the Open Recent Database section.
2.
Ribbon
Navigation Pane
Navigation Pane
Unlike other Microsoft applications, only one database can be open at a time in Access.
DATABASE OBJECTS
Navigation Pane Categories The database contains a variety of objects used to enter, retrieve, manage, and view data. The Navigation Pane, on the left side of the Access User Interface, organizes the database objects into categories and is used to open an object. Tables are the basic building block of the database. They contain information for related items and are broken down into individual units of information. Data is stored in rows and columns. Queries are instructions that extract specific information from one or more tables. When you create and save a query, Access stores the set of instructions needed to create the result of the query, not the result itself. This ensures that you receive the most current data each time you run the query. Queries can also be used to perform calculations. Query Wizards are available to ease query development for the novice database user. Forms are a group of objects which are used to the assist the user in data entry. These objects, or controls, are formatted to create a graphical user interface to enter, display, and edit data. Forms can be customized to include calculations, graphics, and other objects. Reports are screen outputs of data arranged in various formats as required by the user. Reports can also be customized to include calculations, graphics, and other objects and are most often created for the purpose of printed output. Pages, Macros, and Modules are beyond the scope of this introductory class and will not be discussed.
Tabbed Documents
A new feature to Access 2007 is Tabbed Document Window Viewing. This feature allows all open database objects to be displayed in the same window allowing easy navigation between the objects.
When converting a 1997-2003 Access database to a 2007 Access database, your tab viewing feature may not automatically activate. You can activate this feature through the Access Options button on the Office Button pull-down menu. See the notes on Importing.
DATABASE OBJECTS
Changing Views
The View button on the Home tab allows you to switch back and forth between these two views. You can click on the View button down arrow for a drop-down menu of the two view choices or you can click on the button and it will toggle you back and forth between the two views.
1. On the Navigation Bar, open an existing table. 2. Click 3. Click to change to Design view. to change to Datasheet view.
10
Pull-Down Menu
2.
Click the
3.
Click the
11
The Navigation buttons move you to the first, last, next, previous, new, or any specific numbered record in the table.
1. On the Home tab in the Records group, click the More Button. 2. At the drop-down list, click column width. 3. At the Column Width dialog box, change the width and click OK.
12
Active Record
2. 3. 4. 5. 6.
Press the Tab key several times to move forward several fields. Go back using Shift/Tab. Press the arrow keys to move up, down, and side-to-side through the data. Click on the Last Record Navigation Button Click on the First Record Navigation Button to move to the last record. to move to the first record.
To change column width using the ribbon tools, position the cursor at the field to change. On the Home tab in the Records group click the More Button. At the Column Width dialog box, type a value to increase or decrease the column width or use the Best Fit button to set the width to accommodate the length of the longest entry. Press OK. To use the mouse to best fit a column, position the mouse pointer on the right column boundary line in the header row between columns 4 and 5 until the pointer changes to a crosshair. Double-click the left mouse button.
7.
8.
13
Editing Data
Multiple Subdatasheets
Layout Changes
If you switch to another subdatasheet and close the primary table, you will be prompted to save the layout changes. This means that the next time you open the table and use the expand indicator to display a subdatasheet, the new subdatasheet will display. Using the Expand All submenu will open all subdatasheets of related data to the primary table. The Collapse All submenu will close all subdatasheets.
Expand or Collapse
14
2. The subdatasheet opens to display the record for the same employee in the related table Orders. Clicking the expand indicator in the Orders table opens to display the records for the same order in the related table Order Details.
3. The record indicator has now turned to a minus (-) sign. This is the collapse indicator. Clicking the collapse indicator will hide the subdatasheet. 4. On the Home tab in the Records group, click the More button. Point to Subdatasheet at the drop-down list and click Expand All. 5. On the Home tab in the Records group, click the More button. Point to Subdatasheet at the drop-down list and click Collapse All. 6. To change the subdatasheet display, on the Home tab in the Records group, click the More button. Point to Subdatasheet at the drop-down list and click Subdatasheet. A list of all related tables for Employees is displayed. 7. Click Customers on the Tables tab. Click OK. 8. Click the expand indicator on any record in the Employees table. Notice the subdatasheet display. Close Employees. Click No to save layout changes.
15
Find Button
1. At a form or in a table in Datasheet View, place the cursor in the field you are searching. 2. Click on the Find button Replace window displays. in the ribbon. The Find and
3. Enter search criteria in the Find What field. 4. Click on the Find Next button to see the first matching record. 5. Click on the Find Next button to see the next matching record. 6. When there are no more matches, a dialog box opens. Click OK. Cancel returns you to the database.
16
3.
4. 5.
In the Find What field, type Peacock. Click on Find Next. A message box tells you that there were no records found.
6. 7. 8. 9.
Click OK. In the Find What field, type Peacock*. Click on Find Next. Access selects Margaret Peacock. Click on Find Next. Note the current record text box on the Record Navigation Bar.
17
Follow the steps in the previous section to find the first occurrence of the data you wish to change. In the Replace With field enter the data change. Use the options for a more specific search. The Replace and Replace All buttons allow you to replace one entry at a time or all occurrences at once. When making changes to a record directly in the table, a pencil icon will appear in the record selector bar (blank column at the left edge of the datasheet). The pencil icon indicates that the current record is being edited and the changes have not yet been saved. Changes to data will be saved when you move to another record in the table or click the Enter key on the keyboard.
1. Place the cursor in the field to be changed. 2. Click the Replace Button in the ribbon. 3. In the Find What field, type the entry you want found and changed. 4. In the Replace With field, enter the replacement entry. 5. Click on either the Replace or the Replace All button. 6. A message box opens to confirm the change. Click Yes. 7. Click the Close button to close the window.
18
1. 2. 3. 4. 5. 6. 7.
Open the Employees table. Click in any record in the Title field. From the ribbon, click the Replace button. In the Find What field, type Sales Associate. In the Replace With field, type Sales Representative. Click on the Replace All button. A message box opens. Click Yes.
8.
Click the Close button. Note that the change has been made.
19
SORTING RECORDS
How and Why? By default, records in a table are displayed alphanumerically and sorted in ascending order by the primary key field values. To reduce the time you spend searching for data, Access provides several options that will assist you in locating and viewing specified records by arranging data in a specific order. Sorting can be performed on single or multiple fields. Click on any record in the field you wish to sort. The sort buttons are located in the Sort & Filter group on the Home tab in the ribbon. When you click on the Sort Ascending button, the records in the field are sorted in alphabetical order, A-Z. When you click on the Sort Descending button, the records in the field are sorted in reverse alphabetical order, Z-A.
You can also do a sort using more than one field. Columns may be rearranged to perform this sort. Select the columns to be sorted and then click the Ascending or Descending button. Access sorts first by the leftmost column in the selection, then by the next column, and continues this pattern for the remainder of the sort keys. Access saves the sort order when the table is closed. To restore the records to the original order, click the Clear All Sorts button in the Sort & Filter group. This step must be done before you save the design changes.
1. Numbers stored in fields that are not defined as numeric are sorted as character (text) data. All field values must be the same length to sort character type numbers as numbers. 2. If a selected field is empty, the record that contains it is listed first. 3. Numbers are sorted before letters.
20
Restore records to their original order by clicking the Clear All Sorts button.
5.
Now sort the Suppliers alphabetically within an alphabetical listing of Categories. In other words, for each Category (in alphabetical order), show each Supplier (in alphabetical order). As Category is sorted first, it must reside to the left of the Suppliers. Position the mouse pointer in the Category column heading until the pointer changes to a downward-pointing black arrow and click the left mouse button. The column is now selected. Release the mouse. While holding down the left mouse button, drag the Category column header to the left of the Supplier column. A thick black line appears between columns as you drag, indicating the position the new position of the column when you release the mouse. Select both the Category and Supplier columns. Position the mouse pointer in the Category column heading until the pointer changes to a downward-pointing black arrow, hold down the left mouse button, drag right until the Category and Supplier columns are selected, and release the left mouse button. Click the Ascending button, and then click in any cell to deselect the columns. The records are sorted first alphabetically by Supplier then alphabetically by Category.
6.
7.
8.
9.
to close 10. Click on the Close button the Products table. Click No when prompted to save the changes.
21
22
Option
Description Allows you to filter items depending on the value of the selected item. If you are filtering by a Name field, the options list includes selecting equals not equals, contains, or does not contain the value of the item selected. Allows you to filter multiple fields in a form, apply filters that are not commonly available in the filter list, or save your filter as an actual query object in the database. Used to move between the filtered and unfiltered view of data in the table.
1. Filter the records in the desired table. 2. Click the Office button and choose Save As to display the Save As dialog box. 3. In the Save As dialog box, Name the query in the Save To textbox. 4. From the As drop-down list, select Query. Click OK.
23
4. 5.
The Record Navigation Bar indicates that the data is filtered. This customer is having problems with shipments from Speedy Express. Filter out those records so that we can focus on them. Choose a Speedy Express record from the column Ship Via in the display. Click the Selection button in the Filter & Sort group. Click Equals Speedy Express. The new filter is applied. There are only three records displayed.
6.
7.
To cancel the above filters and restore the table to its original view, click the Toggle Filter button. The Record Navigation Bar now indicates that the records are unfiltered.
24
FILTER BY FORM
Complex Filters This feature is useful for filtering several fields or for locating a specific record. Access creates a blank datasheet with the same structure as your original datasheet and allows you to specify search criteria for one or more fields. For Example, if one of your customers is having problems with a particular shipper, display all shipments from this shipper to this customer. The first step is to open the Customers table and click the Advanced button in the Sort and Filter group on the ribbon. Select Filter by Form from the drop-down menu list. You cannot specify field values for multivalued fields using this filter. Fields with Memo, Hyperlink, Yes/No, or OLE object data types are also prohibited. Apply Filter Enter the first set of values, then click the Or tab and enter the next set of values. Each Or tab represents an alternate set of filter values. To apply the filter, click the Toggle Filter button in the Sort & Filter group. Access will show only those records that match your input. To undo a filter, click the Toggle Filter button again. To see the full view of the data, click the filtered button on the Record Navigation Bar.
To remove the filters: 1. Click Filtered on the Record Navigation Bar to return to the full view of data. 2. Click the Advanced button on the ribbon and choose Clear All Filters from the drop-down list. When you remove the current filters, the filters are temporarily removed from all of the fields in the view until you clear them. To reapply the most recent filters: 1. Click Unfiltered on the Record Navigation Bar. 2. The filter will be available as the most recent until all filters are cleared.
25
4. To apply the filter, click the Toggle Filter button on the ribbon. Notice the Filtered indicators in the result.
5. Click the Filtered button on the Record Indicator Bar to temporarily remove the filter. To reapply the most recent filter, click on the Unfiltered button. 6. To save the filtered data as a query, click the Office button and choose Save As to display the Save As dialog box. Name the query and select Query as the type. Click Cancel.
7. Remove the filter from the Customer table by clicking the Toggle Filter button.
26
All records
27
3.
4.
5.
6.
7.
VIEW
8. 9. Close Print Preview by clicking the button in the Close Preview group. You have decided that not all of the data on the datasheet needs to be printed. By hiding columns, they are temporarily unavailable for viewing.
10. On the Employee table Address column, right-click the pull-down menu and select Hide Columns. Also hide Employee ID, Title of Courtesy, City, Region, Postal Code, Photo, and Notes columns.
11. To select multiple columns at the same time, right-click any column pull-down and select Unhide columns. A list of columns in the datasheet is shown along with a checkbox. Uncheck those columns that you wish to temporarily hide from view. Click Close. 12. Preview the datasheet. The datasheet now fits on one page. Click the Print button to print the datasheet. 13. If more formatting needs to be done, close the preview to return to the datasheet view. You can change the font size and type using the options in the Font group on the Home tab. 14. To return the datasheet to its original layout format, right click on any column header pull-down menu and select Unhide Columns. Check all boxes.
29
NOTES
30
Self-Describing
Design Control
Procedure
In the Navigation Pane, double-click a table name to open it in datasheet view. Click the Design view button. Modify the Data Type and Field Description by placing your cursor in that field and typing the change. Use caution when changing data types of populated fields. Place your cursor in the first empty row at the bottom of the field list and type the new field information. Create a blank row by placing the cursor in the row below the insertion field and clicking on the Insert Rows button in the Tools group on the Design tab. Select a row by clicking on the record indicator (the gray shaded bar at the far left of the row) and releasing the mouse. Then click and hold the mouse pointer on the record indicator to display a solid line above the selected record. Drag the field to the desired position. Select the row by clicking the record indicator. Press the delete key. Pay close attention to the warning message.
Make changes
Insert a field
Move a field
Delete a field
31
4.
You are attempting to change the structure of your database. Weigh the consequences carefully before committing the changes. Click No in the warning message. Click the pull-down menu in the Data Type column of the Phone field and select Text. Place your cursor in the first empty row at the bottom of the table. Enter:
Field Name: ContactAddress Data Type: Text Description: Form of address (Mr., Mrs., etc.)
5.
6.
Select the new row by clicking on the record indicator and release the mouse. Reclick the record indicator and while holding the mouse key down, drag the field below the ContactName field. Click the Fax record indicator to select the row. Click the Insert Rows button in the Tools group of the Design tab. Select the new blank row. To delete the row press the delete key or click the Delete Rows button in the Tools group of the Design tab. We do not need to add a field here. Click the Close button to close the table. Click No.
7. 8. 9.
10. We will address field properties and other Design view options later in the course.
32
RELATIONSHIPS
Related Data Access is a relational database management system. The database consists of several subject-based tables. Data may be retrieved from several tables when generating reports or requesting information. Table relationships allow data in tables to be joined to bring the information together as needed. After your tables are created they must be linked together. This is established through a linking field or a common field between the tables. Depending on how the tables are related will determine the type of relationship required. When creating relationships, one table is typically the primary table with the second being the related table. When the tables are joined based on a common field between the two, Access ensures the integrity of the data. For example, Order information (related table) for a Customer (primary table) will not be allowed into the database unless the customer exists. In other words, only customers in your database are allowed to have orders. Trying to find or reference a non-existing customer for an order would create an orphan order. Referential integrity is used to prevent orphans and keep references in sync so that the above situation never occurs. Access creates relationships based on the common field that was used to join the tables. We will create relationships later.
Linked Tables
Referential Integrity
Types of Relationships
Relationship One-to-one One-to-many Description The common data appears only once in both tables. The common data appears once in the primary table, but many times in the related table. The common data can appear many times in both tables. A third table must be created to reduce the redundancy of the data and to create two one-to many relationships.
Many-to-many
33
3.
Each table is related to at least one other table in the database. Data can be retrieved through all of these relationships. The common field has the same name in both tables however; this does not have to be the case.
All relationships in the diagram are one-to-many the infinity symbol ( ) shows the many side of the relationship. To read the relationship between two tables (Customers and Orders for example): A Customer can have many Orders. A specific Order is for only one Customer.
34
Make a Copy
1. Make a copy of the table. 2. At the Navigation Bar, select the table to delete. 3. Press the delete button in the Records group on the Home tab. 4. Pay close attention to the warning message box. 5. Click OK to delete the table.
35
Click OK.
Click NO. 3. When deleting a field that has been specified as the primary key, the following message appears. The primary key is the field that guarantees all records in your table are unique and ensures that there are no duplicate records in your table. It is not a good idea to delete the primary key field.
36
Guidelines Also referred to as redundant data. Keep to a minimum to avoid wasting space and to decrease the likelihood of errors and inconsistencies. Keep table information simple do not include information in a table that does not describe the table. This reduces redundant data. All records in a table must be unique. This is accomplished through the primary key. Also reduces redundant data and decrease possible errors when modifying the database. The primary key must never be blank for any record. Because data is kept in its simplest form to reduce redundancy, it is necessary to combine data from several tables when creating reports or requests for information. Setting up the method for combining data in different tables through relationships ensures the accuracy and integrity of your information. All records belonging to a table takes on the same format, size, and field names. Too much missing information in a record suggests that the data may belong in a different table. Each field has a set of allowable values ensuring the validity of the data.
Subject-based Tables
Uniqueness
Relationships
Similar Records
Allowable Values
Design Process
The database design process consists of several steps: 1. Determine the purpose of your database. 2. Gather existing data and make a list of required fields. 3. Arrange the data into tables. 4. Use sample data to troubleshoot for possible problems such as reducing redundant data. 5. Identify primary keys and specify foreign keys used to relate tables. 6. Determine table relationships and revise the table design as necessary.
37
Example: Books4U
1. Purpose
2. Gather Information
Start with existing information keeping in mind the end result. Gather those documents that are required for day-to-day business operations such as sales slips, purchase invoices, books lists, and customer information. Include spreadsheets, printed documents, index cards, and any other paper or electronic format used. List each item that comes to mind. Dont worry about including everything perfectly at first. Be sure to get input from everyone who will be using the database.
38
The above list is a subset of the data required for Books4U. Each data item describes or is part of an entity in our business. For example, ISBN is an identifier that describes Books. Title also describes Books. Birth Date describes Employees. Order # is part of the transaction process of purchasing a book. The entities become the subjects of our tables. The data items that describe the table entity become the fields of that table. Keep field data as simple as possible to allow for sorting flexibility. For example, it becomes complex to request a sort on cities when city is part of an address field. Keep the city data item separate to facilitate a more efficient search. The same is true for the Name field. Separate first name and last name to allow an alphabetical listing of customers last name.
39
The lists above show 4 possible table designs for our database. The data in Books, Customers, and Employees follow design guidelines. Each field describes the entity of the table, the data items are in their simplest form and it appears that each field will have one value. For example, a Book has only one price, a Customer has only one address, and an Employee has only one title. The Transaction table contains data that will cause problems for database maintenance. First, you should not store the results of calculations in tables as is the case with the Total field. Access can perform the calculation when you want to see the result. Access will calculate this total each time the report is printed. This ensures that you receive the most current data each time. Information should be stored in its smallest form. Customer Name should be separated as first name/last name. However, customer first and last names are already stored in the Customers table. When we relate the tables, we will resolve this situation. The current design for Transactions will cause unnecessary duplication of data. For example, consider a situation when a customer purchases several books at the same time.
Address 123 Any St. 123 Any St. 123 Any St.
Qty 1 1 1
40
Qty 1 1 1
Our modified design shows the transaction # as the only duplication. However, this is a necessary duplication as it links the two tables together and creates a relationship. More about this later. 5. Identify Keys Each table should include one or more fields identified as the Primary Key field. The Primary key ensures that all records in the table are unique and thus reduces unnecessary data redundancy. The primary key field for the Transaction table is transaction #. What is the primary key for the Transaction Detailed Items table? In a relational database, information is divided into separate subject-based tables. Table relationships are used to bring the information together as needed. In the above example, transaction # is used to relate transactions and detailed items. Notice that in the transaction table, customer information is represented by only customer #. If we know the customer # we can go to the Customer table and retrieve that entire customers information. To make this relationship complete, add customer # to the Customer table.
41
Once you have determined the table relationships, test your design for any problems that may occur in retrieving the data. How do you navigate through the database to answer the following questions? 1. What is the name of the customer who purchased The Seeker? 2. On July 15, 2007, who sold the most copies of Harry Potter and the Deathly Hallows? What is their current salary as we need to give them a raise? 3. That book shipment that came in today was damaged. Find out who shipped it and get the contact info so that we can file a claim. Let the vendor know which books were damaged.
42
For the remainder of this workshop, we will develop the outlined tables above for the Books4U database.
43
Auto Save
1. At the Getting Started welcome screen, click the Blank Database button under the New Blank Database section. 2. Type in your database name in the Blank Database pane. 3. Change the location of your file by clicking on the Browse icon next to the File Name box. Select the new location and click OK. 4. Access 2007 will add the extension (.accdb) to your file name. 5. Click the Create button.
44
3. In the Blank Database pane type Books4U in the File Name box. Click the file icon to the right of the file name box to place the location of your database in the Access 07 Class folder on the desktop.
45
CREATE A TABLE
Creating a New Table Access 2007 will open a new table under the Datasheet tab called Table1. The Navigation Pane shows the category All Tables with Table1 listed. Although a new table can be created by simply adding records to the blank datasheet, creating a table in Design View allows you to set data types and design properties. Design view gives you total control in defining table structures. When Access 2007 opens the new table in Datasheet view, the cursor is positioned in the first empty cell in the Add New Field column. An ID field is automatically added to the table. Begin typing to add data. Entering data is similar to entering data in an Excel spreadsheet however, data must be entered in contiguous rows and columns, starting at the upper-left corner of the datasheet. Do not format the data by including blank rows or columns. The visual presentation of your data will be done in forms and reports. The table structure is created while you enter data. Access 2007 sets the data type of the field based on the type of data that you enter. If this is not correct, it may be difficult to change the data type after data has been entered into the table. New Table in Design View By starting in Design View, you set the data types and field properties the way you need them, and then add data later. Access 2007 does not add the ID field to the new table automatically. You have more control in setting the primary key field and the overall table structure. To open Table1 in Design View, on the Home tab in the Views group, click on the Design View button. You will be asked to save the table. At this point, give the table a name and click OK.
1. Click the Create tab on the ribbon. 2. Click the Table Design button in the Tables group.
46
47
3. 4.
The Design View icon is the default display. Click Design View. Notice that the View button is a toggle between the Datasheet and Design Views. You will be asked for a permanent table name to continue. Type Customers and click OK.
5. 6.
To create a new table in Design View directly, make sure that the Create tab is active on the ribbon. In the Tables group, click the Table Design button.
7.
48
DEFINING FIELDS
Creating Data Structure Field Name When creating a table in Design View, you are creating the tables structure. Once youve defined information about the tables fields, you can switch back to Datasheet View to enter your data. For each field in your table, you will define a field name, a data type, and an optional description. The field properties section in the lower half of the work area displays the properties for the active field. The properties will vary depending on the active field. To create a new field, enter a Field Name in the Field Name column. Field Names consists of up to 64 characters (letters or numbers) including spaces. Data Types Data Types determine how data is stored. They also define the allowable values for each field in the table.
Description Alphanumeric data: numbers, letters, symbols and special characters. Alphanumeric characters. Supports rich-text formatting (bold, italic, bulleted lists). Positive or negative values that can be used in arithmetic calculations. Date and time information Monetary values. No rounding during calculations. Automatically generated by Access when a new record is added. Boolean (true/false) data. 1=Yes, 0=No. Used to embed or link objects created in other Office applications. For storing web/email addresses. Allows single-click access. Also link to objects in another database. Store digital images or file attachments to a record. Allows creation of multivalued fields. Displays in a drop-down list.
Memo
Number
1 bit Up to 1 GB
Hyperlink
1 GB
49
3. 4.
The description column is optional. You need only to make an entry in this area if the field is not obvious. Save Customers table. Close Customers table.
50
2. Our design for the Transactions table shows a field called Total. As discussed earlier calculated fields are usually not stored in the database. Access 2007 will calculate the total and present it in either form or report format when needed. Therefore, we will not create a field for Total in the Transactions table.
3. Save the table. Name it Transactions. Click OK. 4. Access alerts you to define a primary key. Click No.
51
2. This table shows the details of what was actually purchased by the customer. It was created to reduce unnecessary data duplication. (see discussion on page 40).
3. Save the table. Name it Transaction Details. Click OK. 4. Access alerts you to define a primary key. Click No. 5. Close the Transaction Details table.
52
PRIMARY KEY
A Unique Identifier A Primary key is a field (or fields) that provide Access 2007 with a unique identifier for each record. Each time the table is opened, it is automatically sorted by the primary key. When a new record is added to the table, Access checks to ensure that there is no other record with the same value in the primary key field. If the data is a duplicate, Access will display a message indicating that duplicate values exist and will not allow the record to be saved. The primary key field can not be left blank when a new record is added to the table as it is the field that is checked and used for sorting. Access will not allow the record to be saved. When you elect to create a new table by adding records in the Datasheet View, a new feature in Access 2007 automatically creates a field named ID that is defined as the primary key. The data type assigned to ID is the AutoNumber type, assigning a sequential number with each new record. Primary Key Button To create a Primary key field for a table, place your cursor anywhere in the field row and click the Primary Key button in the Tools group on the Design tab. Access places a key icon to the left of the Field Name to designate that field as the Key field.
1. While in Design View, place your cursor anywhere in the field row that you have determined to be the Primary Key. 2. Click on the Primary Key button in the Tools group on the Design tab. 3. Click the Save button on the Quick Access bar.
53
1. 2. 3.
Open the Customers table in Design View. Place your cursor anywhere in the C# field row. On the Design tab of the ribbon in the Tools group, click the Primary Key button.
4.
Save the Customers table. (If you are prompted for a Table name to save the table, type Customers.) Click OK. Do not close the Customers table.
5. Follow the steps above to create a primary key for the Transactions table. T# is the primary key for the Transactions table.
We will not create a primary key for Transaction Details at this time.
54
FIELD PROPERTIES
Field Properties Pane The lower half of the work area in Design View displays the available field properties depending on data type. The field property can be used to control the display of the data and for data validation. Special characters, such as dashes in a phone number, are not actually stored in the table. They are used for display purposes only to create a more readable format. If a field property is changed after data has been entered into the table, a warning message is displayed as data could be lost if a field size or data type is modified. Make a backup copy of the table data before making changes to the table structure.
Format
Default Value
55
3. 4.
5. Click the Format property box. Click the pull-down on the far right of the box.
Access 2007 provides a set of predefined date and time formats. 6. Click the Medium Date format. 7. Save the Transactions table.
56
INPUT MASKS
Consistency of Data An input mask establishes a pattern in the Datasheet view which indicates how data is to be entered into the field. Input masks ensure that data is entered consistently into the tables. In addition to specifying the position and amount of characters in a field, you can customize masks that restrict the data entered and whether or not the data is optional. The Input Mask Wizard contains a list of predefined masks provided by Access 2007. You can also customize your own input mask using the Customize Input Mask Wizard. Create Your Own The Edit List button in the Input Mask Wizard allows you to change any of the existing patterns. For example, the pattern for telephone number (602) 255-5545 can be changed to 602-2555545. You can also add new patterns.
1. Open the table in Design view. 2. Place your cursor in the data type column of the field that requires the Input Mask. 3. In the Field Properties pane, click the Input Mask property field box. Click the Build button at the end of the box. The Input Mask Wizard opens. 4. Select one of the predefined Masks. Click the Try It field. Type in a value for the field to examine how the data is displayed. 5. To edit a Mask, select the Mask and click the Edit List button . The Customize Input Mask Wizard window opens. 6. Edit the Input Mask field and click the Close button. 7. Click the Finish button. The Input Mask Wizard closes. 8. Save your design changes.
57
3. Place the cursor in the Input Mask field. Click on the Build button the end of the box. The Input Mask Wizard window opens.
that appears at
4. Select Phone Number. Click the Try It field. Be sure to place the cursor at the beginning of the input box. 5. Type 6025559999. Note that the dashes are inserted for you. However, the dashes are not actually saved in the database. 6. Click the Finish button. The Input Mask Wizard window closes. 7. Save the Customers table.
58
DEFAULT VALUE
Auto Fill The Default Value property is used to define a value that will automatically be entered for the field when you create a new record. The values in existing records are not affected. Although the default value is automatically entered into a field, the value can be modified in datasheet view. Expressions An Expression is a formula that calculates a value. For example, expressions can be created to auto fill the current date or to leave a field blank. A common default value expression is todays date in the date field. In order to have the current date auto fill into a date field, type the following expression into the date fields Default Value property: Date()
1. Open the table in Design view. 2. Place your cursor in the data type column of the field that requires the Default Value. 3. In the Field Properties pane, click the Default Value property field box. Click the Build button at the end of the box. The Expression Builder opens.
4. Create your expression using functions, constants, or operators. When finished, click OK. 5. Create a default value directly by clicking the Default Value field and entering a value or expression. 6. Save your design changes.
59
Books4U also would like to ease the data entry for transactions. The date of the transaction will always be todays date. Rather than typing the date manually for each transaction, setting the default value to Todays date will automatically generate that value in the TDate field. 4. Open the Transactions table in Design view. 5. Place the cursor in the data type column of the TDate field.
6. Use the Expression Builder to set the default. Click the Default Value box in the Field Properties pane. Click on the Build button that appears at the end of the box. The Expression Builder window opens. If you do not know the expression to set todays date default, use the buttons and columns to help. Date is a function, so start by double-clicking Functions and then Built-In Functions. The second column will display the Type options. 7. Select Date/Time as the type. The set of expressions available are displayed in the third column. Double-click the Date expression. The expression Date() is displayed in the Expression Builder window. Click OK. 8. The expression now appears in the Default Value of the field properties. 9. Save the Transactions table. 10. Toggle to Datasheet view to see the automatic entry for the TDate field.
60
VALIDATION RULE
Conditional Test The Validation Rule property is used to enter a conditional test that automatically checks for allowable values for that field. If the data entered fails to satisfy the condition, Access 2007 refuses to accept the data and displays a predefined error message. To customize the error message that is displayed when the validation rule is violated, type a validation message in the Validation Text property box. The Expression Builder helps to build your formula with buttons for common operators. Comparison and Logical operators are also available. When you double-click on the operators in the third column, Access moves them up to the Expression Builder window and starts to build your formula. You add specific information. For example, if your date must fall after 2007, create a formula requiring the date to be greater than 12/31/2007.
Validation Text
Expression Builder
IN
IN (Phoenix, Tempe)
BETWEEN
BETWEEN 1 AND 10
LIKE
LIKE Rio*
61
4. 5.
Save the Transaction Details table. Toggle to Datasheet view. To test the rule, type 0 in the Qty field and press Enter. Access 2007 checks the data entered against the data validation rules for this field. Because the data entered violates the rule of quantity being greater than zero, a predefined message is displayed and Access does not accept the entry. Click OK to correct the entry. To display a message that is easier to understand for the user, customize the message in the Validation Text box of the Field Properties pane.
6. 7. 8.
Enter the number 1 in the Qty field, and toggle back to Design view. In the Validation Text box of the Field Properties pane, type; A number > 0 must be entered. Save the table. Toggle back to Datasheet view to test. Enter a 0 in the Qty field and press Enter. A more comprehensible message for the user is displayed after Access performs the validation test. Click OK. Type a number > 0 in the Qty field.
9.
62
LOOKUP FIELD
Drop-down List Another way to validate data is to restrict the exact values that can be entered. A drop-down list is created for the field and displayed in Datasheet view. Allowing the user to choose from a list will also limit and reduce typing errors for data that must be entered repeatedly. You can further restrict the field to only those items in the dropdown list. Setting the Limit To List property to Yes will cause Access 2007 to display an error message and reject the data if any value not in the list is entered. The Lookup Wizard is used to create the drop-down list. Values for the list can be picked from data in a table or query, or you can enter the values yourself. To launch the Lookup Wizard, click the data type column of the field in Design view. Use the data type pull-down menu to choose the Lookup wizard. Another way to launch the Lookup wizard is to click the Lookup Column button in the Tools group of the Design tab in Design view.
Limit To List
Lookup Wizard
Note: Upon returning to Design view from the Lookup Wizard, you will notice that the data type for the Lookup field is Text. Steps to Create a Lookup Field 1. Open the table in Design View. 2. Click the Data Type column of the field to be created. Click the drop-down menu and select Lookup Wizard. The Lookup Wizard window launches. 3. Specify that the lookup column will accept the values from a table or query and click Next. Access will prompt you for table and field names. Click Finish. OR Specify that you will type in the values and click Next Enter the values in the column provided and click Next. Change the column name, if desired. Click Finish.
63
2.
Click the radio button I will type in the values that I want. Click Next.
3.
Type the six major cities of the Phoenix valley as shown. Use the Tab key to advance to the next entry. If you press Enter before all of your entries are typed, click the Back button. When you are finished with your entry, click Next. You can make a change to the name of the lookup column. Click Finish. You are returned to Design view. The data type for your lookup field is displayed as Text. Save the table.
4. 5.
64
7. 8. 9.
To ensure that these are the only values that will be accepted for the CCity field, change the Limit To List property to Yes. Save the table. Toggle to Datasheet View. Click the pull-down menu in the first row for CCity. The list of accepted values is displayed. Click on any cell to close the list.
10. Click the CCity field box. Type Gilbert and tab to the next cell. 11. Access 2007 checks the data entry with the list of allowable values. The following message is displayed when the value was rejected.
12. Click OK. 13. Use the pull-down menu to choose a city on the list. Type number 9 in the C# field. 14. Save the Customers table.
65
3. 4. 5.
Change the Allow Value List Edits property to Yes. Save the Customers table. Toggle to Datasheet view. Right-click any record in the CCity column and then click Edit List Items on the shortcut menu.
6.
Add Gilbert to the bottom of the list and then click OK.
66
Options
1. On the External Data tab, in the Import group, select the file format of the source file. The Get External Data dialog box will open. 2. Specify the location of the source data. 3. Select the option for importing, appending, or linking to the source file. Click OK. 4. The Wizard will guide you to complete the import procedure.
67
1. 2.
Close all tables. Check that you have three tables; Customers, Transactions, and Transaction Details. If you do not see them, click the pull-down menu on the Navigation pane and select Object Type. On the External Data tab on the ribbon in the Import group, click the Excel button. The Get External Data Excel Spreadsheet wizard opens.
3.
4.
In the File Name box, specify the Excel file that contains the data. Use the Browse button to locate the Customer Data file in the Access 07 Class folder on your Desktop.
68
7. 8.
The next window states that Access will use the column headings found in the Excel worksheet as field names for the database table. This is a default action. Click Next. Before Access imports the data, it gives you one last chance to change the table name. Leave the name as Customers and Click Finish. Do not save the import steps. Click Close.
9.
10. Open the Customers table in Datasheet view to examine the data. Toggle to Design view to check formatting. Delete test rows.
69
20. Finally, import data into the Transaction Details using the same Append procedures as outlined above. Use the Browse button to locate the Transactions Data file in the Access 07 Class folder on your Desktop. 21. The data destination is the Transaction Details table. 22. The Excel worksheet that contains the data is the Transaction Details worksheet. 23. Check the data in both Datasheet and Design view of the Transaction Details table.
70
71
31. In this window, we define a primary key for our table. From past discussions, it is necessary to set a primary key to ensure that all records in the table are unique. It is never a good idea to allow Access to add the primary key keep control of your data at all times. For the Book data, the ISBN number is a unique key that has already been provided through standard coding. Click the middle radio button to choose the primary key. Use the pull-down menu to select the ISBN number. Click Next.
32. The final window allows us to name our new table. Type Books. Click Finish. 33. Do not save the import steps. Click Close. 34. Open the Books table. While in Datasheet view, resize the columns to display all data. Notice that all columns except QtyOH and Price are in text format. Check that QtyOH is in number format and Price is in currency format; toggle to Design view by clicking on the Home Tab, View button. 35. P# is the Publisher number of the book. Notice that P# is repeated several times in the Books table. To have access to the rest of the Publisher information, we will import the data. 36. Follow the same procedure above to import the Publisher data. Use the Browse button to locate the Book Data file in the Access 07 Class folder on your Desktop. Select the Publishers worksheet. 37. Set P# as the primary key and name the new table Publishers. 38. Open the Publishers table. Check that the data type formats are both text format.
72
Appending Records
Previous Versions
Skipping fields & records Relationships Table Definition Record Source objects
Lookup Fields
Subforms/Subreports
Queries
73
2. On the External Data tab on the ribbon in the Import group, click the Access button. The Get External Data Access Database wizard opens. 3. In the File Name box, specify the Access file that contains the data. Use the Browse button to locate the Employee Data 2007 file in the Access 07 Class folder on your Desktop. 4. To specify the data destination, click the radio button to Import tables, queries, forms, reports, macros, and modules into the current database. Because we currently do not have a table created to accept this data, Access will create the table. Click OK.
74
6.
7. 8. 9.
Do not save the import steps. Click Close. Open the Employees table in Datasheet view to examine the data. To toggle to Design view to check formatting click the Home tab and then the View button on the ribbon.
10. Note that the Title field is a Look Up field. E# is set as the primary key field. 11. Open the Emails table to examine the data in both Datasheet and Design views. 12. Close the Employees and Emails tables.
75
76
CREATING RELATIONSHIPS
Related Data Our Books4U database consists of several tables of related data. It is essential to separate the data into multiple tables to reduce unnecessary data redundancy and to decrease possible errors when adding to or modifying the database. The next step in the process is to establish table relationships that will ensure the accuracy of the data when generating reports or requesting information. Data may be retrieved from several tables to generate a single request. Linking the tables together to retrieve the required data creates the relationship. Related tables are linked through a common field. Depending on how the tables are related will determine the type of relationship required. Note: The linking field may not be the only field that the two tables have in common. To avoid confusion, give the linking field the same name in both tables. Referential Integrity When creating relationships, one table is typically the primary table with the second being the related table. When the tables are joined based on a common field between the two, Access ensures the integrity of the data. For example, Order information (related table) for a Customer (primary table) will not be allowed into the database unless the customer exists. In other words, only customers in your database are allowed to have orders. Trying to find or reference a non-existing customer for an order would create an orphan order. Referential integrity is used to prevent orphans and keep references in sync so that the above situation never occurs.
Linking Tables
Types of Relationships
Relationship One-to-one One-to-many Description The common data appears only once in both tables. The common data appears once in the primary table, but many times in the related table. The common data can appear many times in both tables. A third table must be created to reduce the redundancy of the data and to create two one-to-many relationships.
Many-to-many
77
The Design tab is activated. In the Relationships group, click the Show Table button. 3. 4. 5. The Show Table window opens. On the Tables tab, select Employees <shift> Emails to select both tables and click the Add button. Click Close. Both tables are displayed in the Relationship layout area. Click and drag the edges of the tables to expand them if necessary to view all field names. The common field in both tables is Employee Number. Note that the field name does not have to match in both tables. Position the mouse pointer over E# in the Employees table list box, hold down the left mouse button, drag the pointer to Employeeid in the Emails table list box, and release the mouse button. The Edit Relationships dialog box appears. Note the One-to-One relationship type. Access determined the relationship type based on the common field that was used to join the tables. E# in the Employees table is related to employeeid in the Emails table. 6. Click the Enforce Referential Integrity box. Click Create. Save the relationship. For each employee there is one and only one email address. Each email address belongs to one and only one employee.
78
79
NOTES
80
Customers
Books
Linking Fields
In the Customers table, ISBN is the linking field with the Books table. To retrieve more information about the books that Abgail and Hugo have purchased, we take the ISBN in the customer record and use it to look-up the ISBN in the book table. Conversely, the Books table uses C# as the linking field to the Customers table. To retrieve the names of the customers who have purchased a book, we take the C# in the book record and use it to look-up the C# in the Customers table. The challenge created by this design is the large amount of redundant data created. For every book that Hugo purchases, the entire record of information for Hugo must be duplicated. Similarly, for every customer who purchases No Excuse, the entire record of information for the book No Excuse must be duplicated. The possibility of creating errors when duplicating the data or for modifying the data is vast. For example, a change in Hugos address would require a change in every record that the address appears. If one record is missed, the integrity of your data has now been violated.
Redundant Data
81
Foreign Keys
Looking closer at the tables in our Books4U database, we see that the Transactions table was created as the junction table to relate Customers and Books. The Transaction Details table reduces the data redundancy that would have been created if that information were left in the Transactions table. We now have several one-tomany relationships replacing our many-to-many relationship.
The relationship between Transactions and Transaction Details was created in the previous exercise. We will now create the relationship between Customers and Books using Transactions and Transaction Details as the junction tables.
82
7. Click the Enforce Referential Integrity box. Click Create. 8. The Books table can be related to Customers through the Transaction Details table. The Books table and the Transaction Details table have ISBN in common.
83
14. Add Shippers and Publishers to the relationship window. Click the Show Table button in the Relationships group. On the Tables tab, select Publishers <shift> Shippers to select both tables and click the Add button. Click Close. 15. Move the Shippers table list box below and to the right of the Transactions table list box. These two tables have S# in common. Position the mouse pointer over S# in the Shippers table list box, hold down the left mouse button, drag the pointer to S# in the Transactions table list box, and release the mouse button. Click the Enforce Referential Integrity box. Click Create. 16. Move the Publishers table list box below and to the right of the Books table list box. These two tables have P# in common. Position the mouse pointer over P# in the Books table list box, hold down the left mouse button, drag the pointer to P# in the Publishers table list box, and release the mouse button. Click the Enforce Referential Integrity box. Click Create. 17. Move the table list boxes in the relationship window so that the relationship links are visible and not crossing over each other. (See diagram, next page same as handout)
84
18. When you have the tables positioned so that all relationships are visible and no lines are crossed, Save the relationship diagram. 19. To delete any relationship, right-click the relationship line and select Delete or leftclick the relationship line and press the Delete key. You will get a warning message from Access to confirm the delete action. 20. To edit any relationship, right-click the relationship line and select Edit Relationship or double-click the relationship line. The Edit Relationships window opens. 21. After making modifications to the relationship diagram, save the diagram. 22. To print your report the relationship window must be open. On the Database Tools tab, click the Relationships button in the Show/Hide group. The Design tab is activated. On the Design tab in the Tools group, click the Relationship Report button. 23. The report format opens and the Print Preview tab is active. In the Page Layout group, change print orientation to Landscape to fit the diagram to the page. The Margins button allows you to modify the layout further if needed. Click the Print button. 24. Close the relationship window.
85
NOTES
86
CASCADE OPTIONS
Referential Integrity When creating relationships, we have the option to enforce referential integrity. This ensures data validity across tables by preventing orphan records and by keeping references synchronized so that there is no data that points to non-existent records. In our Books4U database there is a one-to-many relationship stated between the Customers table and the Transactions table. Before we can add a transaction record, the customer referred to in C# must exist in the Customers table. Similarly, we cannot delete a customer record if there are related transactions for that customer; it would cause orphan transaction records (transactions for a nonexistent customer).
Orphans
Two additional options are dimmed until you turn on referential integrity: Cascade Update Related Fields and Cascade Delete Related Fields. Checking these options will instruct Access to change a record in a related table if you make a change in the primary table. You may encounter a situation where there is a valid need to change one side of a relationship. To keep the data consistent, Access will automatically update the affected rows in the related table as part of a single operation. When you check the Cascade Update Related Fields option, Access ensures that the update is completed in full so that the database is not left in an inconsistent state. You might need to delete a row and all related records. For example, if we deleted a customer from the Customers table, all related transactions will be automatically deleted from the Transactions table (and all details of the transaction from the Transaction Details table) to make certain that no orphan records remain. Use the Cascade Delete Related Fields for this task.
87
4. Click OK.
88
7. Click the collapse indicator (-) for transaction T0111. 8. To select the record, click in the gray column to the left of the expand indicator for transaction T0111. 9. In the ribbon on the Home tab in the Records group, click the Delete button. Access displays a warning message. Click Yes.
10. Open the Transaction Details table. The result of deleting transaction T0111 from the Transactions table cascaded down to also delete any related records in the Transaction Details table. The Cascade Delete Related Fields option ensures that no
orphans exist. 11. Closing and re-opening the Transaction Details table will erase any records flagged for deletion.
89
NOTES
90
QUERIES
Retrieve Data A query is an Access object designed to retrieve data from one or more tables or queries. A query is much like a filter, but unlike a filter, a query can extract data from multiple sources. The query can be created for various purposes; from a simple selection of a field to complex conditional statements or calculations. Access includes the Simple Query Wizard to assist in creating an uncomplicated query. As you create the query, Access generates a series of instructions to find and retrieve the desired data. When the data is found, it is displayed in Datasheet view. When you save the query for future viewing, Access does not save the Datasheet view of the results. Access saves the instructions to retrieve the data. This ensures the most current view of the data at any given time. The instructions are displayed in SQL view. Because the result of a query is a table, queries can be queried. Access retrieves the queried data first, and then will retrieve data based on those results. New Query On the Create tab in the Other group, there are two options for creating a new query; the Query Wizard and Query Design. There are four options included in the Wizard.
Query Simple
Allows You To Select fields from multiple tables and queries. Does not allow specific criteria for the selection. Calculate totals such as sum, average, and count, and then group them. Find duplicate field values. Find records in a table with no related records in another table; for example customers with no transactions.
Crosstab
91
5. In the next window, keep the default choice to view Details. Click Next. 6. Name the query Books Qty & Price. Click Finish.
7. Close the result window. The result instructions are automatically saved.
92
5. Name the query Repeat Customers and click Finish. 6. The result displays the C# and date of each transaction for repeat customers.
7. Close the result window. The result instructions are automatically saved.
93
4. The next window requests the linking field between the two tables. Select E# for both tables. Click Next.
5. Double-click EFName, ELName, HDate, and Title in the Available fields list to add the data to the Selected fields list. These fields will be in the query result. Click Next. 6. Name the query Employees Not Selling Books. Click Finish.
7. Close the result window. The result instructions are automatically saved.
94
Query Types
1. On the Create tab in the Other group, click the Query Design button. The Query grid and Show Table windows display. 2. From the Show Table window, select the desired table(s). Click the Add button for each table. Click Close. 3. From the table(s) field list, double-click the required fields to move them down into the query grid. Select the fields in the order you want them to appear in the datasheet. 4. Enter Criteria to restrict the data retrieved. Use the Sort feature to order the data. Click Show to display the field. 5. Save and name the new query. Toggle to Datasheet view.
95
Close all database objects. In the ribbon on the Create tab in the Other group, click the Query Design button. The Show Table dialog box opens. (we used this dialog box to create our relationship
diagram)
3.
Select the tables or queries where the required data resides. ISBN, Title, and Author are in the Books table. Publisher Name is in the Publishers table. Select the Books table, press and hold the Ctrl key, and select the Publishers table. Release the Ctrl key. Click Add. Click Close. The top portion of the query window shows the table field lists and the relationships between the tables. The bottom portion, or design grid, represents the columns in the query results that will be displayed in datasheet view. Place the field names on the grid in the order that you want the fields displayed in the query results. Double-clicking the field name in the table field list adds the field to the grid columns.
4.
Double-click the ISBN field in the Books field list. Double-click Title and then double-click Author. Publisher name comes from the Publishers field list. Doubleclick PName. The grid displays the field names and table names of the required data. We have all of the required fields. We must now tell Access to display the results alphabetically by book Title. Click the Sort row in the Title column. Choose Ascending from the drop-down menu.
5.
96
7.
When you save the query, Access does not save this result. The instructions that were automatically generated to run the query are saved. If another book published by Wildside Press was added to the Books table immediately after we ran this query, we would want to see that book in the result the next time we requested the data. By saving the instructions, every time we request this data, Access will run the instructions to renew the result, thus ensuring that the most current data is displayed. 8. On the Home tab in the Views group, click the drop-down list and select SQL View.
The instructions to create the query are shown above. When you save the query, it is these instructions that are saved. When you click the query name in the Navigation Pane, Access retrieves this set of instructions, executes them, and displays the result. 9. Save the query by clicking the close button query Wildside Press Books. on the query window. Name the
97
98
9.
When creating this query, it is necessary to include the CCity field in the query grid to restrict the results to Chandler customers. However, as the results show, CCity is an unnecessary duplication. We know that the city will be Chandler as this is the only city we were searching. The CCity field can be hidden in the Datasheet View. 10. Toggle back to Design View. 11. Uncheck the Show box in the CCity column. Toggle to Datasheet View.
12. Save the query by clicking the close button on the query window. Name the query Late Chandler Order.
99
NOTES
100
Expressions
1. On the Create tab in the Other group, click the Query Design button. The Query grid and Show Table windows display. 2. From the Show Table window, select the desired table(s). Click the Add button for each table. Click Close. 3. From the table(s) field list, double-click the required fields to move them down into the query grid. Select the fields in the order you want them to appear in the datasheet. 4. Enter Criteria to restrict the data retrieved. Use the Sort feature to order the data. Click Show to display the field. 5. In a blank column of the criteria grid, enter an expression in the Field row. 6. On the Query Tools Design tab in the Show/Hide group, click the Property Sheet button. In the Format property box, use the pull-down menu to display field formats. Click the appropriate format. Click the close button at the top right of the Property Sheet task pane. 7. Enter sort and criteria information for the new field, if desired. Toggle to Datasheet view. 8. Save and name the new query.
101
5.
6.
On the Query Tools Design tab in the Show/Hide group, click the Property Sheet button. In the Format property box, use the pull-down menu to display field formats. Select Currency. Click the close button at the top right of the Property Sheet task pane. Toggle to Datasheet View.
7.
Save the query by clicking the close button on the query window. Name the query Qty * Price.
102
103
Run to Update
To run an Action query, first change the query type by clicking the appropriate button on the Query Tools Design tab, Query Type group. In the Results group, click the Run button. Clicking the Run button will update the values in the database. Once you create and run an update query, you cannot undo the changes, therefore use with caution. It is a good idea to make a copy of the table(s) first and practice your update query before running the query on the original table.
Append
Make-table Delete
104
7.
If we simply toggle to Datasheet View, we do not see the results of the query as with the Select query. What is displayed is the data that will be changed. In order to update the values, we must Run the query.
105
On the Query Tools Design tab in the Results group is the Run button. Notice that the symbol identifying the Run action is an exclamation mark ( ! ). Also notice that the exclamation mark is included on all Action query buttons. All Action queries must be Run before the changes take place in the database.
8.
On the Query Tools Design tab in the Results group click the Run button. Access displays a warning message that data will be updated and that the operation cannot be undone. Click Yes.
9.
To view the results of the update, open the Publishers table. Simon & Schuster is now the PName for publisher #324.
10. It is not necessary to save this query. Close the query window. Click No.
106
107
5.
Toggle to Datasheet View. Verify that the email address is the correct address for that employee. To do this, compare the employeeid and E# fields. They should match.
When Access combines data from two tables, it will join the tables based on the relationship in our relationship diagram as shown above the query grid. In this case, the linking fields are employeeid/E#. Access will join these fields based on an exact match of the data contained in the fields. (Notice that the names of the fields do not have to match.)
6.
Toggle back to Design View. Now that youve verified that the employeeid fields match, you no longer need the employeeid field from the Emails table. Delete it by clicking the area in the grid directly above the employeeid field name to select the column and pressing the Delete key. Toggle back to Datasheet View. Your result now shows the original Employees table including the email field. Save the query by clicking the Save button on the quick access toolbar. Name the query Employees & Emails. Leave the query open in Design View.
7.
We now want to replace the original Employees table with the query result that we just created. As a query, the result data is not stored only the instructions to re-create the query are stored. We want the results to be stored as the original table, so we have to make our query a table. 8. In the ribbon on the Query Tools Design tab in the Query Type group, click the Make Table button. The Make Table dialog box opens. In the Table Name textbox, name the new table New Employees. Click OK.
108
10. Examine the new table. On the Navigation pane, double-click the New Employees table. 11. We now want our New Employees table to be the original; all subsequent queries will now be based on this table. Currently, we have queries in Books4U that are based on the old Employees table. We need to change the names of the tables to reflect the change in data. 12. Close the New Employees table. 13. Right-click the Employees table in the Navigation pane. Select Rename from the drop-down list. Rename the table Old Employees. 14. Right-click the New Employees table in the Navigation pane. Select Rename from the drop-down list. Rename the table Employees. 15. Open the Employees table in Design View. Set E# as the primary key. Save the table. Close the Employees table. 16. Delete the Old Employees table. Right-click the table in the Navigation pane. Select Delete. Click Yes to destroy all relationships to the Old Employees table. 17. Check the relationship diagram. On the Database Tools tab in the Show/Hide group, click the Relationships button. The relationship between Employees and Transactions has been deleted. We need to recreate it. 18. Position the mouse pointer over E# in the Employees table list box, hold down the left mouse button, drag the pointer to E# in the Transactions table list box, and release the mouse button. Click the Enforce Referential Integrity box. Click Create. 19. Close the Employees & Emails query. Click Yes to save the changes. Close the relationship layout. Save the changes.
109
3. 4. 5. 6. 7. 8. 9.
10. On the query grid in the Criteria row of the CCity column, type Scottsdale. This is the specific data we are seeking. 11. On the Query Tools Design tab in the Query Type group, click the Delete button. The Delete property now appears on the grid. The default instruction for this property is Where. The instruction that will be executed is; delete all records from the Copy of Customers table where the CCity data = Scottsdale.
110
13. Click the Close button the query1 window. Click No to save the changes. 14. In the Navigation pane, double-click the Copy of Customers table to open it. 15. Examine the data. Notice that the 7 Scottsdale records have been deleted. Again, this is a permanent deletion. 16. Click on the Close button on the Copy of Customers table. 17. In the Navigation pane, right-click the Copy of Customers table. On the pull-down menu, left-click Delete. Click Yes to delete the table from the database.
111
CALCULATING AGGREGATES
Expressions In a previous section we saw that expressions can be used in a query to create calculated fields on a single record. The calculated field is derived from other fields and is not stored in the database. With aggregate functions such as Sum, Avg, Min, Max, or Count Access groups records and then performs calculations on the group. When an aggregate function is used, Access displays one row in the query result datasheet for each group. The aggregate is considered a summary of the group. Access assigns column headings in the query results datasheet using the function name, the word Of, and the field name from which the function has been derived. For example, adding the data in the Sales column would have a heading; SumOfSales. A new feature in Access 2007 allows you to include an aggregate function on your database tables using the Totals button on the ribbon. The totals row appears beneath the asterisk (*) row. The aggregate function on database tables will total selected columns of the entire table. You cannot calculate totals based on a specific data item. For example, you cannot count total sales for a particular book. Once you have defined aggregates for your table, they can never be removed. They can however, be hidden from view. The Totals button acts as a toggle between hidden aggregates and visible aggregates. Totals in Queries Design View An aggregate function can also be performed on one or more columns of a query result set without having to change the design of your query. Calculating totals for queries is more flexible; data can be categorized into groups and totals can be calculated for each group. Calculating total sales for a particular book is possible in this case. Use the Totals button in Design view to add a Totals row to the query grid. Several aggregate options are available to choose from.
Aggregates
Column Headings
112
1. 2.
Close all database objects. Make a copy of the Transaction Details table. Single-click on the Transaction Details table in the Navigation Pane to select it. Click the Office button and select Save As from the drop-down menu. Click Save Object As. In the Save As dialog box, the Save Transaction Details To textbox defaults to the name, Copy of Transaction Details. Click OK. The table opens in Datasheet view. On the Home tab, in the Records group, click Totals.
3. 4.
The Totals row appears beneath the asterisk (*) row. In the Totals row, click the down arrow in the column that you want to calculate. 5. 6. Click the Totals row in the Qty column. Click the down arrow and select Count. Click the Totals row in the Price column. Click the down arrow and select Sum.
Once a totals row is created, it can never be removed. Instead, you hide the row. When you display the row again, Access remembers the function that you applied to each column in your datasheet and the row appears in its previous state. 7. Note that the Totals button you clicked to create the totals row is active (orange). To hide a totals row, click the Totals button (it acts as a toggle). Access removes the totals row.
8.
113
114
10. In the ribbon on the Create tab in the Other group, click the Query Design button. The Show Table dialog box opens. 11. Click the Qty * Price query. Click Add. Click Close. In this query, we are looking for total sales for each transaction. The data comes from the same source, however, we need to group the transaction data and sum the total sales. Include the Customers name in this list to compare with the previous result. 12. Double-Click the T#, CLName, and Total Price fields from the Qty * Price field list. The fields appear in the query grid. 13. On the Query Tools Design tab in the Show/Hide group, click the Totals button to add a Total row to the query design grid. 14. In the Total row of the T# field, Group by is the correct option. Access will group the data by Transaction number. Keep the default settings. 15. In the Total row of the CLName field, Group by is the correct option. Because there is only one customer per transaction, Access will group the data by Transaction number and customer name together. Keep the default settings. If you do not specify the Group by option for customer name, Access will display the following message:
16. Click the Total row of the Total Price field. The pull-down menu contains the list of aggregate options. Select Sum. Toggle to Datasheet View to see the results. 17. Close the query. Save it as Total Sales by Transaction.
115
FORMS
Many Uses A form is a database object that you can use to enter, edit, or display data from a table or a query. You can use forms to control access to specific rows or fields of data. Controls can be added to a form to automate frequently performed actions. The form is a different view of your database: forms can be designed for effective retrieval of data through automated searches; a visually attractive form is easier and more enjoyable to use; a form can also include verification controls to help prevent incorrect data from being entered. Form Views Access allows database users to view forms in different ways. This involves viewing a form during design, runtime, or a combination of both. The views are available on the Format tab in the Views group on the ribbon. .
View Types
View Design
Description
A detailed view of the structure of your form. It contains the Header, Detail, and Footer sections. A wide variety of controls, such as graphic images and labels can be added in Design view. The form is not actually running in this view, so you cannot see the underlying data while you are making design changes. The form is running in this view so you can see the underlying data on which the form is based. You can use this view to add records, edit records, or navigate through a table. Changes to the design of the form cannot be implemented in this view. The form is running in this view so you can see the underlying data on which the form is based. 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 useful view for setting the size of controls or performing almost any other task that affects the appearance and usability of the form.
Form
Layout
116
Description Creates a form with one click and uses all the fields in a table. The form will display in Layout view. Displays the form in Form view and Datasheet view simultaneously. Form view can be used to edit a record while the Datasheet view can be used to navigate to a record. Multiple records from the table are displayed in the form as a spreadsheet. Creates a form in Pivot Chart view. This allows a three-dimensional analysis of data. Creates a form from scratch. The form is developed by adding and positioning controls, including a field, on a blank form. The wizard takes the user through a series of steps to specify the layout and background themes for the form. Helps to create a more detailed structure of your form in Design view. With this tool, you have a wider variety of controls you can add to your form. You can also resize form sections such as the Header or Detail section, and you can edit the text box control sources without using the property sheet.
Split Form
Blank Form
Form Wizard
Form Design
117
Access creates the form using all fields in the table in a vertical layout. The records are displayed in Layout View with the Form Layout Tools Format tab active. Remember the views are available on the Format tab in the Views group. You also have quick access to the form views at the right end of the status bar in the lower right corner of the screen.
Form View Design View
Layout
You will recall that the Employees table is related to the Transactions table in a one-tomany relationship. Access adds the datasheet to the form that is based on the related table. You can delete the datasheet from the form if you do not need it; in Layout view, click anywhere in the datasheet and press the Delete key. Do not delete the related datasheet.
118
4.
5.
Click the E# textbox. Enter a new record using the following data. Tab to advance to the next field.
E# EFName ELName EMiddle BDate HDate Title Email 999-999-999 (dont include dashes) Your first name Your last name Middle initial Your birth date Todays date Salesperson Your email address
6.
Click the first new record of T# in the datasheet. Enter a new related record using the following data. Tab to advance to the next field. Press the Enter key to accept the changes.
T# C# TDate S# T0111 699-74-5211 (dont include dashes) Today (autofilled) S30
7. 8. 9.
Close the form. Click Yes to save. Name the form Employee Form. Click OK. In the Navigation pane, double-click the Employees table to open. Note the new record that was added through the form. In the Navigation pane, double-click the Transactions table to open. Note the new record that was added through the form datasheet.
10. Reopen the Employee Form by double-clicking it in the Navigation pane under Forms objects. 11. Click the last record button on the form Record Navigation bar. Close all objects
119
Form View
Record 26 of 31
Datasheet View
Access creates the form and displays it in Layout view. Recall that in Layout view, you can make design changes to the Form while it is displaying data. With a split form, you can also make data changes to the Datasheet that will reflect back to the Form. (Allow Edits must be set in the Split Form property sheet press F4) 3. Click the Layout View button on the Status bar in the lower right corner of the screen. 4. Locate and select the record for Isabel Quail in the Datasheet. The record is displayed in the form above. 5. Change Isabels first name to Connie. Press the Enter key. The changes sync to the form above. 6. On the form, click the C# field. Left-click the right orange border of the textbox for C# and while holding down the mouse button, drag the mouse to the left to shorten the textbox. Repeat the steps for the CCity field.
120
7. Close the form. Click Yes to save the changes. Name the form Customers Split Form.
2. To add a field to the form, double-click the S# field or click and drag it to the form. To add all remaining fields from Shippers at once, hold down the CTRL key and click each field. Drag them to the form. As with the Form and Split Form tools, each form created is a series of objects called controls. Each field from the table has a Label Control and a Text Box Control. The label control contains the field name. The text box control is the field placeholder where data is retrieved from the database and can be entered or edited. The controls can be moved, resized, formatted, or deleted from the form.
121
A forms style can be modified after the form has been created by changing the color theme and fonts. Tools in the Controls group on the Format tab can be used to add a logo, title, page numbers, or the date and time to a form. Well customize the form next.
122
12. Click the Save button on the Quick Access Toolbar. Name the form Shippers Form. Close the form.
123
3. Click the Add All Fields button to move all of the fields in the Available Fields list box to the Selected Fields list box. Click Next. 4. With Columnar already selected as the form layout, click Next. 5. Using the scroll bar, preview each styles colors and backgrounds in the preview window. Click Flow to select it, and then click Next. 6. Name the form Books Form. Click Finish. Switching to Design view will add a wider variety of controls to the form. On the Design tab in the Controls group, the number of available controls is displayed. We will use several of these controls to modify our Books form.
124
125
13. While holding down the Shift key, click ISBN, Title, Author, and P# Label controls to select them. Notice a broken border around the corresponding Text Box controls. Position the cursor on the bottom right corner of any of the selected Label controls until the cursor changes to a diagonal double-arrow. Left-click and drag the mouse straight up (1/4 inch). All Label and Text Box controls are resized. 14. Place the Publishers name below the P#. The publishers name is in the Publishers table. To display the Field List pane, click the Add Existing Fields button in the Tools group on the ribbon. The Field List pane opens. 15. In the middle section of the Field List pane (Fields available in related tables), click the plus sign (+) next to the Publishers table. The fields from the Publishers table are now visible. 16. Double-click or click and drag the Pname field to the form. The Label and Text Box controls appear on the form. Close the Field List pane. 17. Resize each control by clicking the right and bottom borders of the control and dragging the borders to match the controls already on the form. Reposition the controls if necessary. 18. Click the Form View button on the Status bar in the lower right corner of the screen to view the changes. Click back to Design View. Add a reminder message at the bottom of the form. To do this, we need a Label control. Before we add the control, expand the Detail section of the form. Roll the cursor to the area between the Detail and Form Footer sections. When the cursor changes to a doublearrow, left-click and drag the line down to expand the detail section.
126
19. To add a Label control, click the Label button in the Controls group on the ribbon. If you do not see the Controls group, make sure you are in Design View. 20. Position the mouse pointer below the Pname controls. The mouse pointer changes to +A. Click and drag the mouse pointer to create a control that matches the size of the Pname Text Box control. Release the mouse. The Label control is created and a blinking cursor is positioned to the top left of the control. 21. Type Orders are completed on the last day of each month in the Label control. Click a blank area of the form to deselect the label control. 22. Click the label control again to activate the Font group to change the italic and bold font properties. Align the control in the center of the form. Click the Form View button on the Status bar in the lower right corner of the screen to view the changes.
23. Click the New Record button on the Record Navigator bar. Access creates a blank record. Enter information for a fictitious book with you as the author. Type 100 for P#. As you tab to Pname, you will notice that Access auto fills the data from the database. (one-to-many relationship between Books and Publishers) 24. Save the form. Close the form.
127
NOTES
128
SUBFORMS
Form tool Sub datasheet When working with related data tables, you often need to view data from more than one table or query on the same form. For example, customer information and all data for each order placed by the customer is on the same form. You will recall that Access 2007 creates a similar display with the Form tool; if the form data has a one-to-many relationship with another table/query in the database, Access adds a datasheet to the form that is based on the related table/query. A subform is a form that is inserted in another form called the main or primary form. In a one-to-many relationship, the main form shows the one side of the relationship, while the subform displays the many side. Access creates two forms; one for the main form, and one for the subform. The main form and subform are linked so that the subform displays only records that are related to the current record in the main form. For example, when the main form displays employee information, the subform displays only the transactions for that employee. To create the subform, all relationships must be established first. This allows Access to automatically create the links between the main form and subform. When identifying the tables that will be used in the main form/subform, there does not need to be a direct one-to-many relationship between the tables. Access will create the subform with tables that have a many-to-many relationship, utilizing the modified design of one-to-many relationships that were created to resolve the many-to-many relationship issue. For example, a customer can purchase many book titles and a book title can be purchased by many customers. In creating the main form/subform, Access utilizes the intersection table used to form the one-to-many relationships.
Intersection Tables
Sub-Forms
Many-to-Many Relationship
129
130
15. Click the record navigation bar of the main form (Employees) to locate the fifth record. The subform shows that Leadership was sold twice by Bullock. To get more information about the sale, we need to add the purchase date. The purchase date was on the list of required fields to be placed on the Employee form. However, the purchase date (TDate) is in the Transactions table. If we had selected TDate while creating the form, it would have required three tables and the form wizard would have created a form with two subforms. We need only add TDate to the current subform. To accomplish this task, we need the Field List pane.
131
132
CONTROL LAYOUTS
Arranging the Display When forms are created, Access arranges the label and text box controls into one of two control layouts: Tabular and Stacked. Control layouts are guides that align the controls horizontally and vertically to give your form a uniform appearance. You can have multiple control layouts of either type on a form. In tabular 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 with a label to the left of each control. Stacked layouts are always contained within a single form section. Access automatically creates stacked control layouts when you create a new form by clicking Form in the Forms group on the Create tab, or 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 first selecting the control and then clicking either the tabular or stacked buttons in the Control Layout group on the Arrange tab.
Tabular Layouts
Stacked Layouts
Control layouts can be switched from tabular to stacked, or from stacked to tabular. Select all of the controls of the layout. On the Arrange tab, in the Control Layout group, click the layout type you want. Removing a control from a control layout allows you to place it anywhere on the form without affecting the positioning of any other controls. Once you select the control(s) you want to remove from the layout, click Remove in the Control Layout group on the Arrange tab.
133
134
6. Click through the records on the record indicator bar to identify the books that need to be reordered. 7. Save the form. Close the form.
135
NOTES
136
REPORTS
Summarizing Data Record Source When making decisions, we can summarize the data that is viewed and manipulated on forms by generating reports. Like forms, Access 2007 offers several types of reports. A report contains information that is pulled from tables or queries, as well as information that is stored with the report design, such as labels, headings, and graphics. The tables or queries that provide the underlying data are the reports record source. If the fields that you want to include all exist in a single table, use that table as the record source. If the fields are contained in more than one table, use one or more queries as the record source. Those queries may already exist in your database, or you may need to create new queries specifically to fit the needs of your report. Access provides several views to edit and modify reports. Design, Report, and Layout views operate the same as they do with Access forms. Design view displays the detailed structure of your form. While you can modify the report sections and controls, you cannot see the data. In Report view, the data is displayed but changes to the design of the report cannot be implemented. Layout view allows you to view the data and make changes to the report design. A forth view, Print Preview, displays the appearance of your report when printed on paper. In this view, you can set report page layouts before printing the report.
Report Views
Blank Report
Report Wizard
Report Design
137
6.
7. 8. 9.
138
GROUP REPORTS
Categorizing Data Information is often easier to understand when it is divided into groups. For example, a report that groups sales by city can highlight areas that may need more of a companys advertising dollars. Adding totals for each group in the report will also help with data analysis. A basic grouped report can be created by using the Report Wizard. A group is a collection of records, plus any introductory and summary information displayed with the records. A group includes a group header, possible nested groups, detail records, and a group footer. When you group a report based on a field, Access creates a group header section for that record. Group headers are matched with group footers. When a calculation is performed for a field, the calculation is performed for each of the groups and the result is displayed in the group footer. To create useful reports, placement of controls in a header, detail, or footer section determines how Access calculates results. The following describes each section type.
Groups
Report Sections
Description Printed once at the beginning of the report. Usually includes logo, title, and date. This header prints before the page header. When a calculated control is placed here, the value is calculated for the entire report. Printed at the top of every page. Printed at the beginning of each new group of records. Usually the group name is placed here. When a calculated control is placed here, the value is calculated for the current group. Printed once for every row in the record source. Controls that make up the main body of the report are placed here. Printed at the end of each group of records. Use controls to print summary information for the group here. Printed at the end of every page. Print page numbers here. Printed once at the end of the report. Print report totals or other summary information for the entire report.
Detail
Group Footer
139
For each customer, the report contains customer name and sales transaction number. A sequence of repeating items purchased on the transaction is next. The transaction purchase is totaled and if the customer has purchased again, the transaction data and purchase data is displayed for a second time. All purchases for the customer are then totaled. The process is repeated for the next customer. The report ends with total sales of purchases by all customers. The report contains a date, title, and page number that are all repeated on each page.
140
5. We do not want to add any other grouping levels. Click Next. 6. We do not need any sort order on the detail information. Click Next. Note: The Customer, Transaction, and Total Purchase totals on the sketch are calculated fields. We will create those directly on the report.
141
We need to make a number of adjustments to our report to satisfy the requirements given to us by Ana Rivera, the manager. The report requires aggregate totals for each transaction and customer, and a report total. We must add the report title, date, and page number to all new pages. Each customer must go on a new page. Other cosmetic modifications can be done later.
142
CONTROLS
Enhancing Reports 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. Controls can be selected, sized, aligned, and moved. We previously visited controls when creating forms. The controls placed on a form or report are classified into three types, depending on the type of data they are associated with. These three types are summarized below.
Description The source of data is a field in a table or query. Bound controls are used to display values from the database. The values can be text, dates, numbers, Yes/No values, images, or graphs. A Text Box is the most common type of bound control. A control that doesnt have a source of data. Unbound controls are used to display information, lines, rectangles, and images. The Label controls are a type of unbound control. The source of data is an expression rather than a field. An expression is a combination of operators, control names, field names, functions that return a single value or constant values. An expression can use data from a field in the reports record source or from a control on the report.
Unbound control
Calculated control
When you create a report, it is most efficient to add and arrange all the bound controls first as they are created directly from the reports record source. The unbound and calculated controls can be added to complete the design by using the control tools on the Design tab in the Controls group. Control Source A field can be bound to a control by either typing the field name in the control itself or in the box for the ControlSource value in the controls Property Sheet. The property sheet defines the characteristics of the control, such as name, data source, and format. To display the property sheet in layout or design view, press F4. In design view only, click the Property Sheet button in the Tools group on the Design tab.
143
3. 4.
If needed, close the Shutter Bar on the Navigation pane for a larger viewing area. Notice that the title, date, and page numbers must be repositioned. Click the Title label control in the Report Header section to select it. Position the mouse pointer inside the orange border of the title control until the pointer changes to a double arrow. Click and drag the mouse pointer until the title is centered above the data on the report. Release the mouse pointer. The Date control is located in the Page Footer section. We need to move it up to the Report Header section. Click the date control to select it. Position the mouse pointer inside the orange border of the date control until the pointer changes to a double arrow. Click and drag the mouse pointer through the various report sections until the date is above and to the right of the title in the Report Header section of the report. Release the mouse pointer. The Page Number control must be centered on the page. Click the page control in the Page Footer section to select it. Position the mouse pointer inside the orange border of the page control until the pointer changes to a double arrow. Click and drag the mouse pointer until the page number is centered. Release the mouse pointer.
5.
6.
144
8.
9.
10. Click the Title control, hold down the Shift key, and click the Date control. Both controls are selected. Right-click the mouse, select copy. Click in the Page Header section. Right-click the mouse and paste. Reposition the Title and Date controls. 11. As you preview the changes, you will notice that the Title and Date appears twice on the first page. This is because we left the controls in the Report Header section. In Design View, Report Header Section, select the Title and Date controls. Press the Delete key. Collapse the Report Header section by placing the mouse pointer just above the Page Header border until the mouse control turns into a double arrow. Click and drag the Page Header border until it touches the Report Header.
12. Adjust the control boxes to fit the text. The Date control can be shortened by clicking the Date control. Click the bottom and right orange borders and drag to shorten. You can change the font size of the title and fit the control box to accommodate it. 13. Save the report. We will now add the totals to the report.
145
Access 2007 permits the calculation of a sum, average, count, or other aggregates 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. 1. Click the Design View button on the Status bar in the lower right corner of the screen. 2. Click the Total Price text box in the Detail section to select it. On the Design tab in the Grouping & Totals group, click the Totals pull-down menu and select Sum. Access adds a calculated text box control to the Report Footer section, which creates a grand total. Access also adds group footer sections to Transaction and Customer groups and places a total in each footer group.
3.
4. 5. 6.
Click the Report View button on the Status bar in the lower right corner of the screen. Examine the data. The report is very similar to the sketch provided. We need to add labels to identify each aggregate total. Click back to Design View. Add a Label control to the T# Footer section. On the Design tab, in the Controls group, click the Label control.
146
8.
Click the Report View button on the Status bar in the lower right corner of the screen to view the changes. The report is easier to read with the label controls in place.
9.
Save the report. The next step is to limit one customer per page of the report.
147
2. Close the Print Preview. Click the Design View button on the Status bar in the lower right corner of the screen. 3. Customer information first appears in the CLName Header. Each time Access detects a customer in the record source that is different from the last, we want this section to print on a new page. Right-click the CLName Header and then click Properties. The Property Sheet opens. 4. Click the All tab. Click the pull-down arrow for the Force New Page property. We want to force a new page before the customer information is printed. Click Before Selection. 5. Close the Property Sheet. 6. Click the Print Preview button on the Status bar in the lower right corner of the screen. 7. Advance to the next page using the Record Navigator bar. 8. Customer information is no longer split across multiple pages. 9. Save the report.
148
6. Note that when we create a Text Box control, Access will also create a Label control for us. In this case, we dont need the Label control. Click the Label control, and then press the Delete key.
149
150
151
NOTES
152
PRINT A REPORT
Preview Before Printing Typically, reports are created to be printed. Occasionally, a report contains so much information that the data to be displayed exceeds the size of the print area. If the data overflows the page margins, blank pages may result. You must define the page setup options before printing your report to reduce these problems. Before printing, it is good practice to preview your report. Reports are displayed in Print Preview, so you have previously viewed them in this format. The Page Setup tab will be used to define page options before printing. Page Setup Options The Page Setup tab is automatically enabled in the Design, Print Preview, and Layout views. Under this tab, in the Page Layout group, is a collection of tools that help you set the paper size, report margins, and choose page orientation style. After you make a change, use the Record Navigation buttons to view several pages to ensure that formatting problems were not created on later pages.
Permits You to Choose the paper size Print the report along the length of the paper Print the report along the width of the paper Set the margins. Three options are available; Normal, Wide, and Narrow. Display the margins in the report window. Print the data without the column headers Divide the page into two or more columns Open the Page Setup dialog box; it contains the above options on tabbed pages.
To send the report to the printer, click the Microsoft Office button and then click Print. When the print dialog box displays, enter your choices for printer options, print range, and number of copies. Click OK.
153
3. 4.
Click the Landscape button to change the page orientation. Click the pull-down on the Margins buttons to display margin settings. The Page Setup button displays the set up options on tabs.
5. 6. 7. 8.
When you have made all necessary changes, click Print on the Print Preview tab. Options for printing are the same as with all Microsoft applications. We will not print this report. Click Cancel. Close the report.
154
1. Select the table or query to be merged with the form letter. 2. On the External Data tab, in the Export group, click More and then select Merge it with Microsoft Office Word. The Microsoft Word Mail Merge Wizard opens. 3. Choose to create a new document or link to an existing document and click OK. The document opens. 4. Follow the steps of the wizard. On the Mailings tab in the Write & Insert Fields group, click the Insert Merge Fields button to insert Access fields into the document. 5. To complete the mail merge, click to step 6 of the process. 6. To personalize your letters, click Edit individual letters in the Wizard pane. 7. Save or print the form letters. Click the Microsoft Word Close box.
155
4. In the Select Microsoft Word Document dialog box, locate and select the Sales Promotion Letter file from the Access 07 Class folder. Click Open. The document opens in MS Word. The Mail Merge pane is open on Step 3 of 6. In step 3, we are creating the link between the data source in Access and the Word document. This link is automatically created because we started the wizard from Access. Under Select recipients, Use an existing list is selected, and the name of your data source is displayed under Use an existing list.
(Click Edit recipient list if you want to customize the contents of the table or query. You can filter, sort, and validate the data. Click OK to continue.)
5. Click Next: Write your letter at the bottom of the Mail Merge pane to continue.
156
157
18. Using the vertical scroll bar, scroll down to view all letters.
19. Close the window. Click No to save the changes. Close MS Word. Click No to save changes. 20. MS Word closes and you are returned to the Access window.
158
Label Wizard
1. Click the object in the Navigation pane that contains the fields to be printed on the label. 2. On the Create tab, in the Reports group, click the Labels button. 3. The Label Wizard is launched. 4. Choose label type, font size and color. 5. Select the fields that will be displayed on the label. 6. Select a field to sort the labels. 7. Name the label report. Click Finish.
159
3. 4.
Choose label size, 5383. In the Filter by manufacturer text box, use the pull-down to select Avery. Select English in the Unit of Measure field, and Sheet feed in the Label Type field. Click Next.
5.
At the Font name text box, use the pull-down font size to 10. Click Next.
Choose the fields you want on your labels from the Available Fields list, and doubleclick them to add to the Prototype label box. Create your address label as you would a regular address, with spaces and commas.
160
10. Sort the labels by double-clicking the CLName field. Click Next. 11. In the last wizard window, name the report Customer Labels. Click Finish. 12. The report opens in Print Preview layout.
161
NOTES
162
1. Click the desired object for export in the Navigation pane. 2. On the External Data tab, in the Export group, click the Excel or Word button. 3. The Excel Spreadsheet dialog box or the RTF File dialog box opens. 4. Click the Browse button. 5. At the File Save dialog box, navigate to desired folder, then click Save. 6. Click the desired options. 7. Click OK.
163
7. Save the Excel file. Close the file. Do not save the export steps. Click Close.
164
The file extension .rtf signifies that the file is saved in rich-text format, which preserves formatting such as fonts and styles. 6. Save the Word document. Close the file. 7. Click the close button on the Export RTF dialog box.
165
8. Examine the list to be sure that all objects were transferred. 9. Close the database.
166
167
168
NOTES
169
Appendices
Additional Features in Access 2007
170
Offline Help
Help information is available without internet access, although fewer resources display help topics when using offline help.
171
1. Double-click Contacts in the Featured Online Templates section in the center pane. 2. Click the browse button next to the file name text box in the right pane. 3. At the File New Database dialog box, navigate to the Access 07 Class folder, add your initials to the file name and click OK. 4. Click the Download button. Access downloads the database template from Microsoft Office Online and displays the Contact List form along with the Access Help window. 5. Close the Help window and click the shutter bar to open the Navigation pane. 6. Click the pull-down arrow to the right of Contacts Navigation and then click Object Type at the drop-down list to display all database objects. 7. You can now open any object in Design view or Layout view to make changes as appropriate for your application.
172
4. In the Link Tables dialog box, select the Products table. Click OK to finish. 5. Access creates the linked tables. Open the table in datasheet view.
Linked Table
173
174
INDEX
Access 2007 Objectives .................................................................. 1 Action Queries (Delete) .............................................................. 106 Action Queries (Make-Table)..................................................... 103 Action Queries (Update) ............................................................. 101 Action Queries In Design View.................................................. 100 Add A Custom Field To A Report.............................................. 144 Adding Controls in Forms .......................................................... 120 Adding Criteria Queries................................................................ 93 Adding Totals To A Report In Design View .............................. 141 Aggregates (In Queries).............................................................. 110 Aggregates (On Tables) .............................................................. 109 Aggregates .................................................................................. 108 Apply An Autoformat To A Report............................................ 146 Applying And Removing Filters................................................... 22 Autoformatting Reports .............................................................. 146 Blank Form Tool......................................................................... 117 Calculating Aggregates (In Queries) .......................................... 110 Calculating Aggregates (On Tables)........................................... 109 Calculating Aggregates............................................................... 108 Calculations Queries ..................................................................... 98 Cascade Options ........................................................................... 84 Clone The Database .................................................................... 162 Compact And Repair................................................................... 169
175
INDEX
Conditional - And/Or Queries....................................................... 95 Conditional Formatting............................................................... 130 Control Layouts .......................................................................... 128 Controls....................................................................................... 138 Create A Form (Adding Controls) .............................................. 120 Create A Form (Blank Form Tool) ............................................. 117 Create A Form (Form Tool)........................................................ 114 Create A Form (Form Wizard) ................................................... 119 Create A Form (Split Form Tool) ............................................... 116 Create A New Database ................................................................ 42 Create A Report (Report Tool) ................................................... 133 Create A Table .............................................................................. 44 Create Mailing Labels................................................................. 154 Creating Many-To-Many Relationships ....................................... 78 Creating One-To-Many Relationships.......................................... 76 Creating One-To-One Relationships ............................................ 75 Creating Relationships.................................................................. 74 Creation Tools (Forms)............................................................... 113 Custom Field In A Report........................................................... 144 Database Concepts .......................................................................... 2 Database Objects............................................................................. 8 Database Templates .................................................................... 167 Datasheet Formatting .................................................................... 26
176
INDEX
Datasheet View ............................................................................. 12 Default Value ................................................................................ 56 Defining Fields ............................................................................. 46 Delete Queries ............................................................................ 106 Deleting Objects In Access........................................................... 34 Design View Queries ............................................................ 92, 100 Design View Report Totals ........................................................ 141 Design View.................................................................................. 30 Designing The Database ............................................................... 36 Displaying Records In A Subdatasheet ........................................ 14 Edit Or Replace Data .................................................................... 18 Editing And Finding Records ....................................................... 16 Exploring An Existing Database................................................... 10 Export 2007 Database To Access 2003 ...................................... 161 Export A Report To Ms Word .................................................... 160 Export A Table To Excel ............................................................ 159 Exporting Data ............................................................................ 158 Field Properties ............................................................................. 52 Filter By Form............................................................................... 24 Filtering By Selection ................................................................... 23 Filters (Applying and Removing) ................................................. 22 Find Duplicates Queries................................................................ 90 Find Unmatched Queries .............................................................. 91
177
INDEX
Finding And Editing Records ....................................................... 16 Form Tool ................................................................................... 114 Form Wizard ............................................................................... 119 Formatting The Datasheet............................................................. 26 Forms (Adding Controls)............................................................ 120 Forms (Blank Form Tool)........................................................... 117 Forms (Form Tool) ..................................................................... 114 Forms (Form Wizard) ................................................................. 119 Forms (Split Form Tool)............................................................. 116 Forms Creation Tools ................................................................. 113 Forms .......................................................................................... 112 Group Reports............................................................................. 134 Import Data From An External Source......................................... 64 Importing Data From An Access Database .................................. 70 Importing From An Excel Spreadsheet......................................... 65 Index ........................................................................................... 170 Input Masks................................................................................... 54 Integrate Programs Exporting Data ......................................... 158 Link To An External Table ......................................................... 168 Lookup Field................................................................................. 60 Mailing Labels ............................................................................ 154 Make-Table Queries .................................................................. 103 Many-To-Many Relationships...................................................... 78
178
INDEX
Modifying The Report (Property Sheet)..................................... 143 Msword Mail Merge With Access Data ..................................... 150 Objectives ....................................................................................... 1 One-To-Many Relationships......................................................... 76 One-To-One Relationships ........................................................... 75 On-Line Help .............................................................................. 166 Previewing & Printing Formatting The Datasheet .................... 26 Primary Key .................................................................................. 50 Print A Report ............................................................................. 148 Printing & Previewing Formatting The Datasheet .................... 26 Property Sheets ........................................................................... 143 Queries (Delete) .......................................................................... 106 Queries (Make-Table)................................................................. 103 Queries (Update)......................................................................... 101 Queries In Design View.............................................................. 100 Queries .......................................................................................... 88 Query Wizard (Find Duplicates)................................................... 90 Query Wizard (Find Unmatched) ................................................. 91 Query Wizard (Simple)................................................................. 89 Relationships........................................................................... 32, 74 Replace Or Edit Data .................................................................... 18 Report Printing............................................................................ 148 Report Tool ................................................................................. 133
179
INDEX
Reports (Report Tool) ................................................................. 133 Reports ........................................................................................ 132 Select Queries (Adding Criteria) .................................................. 93 Select Queries (Calculations)........................................................ 98 Select Queries (Conditional - And/Or) ......................................... 95 Select Queries In Design View..................................................... 92 Simple Queries.............................................................................. 89 Sorting Records............................................................................. 20 Split Form Tool........................................................................... 116 Start Access..................................................................................... 4 Subdatasheets................................................................................ 14 Subforms (Enhance The Appearance) ........................................ 126 Subforms ..................................................................................... 124 Tables Getting Familiar With Datasheet View.......................... 12 Tables Taking Control With Design View ................................ 30 Tables............................................................................................ 44 Templates.................................................................................... 167 The Access User Interface .............................................................. 6 Totals In A Report In Design View ............................................ 141 Update Queries .......................................................................... 101 Use Msword Mail Merge With Access Data .............................. 150 User Interface.................................................................................. 6 Validation Rule ............................................................................. 58
180