Você está na página 1de 35

BUILDING APPLICATIONS WITH MICROSOFT ACCESS 2003 PART 1 CREATING THE DATABASE

Introduction This document introduces techniques for building a database application using the relational database management system called Microsoft Access 2003 You will undertake a case study, and design concepts and implementation techniques will be introduced as you work. Prerequisites You will need to be familiar with using a mouse, keyboard and the Windows desk top. Ideally you should have some prior experience of Microsoft Access 97, 2000, XP, or 2003. However, you will have the opportunity to work through examples to cover introductory topics.

Contents 1 2 Introduction Case Study 1 1 1 2 2 3 4 6 6 9 11 12 13 13 14 15 15 15 17 18 18

2.1 What you need to know about cats 2.2 What you need to know about owners 2.3 Analysis 2.4 Database object naming conventions 3 Creating the database 4 Tables 4.1 Creating a Table with Table Wizard 4.2 Modifying a Table Design 4.3 Moving around a Table 4.4 Entering Data in a Table 5 Getting Started with Forms 5.1 Creating a Data Entry Form with Form Wizard 5.2 Entering Data with Forms 6 Relationships 6.1 Types of relationships 6.2 Adding another table 6.3 Enter Cats data 7 Queries What are Queries?

Doc. 5.115a

Building Access 2003 Applications

Building a Query to use in a Report Reports

18 20 20 20 21 21 22 23 23 23 24 26 27 28 28 28 28 30 31 31 33

8.1 What are Reports? 8.2 Building and Modifying a Report 8.3 Selecting Objects 8.4 Sorting Data in a Report 8.5 Changing Object Properties 9 Implementing a new requirement 9.1 9.2 9.3 9.4 9.5 9.6 9.6.1 9.6.2 9.7 9.8 9.9 9.10 9.11 The new requirement Analysing the new requirement Logical Design of Table Bookings Logical Design of Form Bookings Form Create Bookings Table Create FormBooking Create a standard form Add a combo box for Owner's Pick List Combo Boxes Selecting objects Setting the control source of a combo box Add Text Boxes with Calculated controls Testing the combo box

About this Document Words that you type or choose are in bold type, e.g. Choose Programs from the Start menu. Keys that you press are shown in small capitals e.g. press ALT. Press KEY1 + KEY2 means press both keys together e.g. press CTRL + Z Press KEY1, KEY2 means press each key consecutively e.g. press A, B. General guidelines on how to perform a task are indicated by bulleted lists using symbol. Note that these are not tasks for you to perform now they are the advice for you to follow later when you need to work things out for yourself. Exercises for you to practice as you work through the notes are labelled Exercise, e.g. Exercise 1 Importing Database Objects. The steps that you do to complete the exercise are marked by round bullets (). Hints and tips are indicated by If you are not very familiar with using computers then you should pay particular attention to the hints and tips. Even if you are fairly familiar with using a computer you should read them, as they can provide explanations of why you do something, or they may suggest an alternative way of doing things.

ii

Building Access 2003 Applications

Doc. 5.115a

1 Introduction
The aim of this document is to introduce you to some techniques for creating a user interface for Microsoft Access 2003 applications. An application is a database (or databases) that the designer has organised so that the users can focus on the job at hand, without needing any knowledge of Access. The interaction between the user and the application is known as the User Interface. Forms play a central role in the user interface. The user does not need to know about the underlying tables, queries, macros and modules. However, you, as the designer will need to know about these topics. The material does not cover the topics of macros and writing code for Visual Basic procedures in great detail. However, you will have an opportunity to see examples, and to compare the advantages and disadvantages of code and macros. Work through the notes in sequence. Read the hints and explanations before you attempt the exercises. The exercises need to be completed in the order that they appear, as they depend on objects 1 that have been created in previous exercises. Before you build a database it is essential to analyse the problem. This is true even for a simple database such as a list of names and addresses and becomes even more important when you are designing an application based around a database. So before you start to build the database you will need to read the case study notes. As you are working through the exercises you will need to refer back to the notes on the requirement.

2 Case Study
The owner of a boarding cattery has asked for a database to help her manage her cattery. As the cats leave it to their owners to arrange their cattery bookings, she needs to store information about Owners. She would also like to display information about the cats dietary needs. She normally feeds a different variety of food each day, but needs to know if any cats currently in the cattery are unable to eat that variety, and make provision for the exceptions. So she needs to store information about Cats. She would also like to be able to remind owners when their cats are due for vaccination against infectious diseases. 2.1 What you need to know about cats All cats boarded at the cattery require an up to date vaccination certificate against various cat diseases. Healthy cats are fed a varied diet of white meat, red meat, fish, and dried cat food. Older cats may have to avoid red meat, or dried food. Some cats develop eczema if fed on fish A cat has only one (official) owner When a cat first comes to the cattery, it is given a unique Cat Identifier. The cat occupies a pen or run, which has a unique run number. The cat prefers its owner to live at a fixed address.

Database components in Access 2003 are referred to as objects.

Doc. 5.115a

Building Access 2003 Applications

2.2

What you need to know about owners An owner may own one or more cats Some owners like their cats to occupy the same run, as it is cheaper They like to give their cats names.

2.3 Analysis The important thing at this stage is not knowledge of computers, but an understanding of the problem. As this is not a course in Systems Analysis, the analysis has been done for you, so that you can practise using Microsoft Access 2003 straight away. Entity is the term used in database design for things that we need to keep information about. Entities in the real world map to tables in the database so we will start with two tables in our database called Owners and Cats. The Attributes 2 of an Owner are the contact details. We will give each owner a unique identifier, and store the owners first and last names. We also need the address, town, county, postcode, and phone number. Note that a Cat is NOT an attribute of an Owner. Cats can exist independently of their Owners. The attributes of a Cat are its Cat Identifier, name, age, sex, vaccination date, and special dietary needs. In order to identify the Relationship between a cat and its owner we will use the owner identifier as a field in the Cats table, as well as in the Owners table. It is good practice, when designing a database, to use unique identifiers. This is because there may be several people with the same name & initials. We could identify them by name and address. However, since we want to use the owners identity to link to the Cats table, it would mean that we had to update the Owners and the Cats tables if the owner moved address. Examples of unique identifiers that you will probably have come across are your National Insurance number or your ITS Username. These do not change however many times you move. As cats are even less likely to have unique names than their owners, we will give each cat a unique Cat Identifier. We have identified two entities, which tells us what tables to use, and we have identified their attributes. Attributes map to fields in our tables. The Owners table will have the fields shown in Table 1, and the Cats table will have the fields shown in Table 2. We have also identified a relationship between the Cats and Owners, so we have included the common field OwnerId in both tables. Later you will learn how this common field can be used to link tables. Note that Identifier is usually abbreviated to Id when used in field names. A table is a structured way of representing data. Ive used Microsoft Word Table 1 and Table 2 to illustrate the structure of the two tables that we need for the Microsoft Access tables. The fields in Access are the column headers in the Word table. The

Attribute - A quality or characteristic inherent in or ascribed to someone or something. (http://www.yourdictionary.com/)

Building Access 2003 Applications

Doc. 5.115a

database table will hold data values for First name, Last Name etc., for example Bill Smith. These will be rows in the table. In database terms these are called records. Table 1 Fields for Owners Table
OwnerId Firstname Lastname Address City County Post Code Phone Number

Table 2 Fields for Cats Table


CatId OwnerId Name Age Sex VacDate DietNotes

2.4 Database object naming conventions Database development includes naming object files consistently. Naming conventions are not mandatory, but they do make your work consistent. If you plan on sharing a database with others, then it is a particularly good idea to use them. The usual convention is that all objects should have a descriptive tag, placed at the start of the object name. The most commonly used convention is the Leszynski/Reddick Guidelines for Microsoft Access. You can find out more about these at http://www.microsoft-accesssolutions.co.uk/naming_conv.htm However, the choice of naming convention is not as important as making sure that you do implement a naming strategy. We will use more meaningful tags for the object names, e.g. table instead of tbl. This will allow you to familiarise yourself with the objects used in Microsoft Access Try to use identical names for objects and field names to the ones used in the notes. Avoid spaces in names because some database sysems may not permit them. If you are consistent about spelling then Microsoft Office 2003 will do some of the work for you. For example relationships between tables can be implied by using identical field names in the two tables.

Doc. 5.115a

Building Access 2003 Applications

3 Creating the database


The database file that you will now create is the container for the objects (tables, forms etc. that you will create.). Exercise 1 Create a new database Login to the computer and start Microsoft Access 2003 Select Create a new file from the Microsoft Access Getting Started pane on the right of the Window. , as shown in Figure 1 Figure 1 Creating A New Database

Click on Blank Database In the File New Database dialogue box make sure that you have selected the My Documents folder on your N: drive, and replace db1.mdb in the Filename box with fads.mdb 3 . Your New Database box should look something like Figure 2 Click on Create

The most important thing about a database is to give it a memorable, meaningful name. FADS stands for Feline Animals Database System.

Building Access 2003 Applications

Doc. 5.115a

Figure 2 New Database Dialogue Box

Now that you have created the container you can add objects to it, for example tables, forms, queries and reprts. You do not need to create a new database for each new object.

Doc. 5.115a

Building Access 2003 Applications

4 Tables
4.1 Creating a Table with Table Wizard When you create a new database the database window looks something like Figure 3. There are no objects in the database. Objects such as forms, reports and queries are all based on Tables, so first we must create a table. Notice that Microsoft Access 2003 has greyed out the Open and Design buttons, as the only action available to you at this point is to create a new table. Tables are the foundation of your database. Without tables no other objects can exist, so you must create the tables first Buttons that are greyed out in Windows are not available in the current context. Figure 3 New Database Window

We will use the Microsoft Access 2003 table wizard to create the Owners table. When you create a new table using table wizard you will be shown a list of sample tables. Some tips on using table wizards: Choose a table that most nearly matches the entities that you have identified in your analysis. As Owners and Customers are likely to have a lot of attributes in common, for example names and addresses, the Customers table is a good place to start. In the next exercise you will start with the Customer table & customize it to meet the requirement that we have identified.

Building Access 2003 Applications

Doc. 5.115a

There are no spaces in the field names. This is because some computer systems do not recognise spaces. By omitting them in Microsoft Access 2003 we will make it easier to re-use our design on other systems if we need to in future. However, you may want to use spaces where it will make it easier for human users of the database to understand what is happening, for example labels on forms and reports, user specifications to be agreed with your end users. All of the attributes (represented by fields) that we need appear in the Sample Field list, although some of the names will need to be modified. To include a field from the sample field in the New Table Field list click on >. If you make a mistake, click on < to remove the field. This is useful if you get fields in the wrong order. You can simply remove them and add them back in the required order.

Exercise 2 Create a new table Click on the New button in the new database window. The New Table box appears. Select Table Wizard from the list of New Table options Click on O.K. Table Wizard will show a list of sample tables. Click on Customers in the Sample Table list. Click on CustomerId in the Sample fields, then click on > to add it to Fields in My New Table. Do this for the rest of fields that we identified in section 2. (That is Firstname, Lastname, Address, City, County, Postcode, PhoneNumber) Use CustomerId for OwnerId, CustomerFirstName for FirstName, CustomerLastName for LastName, BillingAddress for Address and StateorProvince for County Click on CustomerId in Fields in my new table, then click on the Rename Field button and rename the CustomerId field to OwnerId. Repeat this for CustomerFirstName etc., until all the field names match those that we identified in our requirement. Your Table Wizard dialogue box should now look like Figure 4 (see next page)

Doc. 5.115a

Building Access 2003 Applications

Figure 4 Table Wizard New Table

Click on Next>. Table wizard will ask you what you want to call the table. Type TableOwners. Note that Microsoft Access 2003 also allows you to choose a Primary Key. For this database we can let Microsoft Access 2003 do that for us, so leave that option unchanged. Figure 5 Naming a table

Building Access 2003 Applications

Doc. 5.115a

Click on Next>. Table Wizard will ask you if you want to enter data or modify the design. We do need to modify the design slightly, so click in the Modify Table Design option button. Click on Finish>

4.2 Modifying a Table Design Table Wizard opens the table in design view, which allows you to make changes to the design. The design view of the Owners table looks similar to Figure 6. If you want to make more changes to the design at a later stage, you can go to the design view. You can do this by selecting the database window, selecting the table and clicking on the design view button. An alternative method, if you already have the table open, is to use the toolbar buttons. You will see that while we are in design view the datasheet view button is highlighted on the table design toolbar. If we were to switch to datasheet view then the design view button would appear. You can use these buttons to switch between views. If you cannot see a button or toolbar, choose Toolbars from the View menu and make sure that the required toolbar is checked. Figure 6 Owners Table before modification Datasheet view button

In the design view Microsoft Access 2003 allows you to enter and/or edit Field Names, Data Types, Descriptions, and Field Properties.

Doc. 5.115a

Building Access 2003 Applications

You edit text for Field Names and Properties just as you would edit, for example, a filename in a dialogue box. That is, you can select it with the mouse and overtype it, or you can use the cursor movement and delete keys to locate and delete characters that you do not want. You edit Data Types by clicking on the field and selecting a Data Type from the list that drops down. We will look at data types in more detail when we build other tables. If a Field Property is restricted to a fixed set of values, then a downward pointing arrow appears when you click in the field. You can then click on the arrow and select a value from the list. Notice that OwnerID is of data type AutoNumber. Every time we enter data about a new owner, Microsoft Access 2003 will automatically allocate a unique Ownerid and every record will have a unique key. Microsoft Access 2003 allows the database designer to set a field property input mask on data entry fields. Input masks help users to avoid some data entry errors, such as dropping a digit from a phone number. Exercise 3 Modify the Table Design Click in the field for PostalCode to select it. Click in the Field Properties section in the Input Mask row. (make sure General tab is selected). Click on the build button, that is the symbol on the right of the field. Access may ask you if you want to save the table. Click on yes. When the input mask wizard starts click on PostalCode. Figure 7 Input Mask Wizard

In the Try It box type WC1E 7HX. E is not accepted.

10

Building Access 2003 Applications

Doc. 5.115a

Double click on PostalCode and change >LL00 LL to Laaa 0LL (a means an optional letter or digit). Try WC1E 7HXagain. Click on Finish Chose Save from the File menu

If you had finished using the table, you could close it at this stage by choosing Close from the File menu. However, do not close it yet, as we will enter some data in datasheet view before we look at forms to simplify data entry. 4.3 Moving around a Table Before we can enter data we must leave design view, and change to a view called datasheet view. You can use the on-line help to find out how to move (or navigate in Microsoft Access 2003 jargon) between records in the datasheet. Exercise 4 Navigating round a table Click on the drop down arrow next to the View button on the toolbar. Use Hover Help to locate the button. (Hint: it is near the left hand end of the toolbar). Select datasheet view. The table will now look like Figure 8.

Figure 8 Owners Table in Datasheet View

Select Microsoft Access Help from the Help menu. Type Navigate in the box labelled Search for then click on the green button. In the pane labelled Search Results click on Move between records or fields, then click on Moving between records by using navigation buttons in a datasheet or form. A diagram showing how to move around your datasheet appears. Other useful terms to search on are keyboard shortcut and input mask. When you have seen all that you want in the Help windows click the minimise button on the Help Topic Window, and the window will be reduced to a button 11

Doc. 5.115a

Building Access 2003 Applications

4.4

on the taskbar. If you want to refer to that topic again or to go back to other topics, click on the button to restore it. Close the search results pane by clicking on the X in the top right corner of the pane. Entering Data in a Table Exercise 5 Enter Data in a table Enter the data shown in Table 3. Type your data in the fields, using the TAB key to move forward between fields, use Shift+TAB to move backwards. When you have entered the data, choose Close from the File menu. Although Microsoft Access 2003 requires that you to save designs of tables, forms, etc. the data that you enter is saved automatically. Table 3 Owners Data

FirstName LastName Address Alice Brown 1 Oak Crescent Bill Zoe Ann Mary Smith Smith Black-White Green 10 The Street 1 Oxford St. 99 The Lane 77 Wood St

City Welwyn Garden City Stevenage London Hatfield Bennington

County PostalCode PhoneNumber Herts AL10 9BB 01707-765432 Herts Herts Herts SG9 4NM WC3A 9AB AL10 9JB SG5 3BG 01438-123456 0207-1239999 01707-234567 01438-876678

12

Building Access 2003 Applications

Doc. 5.115a

5 Getting Started with Forms


5.1 Creating a Data Entry Form with Form Wizard Later we will look at ways in which forms can include checks on the correctness of the data. For example, when entering cat details, we could use the Owners table to supply a valid list of owners and OwnerIds. Here is a simple example of a form, which does not include any checks. Exercise 6 Create a form Click on the Form button in the database window. Click on the New button in the Form section of the Database Window. In the New Form dialogue box select Form wizard Select TableOwners in the Form Wizard box. (Figure 9) Click on O.K. Figure 9 Form Wizard

Form Wizard will ask you which fields you want in your form. Click on >> to select all fields. The available fields will move to selected fields. Click on Next>. Form Wizard will ask you what layout you want for your form. Choose Columnar layout. Click on Next>. Form Wizard will ask you what style you want. Choose a style. Click on Next>. Form Wizard will ask you what title you want. Type FormOwners in the title box. Click on Finish>. The form appears in Form View, ready for you to enter data.

13

Doc. 5.115a

Building Access 2003 Applications

5.2

Entering Data with Forms Exercise 7 Entering Data into a Table using a Form Press Ctrl+shift +Plus Sign to go to a new record. Enter some more cat owners names and addresses, as shown in Table 4. Use the TAB key to move between fields. Close the owners form by clicking on the Close Button (see left) in the top right corner of the owners form. Open TableOwners and check that the new records have been added. Table 4 Some More Owners

FirstName LastName Address Rose Phil Flower Arrow

City

County

1 The Garden Roseville Roseshire 1 High Rd London

Postal Code RO5 1EE N11 6YU

PhoneNumber 01234 567890 0208 9883210

Note that the form is an alternative way of entering data into a table. Tables hold all the data in Microsoft Access. When you type data in using a form Microsoft Access puts the data into the underlying table on which the form is based. It does not put it into the form.

14

Building Access 2003 Applications

Doc. 5.115a

6 Relationships
6.1 Types of relationships There are three main types of relationship: One-to-one--One record in a table is related to only one record in another table. One-to-many--One record in a table can be related to many records in another table. Many-to-many--One record in a table can be related to one or more records in another table, and one or more records in the second table can be related to one or more records in the first table. In our examples we will use one to many. One-to-one relationships can often be resolved by using one table. Many-to-Many usually require the introduction of a third table as a link between the other two enities. For more information on relationships you should refer to a suitable text book on database design (e.g. Domanski and Irvine see Part 2, Appendix A). 6.2 Adding another table We now need to add another table, to represent the entity Cats. As the Table Wizard did not seem to have any suitable sample tables, we need to design this table ourselves. We need to specify the Field Names, Data types, and Field Properties. The field names are the same as the attributes that we identified in section 2.3, that is CatId, OwnerId, Name, Age, Sex, VacDate, DietNotes. We can also use the field names for our captions, because we chose easily recognisable names for our fields. (We abbreviated some of them so that they will fit better on screens/A4 pages) We will introduce some new data types and field properties. The CatId is an Autonumber in this table, because we want Access to automatically allocate a new Cat Identifier to each new cat. The CatId is known as primary key because it uniquely identifies a record in the table. The OwnerId is given a data type of Number, and Field Size Long Integer. This is important because we want to be able to link cats to their owners. OwnerId in the Owners Table identifies owners, which is of type Autonumber. If we want to link the two tables, then the fields in other tables that are to be linked to Autonumber must be Long Integer Numbers. The OwnerId is known as a foreign key because it is the primary key from a different table. Age is a number. We can reduce the amount of space needed to store this field by giving the field size the property byte. This allows us to store numbers up to 255, and since most cats do not live beyond 20 it will be more than adequate. Sex is a text field. There is a validation rule In ("M","F"). This means that values entered in this field must be in the set M, F. Since this is only one letter, the field size can be set to 1. (The default value for Text fields is 50.) VacDate is of type Date/Time. RunNo is a positive number with field size Byte. Access automatically sets the default value to 0. We will make use of this feature later when we build a query.

15

Doc. 5.115a

Building Access 2003 Applications

DietNotes is a Memo field. Since text fields can be up to 255 characters long, a text field would probably be adequate in this case, but we will use a memo field to show you that it is available. Some keyboard short cuts (see online help for more): You can use the TAB key to move between Field Name and Data Type columns. You can use the F6 key to move between the Field Name/Data Type section and the Field Properties section. You can use ALT + down arrow ( ) to drop down a list. Use the arrow keys to move up and down the list, and press ENTER to make the selection. Exercise 8 Create a new table in Design View Click on the New button in the Tables section of the database window. In the New Table window click on Design View, then click on O.K. Enter the Field names and Data types shown in Figure 10. Figure 10 Cats Table Design View

Captions are set automatically to the field name unless you change them. In the Field Properties box change the properties as follows: For the OwnerId field set field size to Long Integer For the Age field set the field size to Byte For the Sex field set the field size to 1 and the validation rule to In (M, F) For the RunNo field set the field size to Byte. The Field Names and Data Types should now appear as in Figure 10. Save the table as TableCats. Microsoft Access2000 will ask you if you want it to select your primary key. Select Yes

16

Building Access 2003 Applications

Doc. 5.115a

The definition of primary key is " one or more fields whose value or values uniquely identify each record in a table. In a relationship, a primary key is used to refer to specific records in one table from another table. A primary key is called a foreign key when it is referred to from another table." 6.3 Enter Cats data Exercise 9 Enter Data in a table Use the form wizard to create a columnar autoform based on TableCats called FormCats and use it to enter the data shown in Table 5 into TableCats. Close the table and the form

Your Autonumbers may not match mine exactly. If, for example, you make a mistake when entering data and you have to delete a record Microsoft Access 2003 will remove that autonumber as well. An autonumber is never re-used so if you delete one it is gone for good. As Ownerid's were automatically generated you may find yours are slightly different to mine. Make sure that you use your own.

Table 5 Cats Data


CatId 1 2 3 4 5 6 Ownerid Name 1 Tigga 2 Samantha 2 Arabella 3 Tom 4 Blackie 5 Ginger Age Sex 10 m 3f 3f 1m 4m 7m VacDate RunNo DietNotes 16/08/04 6 05/09/04 1 No Fish 05/09/04 1 No Fish 31/07/03 0 01/01/04 0 31/12/04 2 No Red Meat

17

Doc. 5.115a

Building Access 2003 Applications

7 Queries
What are Queries? Another class of database object is the Query. You use queries to view, change, and analyze data in different ways. You can also use them as the source of records for forms and reports. The next example is called a Select Query because we are selecting fields and records from the database. The steps in designing a query are: Say what type of query you want to design. Add the tables that contain the data. Add the fields which contain the data Add criteria that you want to use. Criteria are instructions that you use to tell Microsoft Access which records to display. Building a Query to use in a Report We need to create a report of the dietary needs of the cats that are currently occupying runs. We could simply build the report based on TableCats. The cattery staff could read from the report which cats were in runs (i.e. RunNo > 0). However, as cats normally spend most of their time at home with their owners, there would be more cats NOT in runs than cats in runs. The report would contain much unneeded information. This is confusing and could lead to mistakes. Include the criteria in the design only if it is something that always takes the same value. That is true in this case, because a run number of 0 indicates that the cat is not currently in the cattery. When a cat comes to the cattery, RunNo is updated in the cats table. When it leaves, the RunNo is again updated, this time it is given a value 0. The criteria that we want to use in this query remain constant (RunNo > 0). Later we will used queries that use variable values as criteria, for example a value chosen from a list. The Query By Example (QBE) grid is a graphical interface for creating queries. For more complex queries you can use Structured Query Language (SQL). For an SQL tutorial try http://sqlzoo.net/ Exercise 10 Create a query with constant criteria In the database window click on the Query tab, then click on New. In the New Query box click on Simple Query Wizard, click on OK.. In the Simple Query Wizard box drop down the list of Tables/Queries and choose TableCats. In the Available Fields List choose Name, and click on > to move it to the Selected Fields List. Repeat this for Age, Sex, RunNo, DietNotes. Click on Next>. Make sure that Detail is selected, and click on Next> Give your query the title QueryCatsInRuns. Make sure that Modify Query Design is selected and then click on Finish. The query should appear in Design View. If not, then switch to Design View by clicking on the View button on the tool bar. 18

Building Access 2003 Applications

Doc. 5.115a

In the QBE grid, click in the criteria row in the RunNo column. Type > 0 as the criteria for RunNo. Note that the expression > 0 is not enclosed in [] because we do not want Access to prompt for it when we run the query. Your design view should look like Figure 11.

Figure 11 QBE Grid for CatsInRuns query

From the File menu save your query as QueryCatsInRuns There is a short cut button for running the query on the query design toolbar. Use hoverhelp to locate it. (Hint - it looks like !). Click on the Run Query button. Your Query result should look like Figure 12. Close the query Figure 12 CatsInRuns Query

19

Doc. 5.115a

Building Access 2003 Applications

8 Reports
8.1 What are Reports? The next class of object that we will build is a Report. Reporting is the way in which you choose to present the contents of your database as printed pages. Reports enable you to select which fields will be printed out and what data should be included. Reports can also summarise data in various ways. Microsoft Access gives you the opportunity to design the layout of a particular report including the position of headings, field names, the data itself along with graphics such as pictures and logos. Reports can take their data from tables, or existing queries or queries can be created especially for the report. In order to create a report that uses fields from more than one table a query needs to be created which contains all the necessary fields. You can also use Microsoft Word Mail Merge to customise your own reports, using data from a Microsoft Access database for the merge fields. 8.2 Building and Modifying a Report You can use QueryCatsInRuns as the basis for your report. Although the report generated by Report Wizard will not be exactly as we want it, we will use the Report Wizard to build the report, and then we will modify the design. Exercise 11 Building a report In the database window click on the Reports button, then click on New In the New Report box choose Auto Report Tabular in the report type box. Choose QueryCatsInRuns in the table/query list. Click on O.K. The report appears in print preview. Click on design view button on the tool bar. The report will appear as in Figure 13. Save your report as ReportCatsInRuns Figure 13 CatsInRuns Design View

20

Building Access 2003 Applications

Doc. 5.115a

8.3 Selecting Objects Before you can do anything with an object you have to select it. You select an object by clicking on it when you are in design view. On Forms and Reports you can make Multiple Selection, that is you can select several objects at once. To select several objects located next to each other , hold down the shift key and click on each object in turn. To select several objects that are not next to each other hold down the ctrl key and click on each object in turn An object can have various properties Events, Data, etc. Properties vary for different object, i.e. not all objects will have all properties. 8.4 Sorting Data in a Report When you have selected objects then you can perform operations on them, such as sorting data, or you can change their properties such as fonts, colours, alignment. The data in TableCats on which we based the QueryCatsInRuns is in the order that the cats are added to the database. However, it would be more useful if ReportCatsInRuns was sorted according to RunNo, as the runs with lowest numbers are dealt with first. Exercise 12 Sorting Data in a report Make sure that ReportCatsInRuns is open in design view. Click on RunNo in the detail section. (See Figure 14) Figure 14 Selected Object

Click on the Sorting and Grouping button on the toolbar. The Sorting and Grouping window appears In the Sorting and Grouping Window choose RunNo from the Field/Expression column. (use the to drop down the list of fields). Click on the Close Window button (r) in the Sorting and Grouping Window to close it. (Be careful to close only the window, and not the whole report) Click on the Print Preview button on the toolbar to see a list of cats in runs, sorted in ascending order of run number.

21

Doc. 5.115a

Building Access 2003 Applications

8.5

Changing Object Properties Another change that would improve the appearance is to change the alignment of the Name, Age, and Sex fields. The alignment is a format property of these objects. All objects have properties. If you cannot see the properties window then click the right mouse button. Choose Properties from on the menu that drops down. (See left) To change a property click in the field. Some properties will display a drop down arrow, meaning that you can choose a property from a menu. For other properties you will need to type a value.

Exercise 13 Changing Object Properties Make sure that the report is in Design View. In the detail section of the report select Age, Sex, RunNo (see Figure 15) Figure 15 Selected Details

In the properties window set the text align property (under format tab) for the selected objects to Centre (Figure 16). Repeat this for the page header section Save the report, preview it, and close it Figure 16 Properties Window

22

Building Access 2003 Applications

Doc. 5.115a

9 Implementing a new requirement


Database analysis is done in two parts, the logical design and the physical design. As often happens, the customer did not specify the full requirement at the start of the project. Ms. Twitchett is pleased with the database, and has identified a new requirement. She would now like to use it to keep records of bookings made by owners. The first step is to do an analysis of our data structures (tables) and to identify any additional data database objects that we need to create. 9.1 The new requirement Owners may book more than one visit in advance. Ms Twitchett would like to see: Who made the booking When the cat or cats are due to arrive at the cattery How many days the cats will board for How many cats are to be boarded How many runs are needed The kennelling charge, i.e. use of run and food Heating charge is an optional extra. All cats need it in winter and some older cats may need it at other times. Insurance charge is essential. Total charge for visit. Daily Rates are as follows: Kennelling charge = 2 per run + 2 per cat, i.e. daily rate is calculated by (2*No. of Runs + 2*No of Cats) where '*' is a multiplication symbol. Heating rate = 50p per run Insurance rate = 10p per cat Rates may vary with time. 9.2 Analysing the new requirement First of all let us look at some questions and answers that we need before we attempt to create new objects. Can I generate the report using the information that is already in the database? No, there is no information about bookings in either the Owners table or the cats table. If not, what further information do I need to store? You need to store the booking details, i.e. date, number of nights, number of cats, number of runs, and daily rates. Could I store it by adding attributes (fields) to the existing entities (tables)? As it is the owners who make the bookings for the cats, you might be tempted to add some new fields to the Owners table. Assuming this to be done, could it lead to future problems?

23

Doc. 5.115a

Building Access 2003 Applications

Yes! As there is only one record for each owner, you would only be able to store information about the latest booking. This would not allow owners to book more than one visit in advance. If I decide to add new tables what entities are they representing? Entities represent things. You have seen examples of entities that represented groups of people (Customers, Owners), and of things that are at the core of the business (Cats). A manufacturing or retail business might have an entity for Products. Entities can also represent pieces of paper such as Orders. Similarly in the cattery business you can have an entity that represents Bookings. If I decide to add new tables what are their relationships with other tables? The relationship is between the owner and the booking, not between the cat and the booking. An owner may make one or more bookings. Each booking is made by one, and only one owner. In database design terminology, this is a one to many relationship. What should be the primary key of any new tables? The primary key uniquely identifies the record. We have seen how easy it is to get Access to generate a unique primary key for each record, so we can let Access generate a unique Booking Number. What foreign keys would I need to include as attributes of any the new tables? The relationship is with the owners table, so you should include the foreign key OwnerId. The above analysis suggests that two new objects are required. As none of the existing tables will provide all the information that we need we need to add a table object TableBookings, that will hold data about the bookings. We also need a form object FormBookings that will allow us to enter data into the table. The data type determines how much internal storage is required for the data. To find out about the various data types use Help, type 'Data types, described' in the search box. 9.3 Logical Design of Table Bookings Now that we have identified the need for a table Bookings let us look at the fields that we need in the table, and compare them with the requirement. As with all tables we need a unique identifier. Let us call it BookingId and have Microsoft Access 2003 allocate it automatically. This will be of type autonumber. We need to identify who made the booking. We already have a means of doing this as we have the Ownerid. Just as we used the Ownerid as a foreign key to associate a cat with an owner we can use the Ownerid to associate a booking with an owner. We know that this needs to be of type long integer in order to work with the autonumber Ownerid field in the Owners table. We need to record when the cats are due to arrive at the cattery. Let us call this field CatsInDate. This is of type date.

24

Building Access 2003 Applications

Doc. 5.115a

We need to record how many days the cats will board for. Let us call this field NoOfDays. A field of type integer will allow us to store numbers as large as 32,767. This would allow us to board a cat for 32767/365 years, i.e. 89 years, which is longer than the lifespan of the average cat. So we can save space in our database by storing this field as type integer rather than long integer. However we shouldn't try to save too much space by going for the next size down which is byte data type. This would only allow a cat to stay for 255 days, probably enough for most cat owners, but we'll play safe. We need to record how many cats are to be boarded. Let us call this field NoofCats. Data type byte will allow up to 255 cats to be boarded. Ms Twitchett prides herself on individual service to the cats in her care and wouldn't dream of taking in that number of boarders. So type byte is more than adequate. We need to record how many runs are needed. Let us call this NoOfRuns. Again type byte is adequate for the size of the business. We need to know the kennelling charge. This is something that can be calculated if we know the number of runs, the number of cats, the number of days and the daily rates per run and per cat so there is no need to store it. However, we do know that rates can vary so it would not be a good idea to use constant rates in the calculations. Instead let us store two fields RunRate and CatRate, both of type currency. We can then enter the current rate when the booking is taken and calculate kennelling rate from the following expression. Note the use of * as the multiplication symbol, and brackets to group items. ([RunRate]*[NoOfRuns]+[CatRate]*[NoOfCats])*[NoOfDays] We need to know the heating charge. This is optional. We need to store the HeatRate which is of data type currency. We can use IIf , which is a built in Microsoft Access function that returns one of two parts, depending on the evaluation of an expression. Syntax IIf(expr, truepart, falsepart) Named arguments: expr (Required). Expression you want to evaluate. truepart (Required). Value or expression returned if expr is True. falsepart (Required). Value or expression returned if expr is False. The expression to use is IIf ( [Heating] , [HeatRate] * [NoOfRuns] * [NoOfDays] , 0) We need to know the Insurance charge. This is also easily calculated if we know the rate, so let us have a field InsRate of data type currency. We can then calculate the charge from the expression [InsRate]*[NoOfCats]*[NoOfDays] Note the syntax for the calculated expressions. o Round brackets () are used to group items together and to order precedence in the evaluations. For example Microsoft Access 2003 will calculate the 25

Doc. 5.115a

Building Access 2003 Applications

expression [RunRate]*[NoOfRuns]+[CatRate]*[NoOfCats] and then multiply the result by [NoOfDays] o Field Names are delimited by square brackets[ ] o The arithmetic operators are Multiplication (*), Division (/), Addition (+), Subtraction (-) Before you create the table, we will look at the logical design of FormBookings to see what objects we need on the form. By doing the logical design of this form (which provides the inputs and outputs for TableBookings) we will be doing a check on the table design, which may help us to spot any logical errors in the table structure. 9.4 Logical Design of Form Bookings Form You have created a form FormOwners based on the underlying table TableOwners. Similarly FormBooking is based on the underlying table TableBookings. It needs the following objects BookingNo allows us to see the unique identifier allocated to the booking. Ms Twitchett can, if she wishes, inform the owner of this number. This will be implemented as a text box object. The place from where it gets the data (known as the control source) is the BookingNo field in the underlying table Bookings. OwnerId allows us to record which owner made the booking. We will introduce an object type known as a combo box that will allow us to generate a drop down menu (called a pick list in Access jargon) of owner's names CatsinDate allows us to record when the cats are due to arrive at the cattery. A textbox object with control source CatsInDate. NoOfDays allows us to record how many days the cats will board for. A textbox object with control source NoOfDays NoOfCats allows us to record how many cats are to be boarded. A textbox object with control source NoOfCats NoOfRuns allows us to record how many runs are needed. A textbox object with control source NoOfRuns Heating allows us to record whether heating is required. A textbox object with control source Heating RunRate allows us to record the current daily charge per run. A textbox object with control source RunRate CatRate allows us to record the current daily charge per cat. A textbox object with control source CatRate HeatRate allows us to record the current daily charge for heating. A textbox object with control source HeatRate InsRate allows us to record the current daily charge for insurance. A textbox object with control source InsRate A text box KennelCost displays the calculated kennelling charge. A text box HeatingCost displays the calculated heating cost. A text box InsuranceCost displays the calculated Insurance Cost. A text box TotalCost displays the calculated total cost. You should now compare the proposed design with the new requirement, to confirm that we have got all the required information.

26

Building Access 2003 Applications

Doc. 5.115a

9.5 Create Bookings Table You already know how to create a new table in design view, because you created TableCats (Section 6.2). Use the field names as captions. Table 6 summarises the information that you need in order to create the table. Table 6 Bookings Table FieldName BookingNo OwnerId CatsInDate NoOfDays NoOfCats NoOfRuns Heating RunRate CatRate HeatRate InsRate DataType Autonumber Number Date/Time Number Number Number Yes/No Currency Currency Currency Currency FieldSize Long Integer Integer Byte Byte

Exercise 14 Create the Bookings Table Create a new table called Bookings with the field names and data types given in Table 6. Note that there are no spaces in the field names. In datasheet view enter the sample data shown in Table 7 and close the table. Table 7 does not show the BookingId as Microsoft Access will insert this for you. Table 7 Booking Data Owner Cats In No of No of No of Heating Run Cat Rate Heat Ins Rate Id Date Days Cats Runs Rate Rate 7 05/04/04 3 2 1 Yes 2.00 2.00 0.50 0.10 2 03/03/04 9 2 1 Yes 2.00 2.00 0.50 0.10 6 03/03/04 15 1 1 No 2.00 2.00 0.50 0.10 2 26/08/03 3 2 1 Yes 2.00 2.00 0.50 0.10 9 03/02/04 10 2 1 Yes 2.00 2.00 0.50 0.10 4 31/01/04 3 1 1 Yes 2.00 2.00 0.50 0.10 6 03/03/04 3 1 1 Yes 2.00 2.00 0.50 0.10 Yes/No fields such as heating may be displayed as check boxes, ticked for Yes, clear for No. When entering data you can toggle between ticked and clear by pressing the space bar. You can change this setting by going to design view in your table. In the Field Properties for the field click in the Lookup tab and chose the Display Control property that you want.

27

Doc. 5.115a

Building Access 2003 Applications

9.6

Create FormBooking

9.6.1 Create a standard form The first step is to create a standard form based on TableBookings. You can then add additional objects. If you cannot remember how to use the form wizard to create a standard form please refer to Exercise 6. When you use Form Wizard you are asked to choose the table or query from where the form object's data will come. You are also asked to choose which fields you want on your form. Form Wizard then creates text boxes on the form that use these fields as their control source. Refer back to the section on logical design of the form to identify the fields that you need. Exercise 15 Create a standard form Create a columnar form called Formbookings, based on TableBookings. Go to design view.

9.6.2 Add a combo box for Owner's Pick List 9.7 Combo Boxes You can use a Combo Box on a form to locate a record in a table. A Combo Box is a control, similar to a list box and a text box combined, in which you enter a value or select an item from a list. One example of a List Box that Windows users should be familiar with is the Look In box on the Insert File dialogue box in Word for Windows and other Windows applications. You use the drop down arrow to display the list in a combo box, just as you do in a List box. If the box is not big enough to display the whole list, scroll arrows appear so that you can scroll up and down the list just as you would in a document window. The existing objects almost fill the form so you'll need to create some space for the new objects. We won't worry too much about the appearance of the form at this stage. Later we will look at some techniques for improving the appearance of a form.

28

Building Access 2003 Applications

Doc. 5.115a

Exercise 16 Create a Combo box Form Wizard has created a text box for Ownerid. However, we are going to create a combo box to allow us to select an owner, so you can select the Ownerid box and delete it. If you need more space to add new objects then, in Design View, resize the FormBookings by dragging the border. Then drag the detail section (Figure 17) Figure 17 Resize the form

Drag the border

Drag the detail section

If you cannot see the toolbox (see left) click on toolbox on the View menu. As with

other toolbars, Access provides hover help to show you what the buttons on the toolbox are for

On the toolbox click the combo box button Draw a box in the blank space created when you resized the form. Combo box Wizard starts. You want to look up the values for the box, so make sure that this option is selected, and click on Next>. Select the Tables option, select TableOwners, and click on Next>. Select Ownerid, Firstname, Lastname by clicking on >, and click on Next>. Select sort on Last Name in ascending order then click on Next> Uncheck the hide key column box , adjust the column widths by dragging the column headers so that each column is about 0.5 inches wide, and click on Next>. Select OwnerId as the field that identifies the row, and click on Next>. Make sure that the Remember Value option is selected, and click on Next>. Change the label to Owner, and click on Finish

29

Doc. 5.115a

Building Access 2003 Applications

Microsoft Access will create a combo box that looks like Figure 18. You can select the box, as explained in the following section , and drag to move or resize the components. Figure 18 Unbound combo box

9.8

Selecting objects To select a combo box control click on the combo box. When you select the box it displays a move handle and sizing handles. The attached label has only a move handle (Figure 19). Figure 19 Combo Box Selected

To select the attached label click on the label. When you select the label it displays a move handle and sizing handles. The box has only a move handle (Figure 20) Figure 20 Attached Label Selected

To select the combo box and the attached label click on the box, hold down the shift key, and click on the label. Then click on the box. Both box and label will display the move handle and the sizing handles (Figure 21) Figure 21 Boxes and Label Selected

When you move a box the label moves with it. You can use the same techniques for resizing Text Boxes and other objects.

30

Building Access 2003 Applications

Doc. 5.115a

9.9 Setting the control source of a combo box The box that you created is called an unbound combo box. If you wanted to use the value selected in the combo box to determine the contents of another control or controls, you would use an unbound combo box. For example, you might want to create a combo box that you could use to find a related record on a form. Or you might want to create a combo box that you use to filter the records in another combo box. However, in this case you want to use the combo box to store the value of OwnerId that you select from the list. Therefore the combo box must be bound to the OwnerId field. The OwnerId is the Control Source. In the next exercise you will use the properties box to set the control source value. Please refer to section 8.5 for instructions on setting object properties. Exercise 17 Set the Control Property Click on the combo box object and make sure the properties window is displayed. In the properties window click on the Data tab In the Control Source box select OwnerId. Your combo box should now look like Figure 22 Figure 22 Bound Combo Box

Click on the All tab ans set the Name property to FieldOwnersList

9.10 Add Text Boxes with Calculated controls Exercise 18 Create the text box Make sure that your form is open in design view. On the toolbox click the text box button Draw a box in the blank space created when you resized the form. The box will have two parts, the box and the label, as in Figure 23 Figure 23 Text Box

Click the label. The properties window will be labelled something like label: label32 (your label will probably have a different number to 32 in my example). Set the name property to LabelKennelCost Set the caption property to Kennel Cost Click outside the property window and you will see that the label has changed.

31

Doc. 5.115a

Building Access 2003 Applications

Click on the label to select it. Move the mouse pointer to the border of the box until it turns into a two-ended arrow. Drag the border until you can see all the label text. Click the text box. The properties window should now be labelled something like text box: text31 Set the name property to FieldKennelCost

In the next exercise you will use expression builder to build the expression that is used to calculate the kennel cost. You can type expressions in, but using the expression builder means that you can only select objects that exist, and it reduces the chances of errors through mis-typing. Exercise 19 Build an expression for FieldKennelCost Click on the data tab and then click on expression builder () in the Control Source field in the properties window. The expression builder window will open (Figure 24) Figure 24 Expression Builder

Click on = and ( so that they appear in the box at the top of the window. Double click on RunRate in the middle column (scroll if you cannot see it). Microsoft Access will add [ ] round the object name. Continue adding operators (single click) and field names (double click) until you have built the expression =([RunRate]*[NoOfRuns]+[CatRate]*[NoOfCats])*[NoOfDays] Click on OK to close the expression builder. Set the format property to Currency

32

Building Access 2003 Applications

Doc. 5.115a

Exercise 20 Adding your own calculated controls Add your own text box objects for Heating Cost, Insurance Cost and Total Cost, using the expressions given in section 9.4 You will need to set the name properties of the text box objects so that they will appear in the list of objects available on FormBookings

9.11 Testing the combo box When you open the form in design view you are positioned at the first record and you will need to select the 'new record' navigation button to go to a new record. Later we will learn how to use an event procedure to position the form at a new record when it is opened. Exercise 21 Test the combo box In Formbookings switch to form view. Click on the new record button to go to a new record or press ctrl and + keys together. Click on the downward pointing arrow on the right of the box labelled Owners. Select Bill Smith from the list that is displayed. Your form should look something like Figure 25 Figure 25 Select from Owners list

Book Bill's 2 cats in for 2 days, arriving on 5/4/05. They will share a run, and as it is rather chilly in April they would like heating. Use the current rates, which were specified with the additional requirement. Open the table Bookings and check that the data has been correctly entered as the last record.

Document 5.115

Version 2 September 2007 33

Você também pode gostar