You are on page 1of 373

MS Access Fundamentals

Introduction to Microsoft Access Introduction to Data Sheets Intro to Forms and Reports Database Fields On Sheet Managing Data Fields Data Fields on Forms and Reports Data Field Design Properties of Data Fields Operators and Operands Introduction to Data Types Using Data Types Introduction to Relationships Managing Relationships Referential Integrity Introduction to Data Analysis The Structured Query Language Queries and Relationships Exploring Data Analysis Data Analysis With Charts Formatting Charts Action Queries Data Maintenance, Import/Export Tables and Queries Aesthetics Characteristics of Forms Windows Controls Types of Forms

Subforms Introduction to Expressions Controls and Expressions Built-In Functions Series-Based Functions Domain-Based Functions Business-Based Functions Finance-Based Functions

Introduction to Microsoft Access


Microsoft Access Launching
Introduction
Microsoft Access is a computer application used to create and manage computer-based databases on desktop computers and/or on connected computers (a network). Microsoft Access can be used for personal information management (PIM), in a small business to organize and manage all data, or in an enterprise to communicate with servers. Like any other computer application, in order to use Microsoft Access, you must first open it. There are various ways this can be done. Microsoft Access is a classic computer application and it gets launched like the usual products you have probably been using. As such, to start this program, you could click Start -> (All) Programs -> Microsoft Access:

As a regular member of the Microsoft Office suite of applications, if your installation created a sub-menu on the Start menu, you could click Start -> New Office Application and proceed from the New dialog box. Although Microsoft Office 97 and Microsoft Office 2000 get installed in the C:\Program Files\Microsoft Office folder, they treat the shortcuts that launch them differently. The applications that are part of Microsoft Office 97 designate their shortcuts with full names and these are installed in the Microsoft Office folder. Microsoft Office 2000 (Premium) uses shortcut names to designate its shortcuts and they are installed in the Microsoft Office\Office folder. This means that you could launch an application from Windows Explorer or My Computer. Therefore, in order to launch Microsoft Access, locate its shortcut in Windows Explorer or My Computer and double-click it:

If you have a Microsoft Access database such as an E-Mail attachment, a file on a floppy disk, on the network, or in any other means, once you see its icon, you can double-click it. Not only will this action launch Microsoft Access, but also it will open the file. You can also launch Microsoft Access from a shortcut. If you happen to use the software on a regular basis, you can create a shortcut on your desktop or on the Quick Launch area. Many users also take advantage of the Microsoft Office Shortcut Bar. Sometimes, the icon you need will not be there; in that case you should insert it manually. If you are working on a network of related computers, your database may be located in another computer. In this case the network or database administrator would create a link or shortcut to the drive that is hosting the database. You can then click or double-click this link or shortcut to open the database and, as a result, launch Microsoft Access.

Microsoft Access Shortcuts


Whenever you find out that you are using a particular program or file most regularly, you should have an icon on the desktop that can lead you to it quickly. This icon is called a shortcut. There are various techniques used to create a shortcut. Probably the first thing you should find out is where your application is located. You can find out by doing a search on the computer. Except on Microsoft Windows 95, you can create a shortcut from the Programs menu. By default, the shortcuts on the Microsoft Office 97 applications are located in the C:\Program Files\Microsoft Office folder. And these shortcuts hold the same names as their respective programs; those will be Microsoft Word, Microsoft Excel, Microsoft PowerPoint, etc. The shortcuts of the Microsoft Office 2000 applications are located in the C:\Program Files\Microsoft Office\Office folder. These shortcuts use another naming convention. They are Msaccess, Winword, Excel, or Frontpg, just to name a few. To create a shortcut from Windows Explorer or My Computer, you can right-click the icon or the shortcut of the application, position your mouse on Send To, and click Desktop (Create Shortcut). To create a shortcut from the Start menu, click Start -> (All) Programs. When the program appears, you can right-click it, position the mouse pointer on Send To and click Desktop (Create Shortcut).

Practical Learning: Creating a Shortcut


1. Right-click on an empty area of the Desktop -> New -> Shortcut

2. On the first page of the wizard, click the Browse button 3. Make sure the Look In combo box is displaying the C: drive 4. Double-click Program Files 5. Double-click Microsoft Office

6. If you are using Microsoft Access 97, click Microsoft Access. If you are using Microsoft Access
2000, double-click Office. Then click Msaccess:

7. Click Open

8. Click Next

9. If you are using Microsoft Access 97, notice the name of the shortcut

If you are using Microsoft Access 2000 or later, change the name of the shortcut to Microsoft Access:

10. Click Finish

Microsoft Access Interface


Introduction
To get better acquainted with the user interface of Microsoft Access, we will use this section as a Practical Learning exercise.

The Title Bar


1. As a regular Windows application, Microsoft Access shares some characteristics that are
common to other programs. The top section of the interface is made of wide bar called the title bar:

The left section of the title bar displays a small picture known as the system icon. This icon is used to identify the application. The icon holds a list of actions you can perform to close, minimize, maximize, move or restore the application. To perform any of these actions, you would click the system icon. This would display its list:

This list can also be referred to as the system menu. To use one of its items, you can click it. To experiment with the system menu, click the system icon. If the Restore item is available, click it first 2. Click the system icon again and click Move. Notice that the mouse pointer changes its shape into a cross 3. Press and hold Shift (with your left hand). Then press the right arrow key (with your right hand) three times and press the down arrow key twice. Notice that the Microsoft Access window moves by units 4. To move the window slowly, press and hold Ctrl(with your left hand). Then press and hold the left arrow key (with your right hand) while you are still holding Ctrl. Notice that these last two times, the window moves slowly 5. To keep the window in its new position, press Enter 6. The main area of a title bar is a long bar actually referred to as the title bar. This section is also used to perform the same operations available on the system menu. There are other operations you can perform different than the system menu depending on the way you click the main area of the title bar. To see an example, double-click the title bar. Notice that this maximizes Microsoft Access. The right section of the title bar displays three small squares referred to as the system buttons. They are used to minimize, maximize, restore or close Microsoft Access. These items are

Button

Role

Minimizes the window Maximizes the window Restores the window Closes the window

The Main Menu


1. Under the title bar, there is a horizontal list of words. This list is made of items such as
File, Edit, View, etc. Since there are various kinds of menus on this application, the menu on top will be referred to as the Main Menu and sometimes the Menu Bar. To use a menu item, you click one of its words and the menu expands. If an item is missing from the main menu, you can customize it. To experiment with the main menu, click File. There are four main types of menus you will encounter. When clicked, the behavior of a menu that stands alone depends on the actions prior to clicking it. Under the File menu, examples are Close or Exit

2.

A menu that is disabled is not accessible at the moment. This kind of menu depends on another action or the availability of something else. To see an example, one the main menu, double-click Window:

3.

A menu with three dots means that an intermediary action is required in order to apply its assignment. Usually, this menu would call a dialog box where the user would have to make a decision. As an example, on the main menu, position the mouse on File and click Open...

4. On the dialog box, click Cancel

5.

A menu with an arrow holds a list of menu items under it. A menu under another menu is called a submenu. To use such a menu, you would position the mouse on it to display its submenu. For example, on the main menu, click Tools and position the mouse on Database Utilities

6. To dismiss the menu, click Tools 7. Notice that, on the main menu (and any menu), there is one letter underlined on each word. Examples are F in File, E in Edit, V in View, etc. The underlined letter is called an

access key (the word access has nothing to do with Microsoft Access, it is used in this sense throughout Microsoft Windows and other operating systems). The access key allows you to access the same menu item using the keyboard. In order to use an access key, the menu should have focus first. The menu is given focus by pressing either the Alt or the F10 keys. To see an example, press Alt 8. Notice that one of the items on the menu, namely File, has its borders raised. This means that the File menu item has focus 9. Press t and notice that the Tools menu is expanded 10. When the menu has focus and you want to dismiss it, you can press Esc. For example, press Esc 11. Notice that the Tools menu has collapsed but the main menu still has focus 12. Press f then press o. Notice that the Open dialog box displays. 13. To dismiss the Open dialog box, click Cancel 14. On some menu items, there is a key or a combination of keys we call a shortcut. This key or this combination allows you to perform the same action on that menu using the keyboard. If the shortcut is made of one key only, you can just press it. If the shortcut is made of two keys, press and hold the first one, while you are holding the first, press the second key once and release the first key. Some shortcuts are a combination of three keys. To apply an example, press and hold Ctrl, then press o, and release Ctrl 15. Notice that the Open dialog box opens. To dismiss it, Click Cancel

From now on, in this book, Press T Alt, G Ctrl + H Ctrl + Shift + E Means Press the T key Press and release Alt. Then press G Press and hold Ctrl. While you are still holding Ctrl, press H once. Then release Ctrl Press and hold Ctrl. Then press and hold Shift. Then press E once. Release Ctrl and Shift

The Toolbars
Under the menu bar, there is another bar made of various buttons. This is called a toolbar. The toolbars change a lot in Microsoft Access. As you spend more time with this application you will learn how to recognize these toolbars. Each toolbar has a proper name and we will learn how to recognize them. At times, there will be many toolbars that come and go while you are using Microsoft Access. For this reason, we will refer to each toolbar by its name. To know the name of a toolbar, you can right-click any word on the menu bar or any button on the toolbar. If you have only one toolbar on your screen, its name will have a check box. The other name(s) on the context menu is (are) the one (those) you can add to the screen if you wish:

You could also create your own toolbar.

The Status Bar


The status bar is a long horizontal bar that spans the whole button section of Microsoft Access. It will be used to provide some assistance or information about an item that is displaying or being accessed in Microsoft Access. At this time, it may be displaying Ready (and it means it)

Microsoft Access Database File


1. Click Create 2. When the Database Wizard dialog box comes up, click Finish

Opening a Database
Unlike some other programming environments, Microsoft Access considers a database as a single Windows file with a name. We will eventually learn that this file can contain various objects that actually make up a database. Therefore, a Microsoft Access database is opened as a normal file. To open a database, if you are just starting Microsoft Access, from the Microsoft Access dialog box, you can click the bottom radio button, Open An Existing File, locate the folder that contains the database, select the database file and click Open. If you locate a database in Windows Explorer, My Computer, My Documents, or any other window that displays the Microsoft Access file icon, you can just double-click the icon and open the database. If you received a database as an email attachment, you can also open the attachment and consequently open the database file. Microsoft Access keeps a list of most recently used databases under the File menu. In Microsoft Access 97, the list is limited to 4. In versions of Microsoft Access after 97, you can increase the list of MRU (most recently used) files in the General tab of the Options dialog box. To open a file that was previously used, you can click File from the main menu and click the database file from the list.

Practical Learning: Opening a Database


1. Open Windows Explorer or My Computer and locate the folder that contains the resources that accompany this ebook. Copy a folder called GSC and paste it in your Exercises folder 2. In Microsoft Access, to open a database, on the main menu, click File -> Open 3. Locate your Exercises folder and display it in the Look In combo box. Then double-click the GSC folder to open

4. Click Grier Summer Camp

5. Click Open

Overview of Database Objects


The Database Window
After creating or opening a database, unless the product is setup otherwise, the first object that appears is a rectangular box named the Database window. It is different on Microsoft Access 97 and Microsoft Access 2000 (and later versions). The Database window is a classic object of Windows applications. It is equipped with a system icon on the left side of its title bar and three system buttons on the right side. Based on this, you can maximize, minimize, restore, or close it. You can also resize it by dragging one of its borders or corners. Because the Database window holds all objects that are part of a database, if you close the Database window, it also closes the database but leaves Microsoft Access opened. Because Microsoft Access is a Multiple Document Interface (MDI) application, if you maximize any of its child objects, such as the Database windows, the other objects that you subsequently open would be maximized also. In all versions of Microsoft Access, objects are organized in categories. In Microsoft Access 97, each category is represented by a property page. Therefore, to select a category, you can click its tab.

Once in the property page of a category, to open an object: You can double-click it You can click it to select it, then click the Open button on the right side

You can also right-click an object and click Open

One of the biggest changes that Microsoft Access 2000 brought was on the Database window. It got completely redesigned and highly improved. Like all classic windows, it is equipped with a title bar similar to the Database window of the 97 version as we described above. Under the title bar, the Database window is equipped with a contextual toolbar. This means that the toolbar responds according to the object that is selected in the Database window. Like all releases, objects in Microsoft Access are organized in categories. In the 2000 and later versions, objects are represented by the Objects Bar. Therefore, to select a category, you can click its button. Besides the buttons that represent categories, when you click a button, one, two, or three links allow you to create objects of that category. For example, you can create a table by double-clicking the Create Table By Using Wizard link.

To open an object: Double-click it Click it to select it and click the Open button on the Database windows toolbar Right-click it and click Open

Besides providing the ability to create a new object or open an existing one, you can also delete an object using the Database windows toolbar. To do this, you can click the object to select it. Then, on this toolbar, click the Delete button. The Database windows toolbar also provides four view buttons that allow you to change the way the list displays in the right side of the view. If you have used Windows Explorer, My Computer, or My Documents, you are probably familiar with these buttons. For example, here is the Database window that displays its list in Large Icons:

10

Database Objects: Tables


A Microsoft Access database is a file made of various internal objects: tables, queries, forms, reports, etc. All these are managed from an object called the Database Window. The objects are kept in categories. To access an object, you click the button that corresponds to its category. A table is the central point of a database, because all data is stored in tables. For better organization, you will have various tables in your database, each for a different purpose. Each table is recognized by its name. To open a particular table, you can double-click it. You can also right-click a table's name and click Open. If the desired table is already selected on the Database Window, you can click the Open button to open it.

Practical Learning: Opening a Table


1. On the Database Window, in the Objects Bar (Microsoft Access 2000) click the Tables button or the Tables property page (97)

2. Double-click Employees

3. To close the table, click its Close button

Database Objects: Queries


A table can be large depending on the information it holds. To further organize your data, you should be able to retrieve necessary information for a specific purpose. The solution is to create a query (or queries) in order to limit part of the data in a table for a specific goal, for better managing or searching. That's the role of a query. Just like tables, queries are managed from the Database Window in their own category. You can open a query the same way you open a table.

Practical Learning: Opening A Query


1. On the Database Window, in the Objects Bar (2000) click the Queries button or the Queries property page (97)

2. Double-click List of Registrants By T-Shirt Size to


open it:

Notes
Queries and tables look alike. As you will see in future lessons, their main difference is noticed only behind-the-scenes. This has to do with the way each receives its data.

11

3. After viewing the query, to close it, click its Close


button

Database Objects: Forms


Tables are used to create the data in your database, but they are usually not friendly looking, as far as the users are concerned. Forms are windows objects used to view and/or enter data in your database. A form can combine data that is part of one or more tables or queries. Forms are the window interfaces that you usually will ask your users to access when performing data entry in your database.

Practical Learning: Opening A Form


1. On the Database Window, click Forms

2. Double-click MembersByGender

3. After viewing the form, click its Close button dismiss it

Database Objects: Reports


A report is the organized document that allows a user to print information from a database. A report can include different parts or details about your database. It could include data from a table or a query, it could also get its data from various tables, queries, forms, or data that is calculated from other data coming from different tables or forms. You could also create a completely independent report whose content is not related to any data on an object.

12

Practical Learning: Opening A Report


1. On the Database Window, click the Reports button

2. Double-click Camps

3. After viewing the report, click its Close button

Database Objects: Pages


Starting with Microsoft Access 2000, Data Access Pages allow you to publish your forms as web pages on the Internet or on an Intranet. Their use is not as common as the other database objects but they provide thoughtful functionality.

Practical Learning: Data Access Pages


1. On the Database Window, click the Pages button

2. Double-click Camps

3. After viewing the page, click its Close button

Macros
When creating Microsoft Access databases, you can customize certain behaviors of your products. Some of these behaviors can be automated through a combination of buttons. For example, you may want to open one document (form) from another. You can use macros to do that. In such case, you would not have to write code. Since macros are becoming less and less popular (for good reasons), we will not spend much time learning them.

Modules
13

Modules are pieces of code used to impose particular behaviors to your application to make it better. They are written in Microsoft Visual Basic. Modules are more flexible and extensive than macros, although they are usually written for various and particular circumstances. One example is to print a receipt after a customer has bought paint in a store. Macros and Visual Basic code can be used on the same application. Sometimes you will prefer one to the other, and sometimes you will keep using VBA (Visual Basic for Applications). Whenever possible, you should use VBA instead of macros. Although modules are represented on the Database Window like the database objects we have seen so far, to view, read, or access a module, you need to get to Microsoft Visual Basic. There are various ways you could do that. A module could be an independent piece of code that is not related to another object, in this case its name would appear in the Database Window; all you have to do is double-click it and that would launch Microsoft Visual Basic. If you select a form or report from the Database Window, you will see the Code button on the Database toolbar. If you click that button, it would launch Microsoft Visual Basic. If the form or report has some code associated (or bound) to it or to some of its controls, the code would display; otherwise the programming window look empty (it should have at least one line displaying Option Compare Database.

Practical Learning: Opening Microsoft Visual Basic


1. On the Database Window, click Modules 2. Double-click modUtilities

3. Notice that Microsoft Visual Basic opens (if you are using Microsoft Access 97, you should see a
window called the Code Window):

4. To return to Microsoft Access, click the View Microsoft Access button (if you are using Microsoft Access 97, close the Code window by clicking its Close button )

5. To close the form, click its Close button

Microsoft Access Help


Context-Sensitive Help
Context-sensitive help refers to help provided on a specific item on the screen. Such help is provided for objects that are part of Microsoft Access interface. It includes objects like buttons on toolbars, an object opened such as a table, a query, a form, or a report, etc. Context-sensitive help is also referred to as Whats This?. To get context-sensitive help, press Shift + F1. In addition to the traditional arrow, the mouse cursor would be accompanied by a question mark. To get help on an object, you can just click it. Another type of context sensitive help is provided in various dialog boxes. They display a button with a question mark on the left of the system Close button. To use this type of help, click the question mark button and click the item on which you need help.

Practical Learning: Using Context-Sensitive Help


14

1. Press Shift + F1 and notice the new mouse cursor

2. On the Database toolbar, position the mouse on the Open button

3. Click

4. After viewing help, press Esc 5. To get context-sensitive help on a dialog box, on the main menu, click Insert -> Form

6. In the New Form dialog box, click the Whats This button

7. Click the list box in the middle right side of the dialog

15

8. After viewing help, click the Whats This button again and click the combo box, in the bottom
right side of the dialog box

9. After viewing help, press Esc and click Cancel

The Office Assistant


The Office Assistant is a character or a virtual person whose main job is to provide instant help when using a Microsoft Office product. The Office Assistant is usually on top of Microsoft Access while you are working. If you do not like the way it looks, you can click it and click Options. This would present you with the Office Assistant property sheet in which the Gallery property page allows you to select a different Office Assistant. The Options property page allows you to configure the behavior and responsiveness of the Office Assistant. To use its service, just click it, then type a word, a sentence, or a question. After pressing Enter, a primary list of possible matches would be displayed. If you do not find what is close to your request, you can use the available options or change your request. If you do not want the Office Assistant on the screen while you are working, you can hide it. To do this, in Microsoft Access 97, you can click its Close button. In Microsoft Access 2000, on the main menu, you can click Help -> Hide Office Assistant. To display it when it is not available, on the main menu, you can click Help -> Show the Office Assistant.

Practical Learning: Using the Office Assistant


1. If the Office Assistant is not displaying on the screen, on the main menu, click Help -> Show Office Assistant To use the Office Assistant, click it

2. Type Create Table

16

3. Click Search 4. On the list that appears, click Create a table 5. On the HTML Help window that appears, read the text and click one of the blue links

6. After reading it, on the toolbar of the HTML Help window, click the Back button

7. Click another link 8. After reading it, close the HTML Help window that opened but do not close Microsoft Access 9. In Microsoft Access, click the Office Assistant again. Notice that the last request redisplays. Click Search 10. This time, click See More 11. In the second page, click another link such as Create A Field For Text Or Memos 12. Do not perform but read the instructions. After reading the instructions, close the HTML Help window

Online Help
It is important to note that help in Microsoft Access 2000 and above is different than help in Microsoft Access 97. In the 97 version, help was provided through a system called WinHelp. After that, Microsoft decided to start using HTML Help. Like everything in computer applications, each of these help systems has its advantages and disadvantages. Over all, the process of getting help remains the same but it is displayed differently.

Internet Help
Although help on the Internet tends to be disparate, it is still the widest form of help available. This is provided in web sites, web pages, newsgroups, support groups, etc. As the publisher of the database environment, it is only natural to refer to the Microsoft corporate web site first for help. The Microsoft web site is divided in categories. A web site is dedicated to Microsoft Access at http://www.microsoft.com/access. You can get help at http://support.microsoft.com. Probably the most visited site of Microsoft for developers of all Microsoft products is http://msdn.microsoft.com. This last site provides a tree-based list that presents items in

17

categories.

Microsoft Access Exit


Since Microsoft Access shares the same functionality you are probably familiar with from using other applications, you can close it easily. To close Microsoft Access, from the menu bar, you can click File -> Exit To close Microsoft Access from the system icon, you can either click it and click Close, or you can double-click its system icon To close Microsoft Access from its title bar, you can click its Close button To close Microsoft Access like any regular window of the Microsoft Windows applications, you can press Alt + F4 To close Microsoft Access using mnemonics, you can press Alt, F, X.

Practical Learning: Closing Microsoft Access


To close Microsoft Access, click the Close button on the top right corner of the window

Introduction to Data Sheets


Creating a Database
The Database Wizard
Many techniques allow you to create a database, the fastest of which consists of using one of the provided examples. Microsoft Access 97 shipped with 22 sample databases while Microsoft Access 2000 ships with 10. Furthermore, the 97 version allowed to provide sample data into the database. This is not available with the 2000 release. The databases that ship with Microsoft Access can help you in two main ways: they provide a fast means of creating a database and you can learn from their structure. To create a database using one of the samples, there is a little detail to follow depending on whether you had launched the program already or not. If Microsoft Access is not running, you can start it. When the first dialog box comes up, you can click the second radio button: Access Database Wizard, Pages, And Projects and click OK. If the program is already on your screen, on the menu bar, click File -> New Database The New dialog box displays two property pages labeled General and Databases. If you want to create a database based on one of the samples, you can click the Databases property page. A list of the sample databases appears. You can then choose one and click OK. When creating a database using one of the samples, depending on the sample you selected, the Database Wizard will display a few objects and suggest some fields for your database. Some fields are already associated with the objects and some other fields can be added. You can examine them, then add some fields you think are important for your database. You will also have the option of selecting a design layout. Some of the sample databases have been configured to require information about the company you are creating the database for..

Practical Learning: Creating a Database Using a Sample


1. Start Microsoft Access if necessary and click the second radio button.
If you are using Microsoft Access 97, it is the Database Wizard radio button. If you are using Microsoft Access 2000, it is the Access database wizards, pages, and reports radio button

18

2. And click OK. This opens the New dialog

3. From the New dialog box, click the Databases tab if necessary and, from the Databases tab,
click Time and Billing

4. Click OK

5. Locate the Exercises folder and display it in the Save In combo box 6. Delete the content of the File Name text box of the File New Database dialog box and type
Rockville Techno and click Create 7. When the first page of the wizard comes up, click Next 8. For this exercise, on the Tables In The Database list box, click Information About Employees:

9. On the Fields In The Table list, click the Employee Number check box

10. Click the check box of Email Name 11. Scroll down and click the Home Phone check box
12. Click Next

13. For the style of the screen display, choose International to preview one of the samples and
click Next

19

14. For the style of the printed report, click Bold to preview that display 15. Click Formal and click Next 16. For the title of the database, type Rockville Technologies

17. Click Next 18. Then click Finish While the Database Wizard is creating a database for you, dialog boxes will be flashing from time to time. If you don't have a printer, a nasty dialog box will be giving an error. If this happens, click OK all the time. In this case, after this lesson, use the Add Printer wizard from the Printers window to install a "fake" printer. One way or another, Microsoft Access needs a printer for the reports 19. When asked to provide information about your customer, click OK

20. In the Company Name text box, type Rockville Technologies, Inc. and press Enter 21. In the Address text box, type 5026 Towers Road Suite D14 and press Enter 22. In the City text box, type Rockville and press Enter 23. In the State field, type Maryland and press Tab 24. In the Postal Code field, type 20852-1644 and press Tab 25. In the Country field, type USA and press Tab 26. In the Payment Terms, type 60 Days 27. Click the Invoice Description field and type For more information on our company, visit us
at http://www.rockvilletechnologies.com 28. Press Tab

29. In the Phone Number field, type (301) 869-9814 and press Tab 30. In the Fax Number field, type (301) 869-9618

20

31. After entering the necessary data for your customer, to close the company's form, click its system Close button

32. Notice that the database opens with the switchboard.


To close the switchboard, click its system Close button 33. On the lower left corner of MS Access, click the bar of the Database window and, on the menu that appears, click Restore

Database Properties
Your screen may be made of a large box at this time: this is the Switchboard, and it is a form. A special window you will be using most regularly is called the Database Window. Whenever it is minimized or hidden, you can display it by pressing F11 (unless it has been configured to (almost) never display). Whether you work alone or in a group, communication and documentation are important. Your database project has its own properties that you can use to find out some details about your file, to enter some notes about the project, or to give directives to other people who have access to the database.

Practical Learning: Using Microsoft Access


1. The Rockville Technologies database should still be opened To display the Database Window, press F11 2. On the main menu, click File and observe the menu items under File 3. While the File menu is still selected, move the mouse to Tools and click Startup 4. The Startup dialog box allows you to set some settings that the current database will follow when it starts. In the Application Title, type Rockville Technologies, Inc. 5. Click the arrow of the Display Form/Page combo box and select (None). In case you wonder why (None) is between parenthesis, this is done so that if there are other things in the list, None would always be on top of the list. That way, it would not be between two other objects (forms and Data Access Pages) on the list. 6. Click the browse button of the Application Icon text box 7. On the Icon Browser dialog box, locate the folder that holds the resources for this ebook 8. Click the Rockville Techno icon and click OK

9. Accept all the other defaults:

21

10. Click OK 11. Notice that, on the title bar, the database is now using another icon than the default one 12. On the main menu, click Tools -> Options 13. The Options dialog box allows you to control some settings that are related to Microsoft Access. For example, click the General tab 14. Change the content of the Default Database Folder text box to the Exercises folder you will be using throughout this ebook

15. Increase the Recently Used File List combo box to 8

16. Click OK 17. As mentioned already, each toolbar on the database has a particular name. To find out the name of the current toolbar, right-click any button on it 18. Notice that the Database name has a check box. This means that toolbar is displaying at this time. In this case, this toolbar is called the Database Toolbar 19. On the menu bar, click File -> Database Properties 20. Once more, from the menu bar, click File -> Database Properties 21. From the Properties dialog, click the General tab. Examine the various sections. Notice the size of the current database 22. Click the Summary tab

23. Make sure the Title is set to Rockville Techno

Click the Subject text box and type Business Regular Activities

24. Click the Author text box and type Lucien Durand 25. Click the Manager text box and type Christine Lotts 26. Click the Company text box and type Rockville Technologies, Inc. 22

27. Click the Category text box and type Business 28. Click the Keyword text box and type business, clients, projects, transactions 29. Click the Comments text box and type: This software product is used by the company to
conduct its regular business activities and related transactions. For more information, contact Lucien Durand or Christine Lotts. Refer to the Address Book for their phone number, extension, and E-Mail Address.

30. Click the Hyperlink Base text box and type http://www.rockvilletechnologies.com

31. Click the Statistics, Contents, and Custom property pages and review their contents. The Statistics tab gives you statistics about your database and its summary access. The Contents tab shows a list of the components that are part of your database. The Custom tab shows, and allows you to customize, the field names associated with your database. 32. When you have finished working with the database Properties, click OK (if you click Cancel, any change(s) you have made will be discarded)

Tables Fundamentals
The Table Wizard
Microsoft Access is filled with wizards which are step-by-step dialog boxes that allow you to create objects or fields on a database. Like the Database Wizard, Microsoft Access provides the Table Wizard used to easily create a table. It allows you to add fields that are necessary for a particular table. The fields have been configured in the general sense so you can use them in your database. Of course you can modify any field that was created using the wizard. To use the Table Wizard, on the main menu, you can click Insert -> Table. Alternatively, on the Database Window, when in the Tables section, you can click the New button. These two actions would display the New Table dialog box from where you would select Table Wizard. If you are using Microsoft Access 2000 and later, from the Tables section of the Database Window, you can double-click Create Table By Using Wizard

23

In the Table Wizard, the tables are organized in two primary categories: Business and Personal. To select one of those categories, you can click its radio button. Each main category is made of various sample tables. To select a sample table, you can click its name in the Sample Tables list. In the middle, the Sample Fields list, the fields associated with the selected sample table are displaying. From that list, you can select the desired field(s). Once a field has been selected, it displays in the Fields In My New Table list. You can then select a different table to mix fields from as many tables as desired. The 4 buttons between the Sample Fields list and the Fields In My New Table list allow you to add or subtract fields. To help with selection and de-selection, the wizard provides four buttons: Button Role Used to select one field Used to select all fields from the sample table Used to deselect one field Used to deselect all fields During field selection, if you select a field, its corresponding name appears in the right list. If you select a field of the same name more than once, for example, if you select Address twice, the 2nd Address would be called Address1. Sometimes that will be what you want, and sometimes it will be by mistake. If then you make a mistake when selecting fields, you can double-click the unwanted field in the Fields In My New Table list and that field will be removed. After making your choices, you can keep the names provided by Microsoft Access into your table, or you can rename any field to suit your needs. To rename a field, first select it in the Fields In My New Table list. Then, click the Rename Field button. In the Rename Field dialog box, type the desired name and click OK:

If you try providing a name for a field that already exists, you would receive an error:

24

Practical Learning: Using the Table Wizard


1. The Rockville Techno database should still be opened In the Database Window, click the Tables button

2. Double-click Create Table By Using Wizard. (If you are using MS Access 97, from the
Tables tab, click New and double-click Table Wizard). The Table Wizard starts In the Sample Tables list box, scroll down and click Assets

3. Click the Business radio button if necessary 4. In the Sample Fields, click AssetID and click the Select One Field button 5. From the Sample Fields, double-click Make, Model, ModelNumber, SerialNumber,
DateAcquired, and PurchasePrice

6. In the Sample Tables, scroll up and click Mailing List 7. In the Sample Fields, scroll down and double-click Notes 8. In the Fields In My New Table list, click ModelNumber to select it and click the Remove
One Field button

9. Click the Personal radio button 10. In the Sample Tables, click Categories 11. In the Fields In My New Table list, click AssetID to select it 12. From the Sample Fields, double-click CategoryName 13. In the Fields In My New Table list, click CategoryName to select it and click the
Rename Field button

14. In the Rename Field, change the Field Name to AssetType

15. Click OK 16. Click Next

17. Change the name of the table to CompanyAssets


18. Click Next twice and click Finish

19. To close the CompanyAssets table, click its system Close button 25

Data Entry on Tables


Data is entered in a table by typing it into cells. Some fields can be configured to accept some types of data and reject others. Some other fields would allow anything. This depends on how the database fields were setup. A table's cell holds one particular unit of data. All cells on the same (vertical) column belong to the same category of information. The horizontal range of cells is called a record; and all cells on this range belong to the same record. After typing data into a cell, you can press Enter or Tab to move the cursor to the next cell. In many circumstances you will also be able to move to the next cell by pressing the right arrow key. Sometimes you can move to the next record even if the current record is not completed. In this case, you could press the down arrow key. There are three kinds of fields or cells the user will face: a field in which the user can type data, a field that displays a list such as a combo box the user has to select from, and a field that does not receive input from the user. The latter is usually set for an AutoNumber data type: the database itself keeps track of the numbers. If you as the user have to select from a list, click the field that holds the list and select from the combo box. There are two kinds of combo boxes, those that accept new entries from the user and those that allow only a selection from a preset list. The classic field allows the user to just type the appropriate data in a field. After setting the data in a particular field, you can click another cell and type the desired data. The easiest way is to press the right arrow key to move to the next field or the left arrow to move to the previous field; pressing Enter would work as well. Data on the same row represents a record. Data on the same column represents a category. After typing data, if you press Enter at the end of a record, the cursor would move to the beginning of the next record. At anytime, you can press the up arrow key to move to the same category field of the previous record. If you press the down arrow key, the same category of the next record would receive focus.

Practical Learning: Table's Data Entry


1. The Rockville Techno database should still be opened On the Database window, while in the Tables section, double-click the CompanyAssets table to display it 2. Click the first empty field under AssetType and type Printer 3. Press Enter and type HP 4. Press Tab and type LaserJet 4200dtn 5. Click the empty box under Date Acquired and type 10/08/2002 or 10/08/02 depending on how your computer is setup (we will discuss this during Database Maintenance but for now, if your computer is configured for a two-digit year, enter only the right two digit of the year) 6. Complete the table as follows:

AssetType Printer Computer Laptop Printer Digital Camera Computer

Make HP IBM Gateway Xerox Olympus IBM

Model

Date Acquired 10/08/2002 12/05/2002 10/22/2002 11/06/2002

Purchase Price 1950.95 1035.00 2095.95 1250.55 450.75 1055.55

Notes B/W Printer Business Notebook Color Printer

LaserJet 4200dtn 10/08/2002 NetVista M42 200XL Phaser 8200 C-50

ThinkCentre S50 10/08/2002

26

7. Close the CompanyAssets table

8. On the Database window, right-click the Payment Methods table and click Open
9. Complete it as follows: Payment Method ID Payment Method 1 Check 2 Cash 3 Money Order 4 Visa 5 Master Card 6 American Express Credit Card? No No 0 1 -1 58

10. Notice that the 0 value changes into No and any other number changes into Yes

11. To close the Payment Methods table, click its system Close button
12. On the Database window, double-click the Employees table to open it 13. Click the first empty field under Last Name, type Phillips and press Enter

14. Perform data entry, skipping other fields


15. Close the table after performing data entry

Table Printing
The primary function of the table is to provide a means of storing and arranging information of a database. Nevertheless, you can print data of a table, especially if either you do not have appropriate reports available or you are in a hurry. You can print data on a table whether the table is opened or not. To print a closed table, locate it in the Database Window. Then right-click the desired table and click Print. Once a table is opened in Datasheet View, on the Table Datasheet toolbar, you can click the Print button. This will send all the records of the table to the printer for printing. If you want to control the printing process, instead of using the Print button, on the main menu, you can click File -> Print... To print data of all fields on the table, you can click OK. If you want to print only certain records, unfortunately, Microsoft Access does not allow you to select rows at random: you can only select a range of records. To print a range of records, while a record at one end has focus, you can press and hold Shift. Then click the gray box at the end of the range.

Practical Learning: Printing Tables


1. To reopen the Payment Methods table, on the Database Window, while in the Tables section, double-click Payment Methods

2. To print data from the table, on the Table Datasheet toolbar, click the Print button 3. To close the current table, click its system Close button
4. To print the list of the companys assets, on the Database Window, click the CompanyAssets table to select it (you don't have to open it) 5. On the main menu, click File -> Print (if you are using MS Access 2000, you may need to double-click the File menu to display the whole list, which includes Print...) 6. Make sure a printer is selected in the Name combo box

27

Click the Properties button 7. Based on your printer, select the Landscape radio button (usually in the Orientation section of a Paper tab) and click OK 8. On the Print dialog box, click OK (If you had opened a table, you can close it now) 9. Open the Employees table 10. To print only the names of employees, click David. Press and hold Shift. Then click Network Administrator 11. On the main menu, click File -> Print 12. On the Print dialog box, click the Selected Record(s) radio button and click OK 13. After using the table, close it

Queries Fundamentals
Data Entry on a Query
A query uses the same approach to present its data, like a table: it is made of columns and rows whose intersections are cells. Although the main purpose of a query is to prepare data either for analysis or isolate some fields to make them available to other database objects, as done on a table, data can be entered in a query. Data entry on a query is the same as done on a table: data is entered into cells. The Enter, Tab and arrow keys are used with the same functionality. Like the table, the query provides navigation buttons on its lower section, allowing you to move to the first, the previous, the next, the last or any record in the range of those available.

Practical Learning: Performing Data Entry on a Query


1. While the AssetsInventory query is still opened, click the first empty field under the AssetType column 2. Type Computer and press Enter 3. Complete the query as follows: Date Acquired 10/08/2002 12/05/2002 10/22/2002 11/06/2002 Purchase Price 1950.95 1035.00 2095.95 1250.55 450.75 1055.55 Ctrl + ' Business Notebook Color Printer

AssetType Printer Computer Laptop Printer Digital Camera Computer Computer Ctrl + '

Make HP IBM Xerox

Model

Notes B/W Printer

LaserJet 4200dtn 10/08/2002 NetVista M42 Phaser 8200

Gateway 200XL

Olympus C-50 IBM Ctrl + ' Ctrl + '

ThinkCentre S50 10/08/2002 Ctrl + ' Ctrl + ' Ctrl + '

10/20/2002 1120.55

4. After using the query, close it

5. To create a query of selected information of employees, on the main menu, click Insert ->
Query

28

6. In the New Query dialog box, click Simple Query Wizard and click OK 7. In the first page of the wizard, in the Tables/Queries combo box, select Tables: Employees

8. In the list of Available Fields, double-click FirstName, LastName, Title, and BillingRate
9. Click Next twice

10. Change the Title of the Query to Employees Pay Information and click Finish
11. After viewing the result of the query, close it

Query Printing
Like tables, queries provide you with a fast means of printing data. Once again, this should be done when you need a printed but not a professional-oriented product. Data printing on a query is done with the exact same approaches and techniques as for a table.

Practical Learning: Printing a Query


1. On the Database Window, while still in the Queries section, double-click the AssetsInventory query 2. To print the query, on the main menu, click File -> Print 3. Make sure a printer is selected in the Name combo box and click the Properties button 4. Select the Portrait orientation and click OK 5. Click OK on the Print dialog box 6. To print only a few records, click the gray box on the left side of Laptop

7. Press and hold Shift. Then click the gray box on the left side of Digital Camera and click
release Shift

8. On the main menu, click File -> Print and, on the Print dialog box, click Selected Record(s) 9. Click OK to print

29

10. After using the query, close it.

Exercises
Tenley Associates
1. Start a new database using the Database Wizard and based on the Expenses sample
database

2. Name it Tenley Associates 3. For the Information About Employees, add Department Name, Email Name, Home
Phone, and Date Hired

4. For the Expense Report Information, include the Business Purpose 5. Set the Screen Style to Stone 6. Set the Printed Reports Style to Corporate 7. Set the Database Title to Tenley Associates 8. Set the Startup form to None 9. From the Tables section of the Database window, open the Expense Categories table
and enter the following expenses: Expenses Category ID Expenses Category 1 Office Equipment 2 Car Rental 3 Transportation 4 Customer Entertainment 5 Other 10. Print all records on the table and close it Expense Account# 102 104 105 108 112

11. Open the Employees table and fill it up with the following values, ignoring those not
mentioned:

First Name James Alexandra Walter Bertine

Last Name Bidds Roberts Hoaks Baugh

Title Accountant Sales Manager Manager

Home Phone (301) 725-4570 (410) 727-0982 (301) 912-2129

Sales Representative (410) 521-2850

12. Close the table

13. Using the Simple Query Wizard, create a query based on the Employees table and

include the following fields: FirstName, LastName, Title, and HomePhone. Save the query as Employees Contact Information

14. Close the query and print all of its records without opening it

15. Using the Employees Contact Information query, print only the second and third
records of employees

16. Use the Table Wizard to create a table that includes the following fields: DepartmentID
(from the Assets sample table), DepartmentName (from the Employees sample table),

30

and Notes (from the Recipes sample table of the Personal category). Save the table as Departments and fill it up with the following values Department ID Department Name Notes 1 Administration 2 Sales 3 Accounting Including all personnel from Management Including all sales representatives and managers

Introduction to Forms and Reports


Forms Fundamentals
Introduction
As done for the tables and queries, Microsoft Access provides a central dialog box you can use to create forms: this is the New Form dialog box. To display the New Form dialog box, if no object is opened, on the main menu, you can click Insert -> Form. Alternatively, in the Database window, you can first click the Forms button. Then, on the toolbar of the Database window, you can click the New button. As done for a query, before creating a form, you must decide where data would come from. If you are creating an independent form whose fields are made of Windows controls and whose contents would not depend on any field or data stored in another object, you can just proceed as you see fit, as if you were developing a regular Windows application. If you are creating a form meant for data entry for the database, you should specify where its data would come from. The object can be a table, a combination of tables, a query, a combination of queries, or a combination of tables and queries. If the data of a form will be based on such an object or a group of objects, you must specify it, before or while creating the form.

AutoForm
The fastest means of creating a form is through a feature called AutoForm. To use AutoForm, you can first select a table or a query on the Database window; you don't have to open the object. If the table or query is selected in the Database window, to create a form in one step, on the Database toolbar, either click the AutoForm button if it is already selected, or click the arrow of the New Object button and click AutoForm. Alternatively, while a table or a query is selected in the Database window but not opened, to quickly create a form, on the main menu, you can click Insert -> AutoForm. If a table or a query is already opened and you want to create a form based on it, on the Table Databasheet toolbar, or on the Query Datasheet toolbar, you can click the AutoForm button if it is already set as the New Object or you can click the arrow of the New Object button and click AutoForm. Another technique used to create a form using AutoForm consists of first displaying the New Form dialog box. From there you can click one of the three AutoForm options, select the object that holds data and click OK.

Practical Learning: Using AutoForm


1. Open the Rockville Techno database you created in the previous lesson

2. On the Database window, click the Queries button and click the Employees Pay 31

Information query to select it

3. On the Database toolbar, position the mouse on the New Object button. If the tool tip
displays New Object: AutoForm, , then click it. If it displays something else, click the arrow of the New Object button and click AutoForm

4. After viewing the form, on the Form View toolbar, click the Save button
5. Accept the suggested name for the form by clicking OK 6. Then close the form

The From Wizard


As far as users are concerned, the form is the central point of a database. It is used to view, enter, manipulate, and search data. Because users spend a great deal of their time looking at forms, you should create and make them as attractive and friendly as possible. Form design can take a long time in database development but Microsoft Access provides quick means to get around. The Form Wizard provides an easy and fast means of creating a form. Like the other wizards we have used so far, this one also takes you step by step through creating the object. There are two main ways you can launch the Form Wizard: from the Database Window or from the New Form dialog box. On the Database Window, you can click the Forms button. Then doubleclick Create Form By Using Wizard. On the New Form dialog box, you can click Form Wizard and click OK. The first page of the Form Wizard allows you to choose the originating table or query that will supply the necessary fields in the form. Once you have selected the object, its corresponding fields display in the Available Fields list box. You can then select all fields or decide which ones you want to include in the form. The 2nd page of the wizard allows you to select the desired layout of the form. Forms can be designed in various flavors: Columnar, Datasheet, Tabular, Justified: A columnar form is used to display data one record at a time. This is a convenient display for data entry and analysis because the user is able to examine each piece of information for each one record:

A tabular form displays its data in a table layout following a continuous series of records. All or almost all records are displaying in a single layout:

32

There are three main ways you can create a tabular form: from the New Form dialog box, using the Form Wizard, or designing it A datasheet form looks and behaves like a table, displaying all possible records at the same time instead of one record at a time:

A datasheet form is mainly used in relationships to display another table's related records. It is also suitable for people who prefer to work in a spreadsheet environment. This display allows the database developer to provide a sheet view to the data entry personnel without making the table's design or formats available. You can make the same form available in Form View and Datasheet View. In fact, most forms are. Users can switch from Form View to Datasheet View by clicking the View menu. Unfortunately, this could also allow the users to get the form in Design View, and then they could modify it. If you do not want the users to have access to Design View but retain Form View and Datasheet View, you may have to create custom menus and toolbars. There are two main ways you can create a Datasheet form: using the wizard or designing it. A Justified form provides a good and consistent look. When the form is created, borders are added to labels:

The 3rd page of the Form Wizard presents the forms designs you can choose from. These are the designs we saw when creating a database using the Database Wizard.

33

The 4th page allows you to name the form.

Practical Learning: Form Wizard - Columnar


1. The Rockville Techno database should still be opened On the Database Window, click the Forms button 2. On the Database Windows toolbar, click New 3. On the New Form dialog box, click Form Wizard

4. From the combo box, select the CompanyAssets

5. Click OK

6. Click the Select All Fields button


7. Click Next 8. Accept or choose the Columnar layout, then click Next 9. Click the International style and click Next

10. Accept the name of the form as CompanyAssets and click Finish
An automatic form is created for you

11. To close the form, click its Close button

Data Entry on a Form


Data entry of a database is mainly performed on forms as they provide the friendliest display of information. Data entry on a form is performed using text boxes, combo boxes, and other controls. On text boxes, the user enters data by typing it. On a combo box, depending on how the object was configured by the database developer, the user may have to only select an item from the list. In some other cases, the user may be allowed to enter new data. After entering or changing data on a control, to move from one field to the next, the surest way is to press Tab. On most occasions, the user can also press Enter. The Enter key may not move the cursor from a text box that allows multiple lines of text (such as a field created as Memo). If the user is simply reviewing data without performing data entry, the keyboards

34

arrow keys can also be used to move among fields.

Practical Learning: Form Data Entry


1. The Rockville Techno database should still be opened and the Forms button should be
selected. Otherwise, on the Database Window, click the Forms button Double-click the Employees form to open it

2. In the first record, for David Phillips, click Address and type 10048 Venice Drive 3. Press Enter to move to the City field and type Bethesda 4. Complete each record by clicking in the appropriate field and typing the corresponding data
(after each record, click the Next Record button) 5. Close the Employees form after performing data entry

6. Double-click Expense Codes 7. In the first Expense Code, type Office Supplies and press Enter 8. Type Software and press Enter 9. Type Printer and press Enter 10. Type Computer Supplies and press Tab 11. Type Car Rental and press Tab 12. Type Air Fare and press Tab 13. Type Meal 14. To close the form, click its system Close button 15. Double-click Work Codes 16. In the first Work Code, type Regular and press Enter 17. Type Web Design and press Enter. 18. Type Data Entry and press Tab 19. Type Database Design and press Tab 20. Type Software Coding 21. To close the form, click its close button 22. Double-click Clients 23. In the First Name text box, type Jose and press Enter 24. In the Last Name text box, type Marillo and press Enter 25. In the 8012 Herald Ave Suite 402 and press Enter 26. In the City text box, type Alexandria and press Tab 27. In the State/Province text box, type VA and press Tab 28. In the Postal Code text box, type 22031 and press Tab 29. In the Country text box, type USA 30. Click in the Company Name text box and type PTN Investors, Inc. 31. Click in the Contact Title text box and type Director of Investments and press Tab 32. In the Phone Number text box, type 7038384422 and press Tab 33. In the Fax Number, type 7038385035 34. Click in the Notes text box and type PTN is an investment firm with offices in VA, MD, 35

and NY and is interested in network technology for its future activities

35. Click the Projects button. This opens the form allowing to process projects related to this client

36. In the Project Name text box, type PTNC01 37. Click the arrow of the Project Manager combo box and select Phillips, David 38. Click in the Client PO# text box and type 1 39. In the Project Description text box, type PTN has contracted us, for one year, to
provide part-time technical support for its existing computer network. We will be in their office every Wednesday all day long

40. In the Est. Total Billings text box, type 16250 and press Tab 41. In the Project Begin Date, type 031898 and press Tab 42. In the Project End Date, type 031899

43. To close the form, click its Close button 44. On the Clients form, click the Time Cards button 45. Click the arrow of the Employee combo box and select Phillips, David 46. Select the date in the Date Entered text box, type 03/18/98 and press Tab. 47. In the Date Worked text box, type 031898 and press Tab. 48. Click the arrow of the Project combo box, select PTNC01 and press Tab. 49. Click the arrow of the Work Code combo box, select Regular and press Tab twice. 50. In the Billable Hours field, type 8 51. In the Work Description field, type Besides regular work, we replaced 2 network
cards on the receptionist and Ms. Maureen's workstations

36

52. Press Tab to move to the next record of the subform

53. For the next record, set the Date Worked to 032598 for the PTNC01 project on
Regular work billable for 6 hours. For the Work Description, type Spent some time training employee on mild issues of computer networking.

54. In the Expense subform, click the Date field 55. Enter 031898 and press Enter 56. On the Project combo box, select PTNC01 and press Enter 57. Click the Expense Code combo box and select Computer Supplies 58. Click the Amount field and type 386.10 59. Click the Description field and type I bought 5 network cards. Two were used right
away. The spares are kept just in case

60. Click the Next Record button 61. On the Employee combo box, select Nice, Helene 62. Replace the Date Entered with 032598 63. In the Time Worked combo box, click the 1st empty field and type 03/25/98 64. Select the Project Name as PTNC01 65. Set the Work Code to Regular. Set the Billable Hours to 6 66. In the Work Description, type We spent a couple of hours on site with Mr. Phillips. 67. To close the form, click its Close button 68. On the Clients form, click the Payments button 69. Click the arrow of the Payment Method combo box, select Check and press Tab 70. In the Payment Date, type 03/04/98 and press Tab 71. In the Payment Amount text box, type 8600 and press Tab 72. To close the Payments form, click its Close button 73. On the Clients form, click Projects to review its form

74. Close the Projects form.

Form Printing
Although not part of their primary role, forms provide a quick means of printing data, especially in the absence of desired reports. There are various issues related to printing forms, including printing all records or just some of them. You can print a form without opening it. Once you know the form you would like to print, locate its name in the Database Window, right-click it and click Print... All records on the form would

37

be printed. When a form is opened, you have the option of printing all of its records or the selected one. Once in Form View, you can click the Print button on the toolbar. To print just one record, navigate to the record you would like to print, click the Form Selection bar to select the record. On the Form View toolbar, click the Print button.

Practical Learning: Printing Forms


1. The Clients form should still be opened. Click the Projects button to open the associated projects. Since we have only one project from this client, we will just print that record

2. On the Form View toolbar, click the Print button


the printer and starts printing 3. Close the Projects form and close the Clients form 4. On the Database Window, double-click Employees

. Notice that the job goes straight to

5. To navigate to the 3rd employee, click the Next Record button

twice

6. After making sure that the desired record is displaying, in this case, the 3rd record, on the main menu, click File -> Print

7. On the Print dialog box, click the Selected Record(s) radio button
8. Click OK 9. Verify that only the displaying employee's record was printed 10. Now we will print records from 2 to 4 11. Navigate to record No.2

12. Click the Record Selector bar

13. Press and hold Shift. Click the Next Record button
Vaughn (even though the record # still displays 2) 14. Release Shift 15. On the main menu, click File -> Print

twice to display the record of Lester

16. On the Print dialog box, click the Selected Record(s) radio button and click OK
17. Verify that records from 2 to 4 have been printed 18. Close the Employees form

Reports Fundamentals
AutoReport
38

A report provides an object used to print a database records. Although you can print tables, queries, or forms, reports are customized to be printer friendly. They can perform and display calculations. Once again, Microsoft Access provides wizards to quickly create reports. The simplest way to create a report is by using the AutoReport feature available either from the New Object button on the Database toolbar or the New Report dialog box.

Practical Learning: Using AutoReport


1. The Rockville Techno database should still be opened On the Database Window, click the Tables button 2. Click the Payment Methods table to select it

3. On the Database toolbar, click the arrow of the New Object button and select AutoReport

4. After viewing the newly created report, close it 5. When asked whether you want to save the report, click Yes 6. Accept the suggested name for the report and press Enter 7. On the menu bar, click Insert -> Report 8. On the New Report dialog box, select AutoReport: Columnar

9. In the combo box, select Expense Codes

10. Click OK 11. After viewing the report, close it 12. When asking to save it, click Yes 13. Accept the suggested name for the report and click OK

The Report Wizard


Microsoft Access can help you create a more elaborate report where you would use one of the

39

pre-designed layouts. This is done using the Report Wizard. The Report Wizard is available from the New Report dialog box that you can access either from the menu bar or from the New button on the Database Window when in the Reports section. If you are using Microsoft Access 2000 or 2002, you can also double-click Create Report By Using Wizard.

Practical Learning: Using the Report Wizard


1. On the main menu, click Insert -> Report 2. On the New Report dialog box, click Report Wizard and click OK 3. On the first page of the wizard, click the arrow of the Tables/Queries combo box and select Table: Employees

4. Click the Select All Fields button


5. Click Next 6. Accept anything in the second page and click Next 7. Accept anything in the third page and click Next

8. In the Layout section, click the Columnar radio button:

9. Click Next

10. Select the Bold Style to preview it. Then click Formal and click Next 11. Accept the suggested Title of the report as Employees and press Enter
12. Scroll down in the report to view the records and close the report

Report Printing
As stated already, the report is the favorite object used to print data. As done with the other objects, you can print a report whether it is opened or not. Before printing a report, you must first select or open it. If you want to print a report without opening it, in the Database window, make sure the Reports section is selected. Then, you can locate and right-click the desired report. If you follow this approach, the report would be sent directly to the printer. If you want to control or customize the printing of a report, first select it in the Reports section of the Database window or open it. Then, on the main menu, you can click File -> Print This would display the Print dialog box, allowing you to select a printer if you have more than one. You can also specify such aspects as the color, the number of copies or the range of records to be printed.

Practical Learning: Printing a Report


1. On the Database window, click the Reports button

40

2. Right-click the Expense Codes reports and click Print 3. To print a report after displaying it, double-click the Time Sheet report to open it 4. On the main menu, click File -> Print 5. Click the Properties button 6. Based on your printer, make it print in black and white or grayscale and click OK 7. Click OK on the Print dialog box 8. After printing the report, close it 9. On the Database window, click the Forms button and double-click Clients 10. From the Clients form, click Time Cards 11. After viewing the Time Cards form, click its Preview Time Card button 12. To print the report, on the Print Preview toolbar, click the Print button 13. After printing the report, close it

Exercises
Tenley Associates Company Expenses
1. Open the Tenley Associates database 2. Use the Form Wizard to create a Columnar form based on the Employees table and
including all fields. Save the form as Employees and set its display Style to Stone

3. Use AutoForm: Columnar from the New Form dialog box to create a form based on the
Expense Details table and save it as Expense Details

4. Fill the Employees form up with the following values, ignoring those not mentioned:
Last Name Bidds Roberts Hoaks Baugh Department Accounting Sales Sales Administration Work Phone (202) 266-5022 (202) 266-5022 (202) 266-5022 (202) 266-5022 Extension 2422 2408 2412 2418

5. Print the Employees form

6. Using the Report Wizard, create a Columnar report based on the Expense Categories
table, including all fields and using the Corporate style. Save the report as Expense Categories and print all of its records Employees Contact Information query. Save the report as Employees Contact Information and print all of its records

7. Using the AutoReport from the Database toolbar, create a report based on the

Database Fields on Sheet


Introduction to Data Fields
A Database From Scratch
Starting a database from scratch allows you to create and add its different parts as needed.

41

When using this process, the main advantage is that you will exercise as much control as possible on your database because you will be creating all of your objects. The disadvantage is that you will miss that primary layout that the Database Wizard offers. Creating a database from scratch simply means starting from a blank database and adding the different components. Of course, after learning how to perform some changes, you will be able to modify some aspects of a database created using the Database Wizard. To create a database from scratch, if you are just launching Microsoft Access, you can select the first radio button. If you had started Microsoft Access already, you can display the New dialog box and, from the General tab, select Database. Creating a database from scratch also means that you create a database file that does not contain any objects. Therefore, the most you must first do is to give this file a name.

Practical Learning: Creating a Blank Database


1. To start a new database, on the main menu, click File -> New

2. From the New dialog box, click the General tab. Then click the Database icon (in Microsoft
Access 97, that will be Blank Database)

3. Then click OK

4. Since Microsoft Access is going to create a file to store the necessary components of your
database, it requires a name Change the name of the file to Red Oak High School

5. Locate the Exercises folder from the parent folder of this ebook and display it in the Save combo box 6. Click Create to create the new database file.

Database Object and Fields


A field is an object used to host, hold, or store a piece of information of a database. Before such an object can perform its function, it must first be created. In the strict sense, the most important or the most regularly used fields of a database are created on a table; but as we have mentioned in previous sections, tables may not be the friendliest windows to present to a user for data entry. For this reason, fields can and should also be created on other windows. The process of making a field available depends on the type of object it will reside on and probably how the field will be used. This leads to two categories of fields: those that can receive or store information and those that can only present or display it. All fields of a table, especially in Microsoft Access, are created to store data. On the other hand, fields on almost all of the other objects (queries, forms, reports) can be made of combinations of already existing fields of a table, or they can be created independently of any existing or non-existing data.

The Table Data Sheet and its Fields


Table Layout
To make fields available on a table, you must create each one of them. Before adding the fields, you must first create the table. There are various techniques available. We have already seen how

42

to use the Table Wizard to create a table. Another technique consists of displaying the table as if you were doing data entering. In this Datasheet View, you can create, add, or insert a field. You can also add fields to a table that was created using the Table Wizard. The last technique you can use consists of designing the table. To create a table in Datasheet View, on the Database window, you can click the Tables button and double-click the Create Table By Entering Data. Alternatively, on the toolbar of the Database window, you can click the New button. You can also click Insert -> Table from the main menu. One of these techniques would display the New Table dialog box from which you can click Datasheet View and click OK..

Practical Learning: Viewing a Table in Datasheet View


1. To create a new database, on the main menu, click File -> New (or File -> New
Database for Microsoft Access 97)

2. In the New dialog box, click General if necessary. Make sure Database or Blank Database is selected and click OK

3. Change the name of the file to Clarksville Ice Cream


4. Locate then display the Exercises folder in the Save In combo box and click Create

5. To create a new table, on the main menu, click Insert -> Table

6. On the New Table dialog box, make sure Datasheet View is selected and click OK

The Title Bar


A table is a rectangular window. icon . The table icon provides the table. The middle section of popup windows, the right section On top, it presents a title bar. The title bar is made of a table's a menu that allows you to minimize, maximize, restore or close the table icon is formally called the title bar. Like most regular of the title bar presents the system buttons.

Columns and Rows


Imagine you create a list of people with whom you have some type of relationship. The list can be started with names as follows: Bill, James, Hermine, and Khan. This type of list is considered onedimensional because all of its items fit in one category. In order to create a more significant list, you may want to include these peoples email addresses and probably other related information. If

43

you include these additional pieces of information in the same category, the list may become confusing. To arrange the list, you would create categories. Here is an example: Name Bill James Hermine Khan @Khan.com Email Address bill@yahoo.com jamesemail.com (102)399-2893 (101) 447-8384 Cousin Phone Number Relationship Friend

This type of display allows you to refer to a piece of information by its category. This is the basis of a table. A table is a two-dimensional list of items so that the items are arranged by categories. A complete or incomplete series of items that represent each category is called a record. Therefore, a table can be represented as follows:

In the world of database development, a category is represented as a column. Sometimes it is also called a field. A record is represented as a row. To better organize its information, each column of a table must have a (unique) name. By default, Microsoft Access creates a table with columns named Field1, Field2, Field3, etc. By default, a table starts with 10 columns. You can add more or delete unneeded ones. By default, a table starts with 21 rows. The number of rows increases as a user adds records. The number of rows decreases if you delete records. As we will learn latter, deleting a row is completely different from deleting a column.

Table Cells
Although a table is primarily recognized as an arranged list of columns and rows, these are hardly important to the user. Each column and each row intersect to create a rectangular box called a cell. The cell is actually the object that holds data of a table. A cell holds only one piece of information. The database developer decides what type of information would go into a cell:

The Scroll Bars


If you start entering data into a table and there are more records than the height of the table can display, the table would be equipped with a vertical scroll bar. The vertical scroll bar would

44

allow you to move up and down on the datasheet. This is useful if/when a table has more records than can be displayed all at once, and this will happen (almost) all the time. In the same way, if a table contains one or more records than the width of the table can display, the table would be equipped with a horizontal scroll bar:

The presence or absence of one or both scroll bars is automatically managed by the operating system. Since you will usually not give your users access to tables, you should not be concerned with the management of scroll bars. If your users need to use a table, they know how to use a scroll bar.

Table Navigation Buttons


The lower left side of the table is made of five buttons used to navigate the table or create records, and a text box. Each button plays a specific picture: Object Role First Record: allows moving to the first record of the table Previous Record: allows to move one record back (if there is one) from the current record Record Indicator: Displays the number representing the current record Next Record: allows moving you one record ahead Last Record: Allows moving you to the last record of the table New Record: Used to enter a new record on the table

Table Creation in Datasheet View


Fields Names
Once a table displays in Datasheet View, you can simply start entering data into its cells but because the columns would have insignificant names, you should make sure they display names that can identify their type of information. A field can have almost any name: "Book Title", "This Is The Book Title", "My Book Titles", etc. Some of your fields will have only tinny data, like a person's age, the number of books in an office, a persons middle initial, etc, it might not be a good idea to give them a name that would take too much space. In the future, when you start programming, it would be easier to handle field names that are composed of only one word, without an empty space. To name a field, first figure out what the data in the category will be made of. If you are planning to enter employees' salaries in a field, you can just call the field Salary. If you want to specify employees names by first name, middle name, and last name, you can use such field names and make them distinct. In this case, you could name the first field as firstname (in one word), the last name would be called lastname. Although this good technique allows you to use one word name, some people including yourself might be confused. The suggestion is to distinguish

45

wherever a new English (or the language you are using to design your database) name starts in the field name, by using a starting uppercase. Instead of firstname, you can use FirstName. Instead of fullname, you can use FullName. Instead of firstdayofmonth, you can use FirstDayOfMonth. To change the name of a field, you can click its column header, such as Field1. You can also rightclick a column and click Rename Column. Alternatively, when any cell under a column has focus, on the main menu, you can click Format -> Rename Column and type the new desired name.

Practical Learning: Naming Datasheet Fields


1. Double-click the header of the first field: Field1. When it is highlighted, type OrderDate
and press Enter

2. Click anywhere under the Field2 column to activate it 3. On the menu bar, click Format -> Rename Column. That puts the field name in edit mode

4. Type OrderTime
5. Right-click Field3 and click Rename Column from the context menu

6. Type Container and press Tab

The Name of a Table


Like everything that is part of a database, a table must have a name that can be used to refer to the object throughout the database in other files that can be linked to the table. Fortunately, when you perform data entry, information you type into a table is saved immediately, as soon as you move to another cell. There are two main ways you can specify the name of a table, either when you save it for the first time or if you decide to rename it. To save a table you have just created, on the main menu, you can click File -> Save. You can also press Ctrl + S. You could also perform a trick by trying to close the table. You would be prompted to save the table (if its structure has been changed from the structure it had before it was opened). If a table has not been saved before, you will be asked to provide a name for the table. A table can have any name. With the same concerns we had when creating field names. This time also, there are suggestions made to you. First, the name of a table should reflect the kind of data it is holding. Second, you can name a table with a few words, with spaces; but for the same reasons mentioned earlier, keep the name of a table in one word. The last suggestion sometimes states that you use a prefix that identifies the table as such, a table. The name of a table would be preceded with tbl. If the name includes one word, such as Musicians, you can give the table a name like tblMusicians,

46

another name would be tblStudents. If the name of the table reflects a combination of words, such as Bank Accounts or Students Academic Numbers, start each new word with an uppercase. Here are examples: tblBankAccounts, tblStudentAcademicNumbers, tblMemberRegistrations. Unlike the previous version of this site, we will not use the convention of prefixing the name of a database object with a three letters. For example, the names of tables will not start with tbl. We came to this decision because most other database environments, including Microsoft SQL Server, do not suggest this rule. Although the lack of this rule may create some confusion, because you will end up having a table and a form with the same name, we will strive to explicitly state what object type we are referring to. For example, we will avoid writing, Open Employees or Open the Employees object. Instead, we will usually state, Open the Employees table. This should clearly indicate that you must first click the Tables button in the Database Window because the tables are only in the Tables section, and then open the indicated table. In the same way, if we write, Open the Employees form, you must first click the Forms button in Database Window, then open the indicated form.

Practical Learning: Saving a Table


1. On the Table Datasheet toolbar, click the Save button to save the current table

2. Type CustomersOrders and press Enter


3. You will receive a long message box. Click No

4. To close the table, click its system Close button

Column and Row Maintenance in Datasheet View


Introduction
A database table and its fields are made of special properties that govern how a table displays its data and how the fields behave. Most of these features are highly customizable. The most important properties you will need to know from a table can help you decide what fields a table should display and in what sequence. Although users will usually not have access to your tables, you should still be aware of some of the internal configurations of a table so you would know what they can do on tables. Anticipating some of the features you will need to implement when designing tables, such as hiding and displaying items, freezing and unfreezing them, it is a good idea to know how these features operate on a table.

Column Insertion
One of the jobs performed when maintaining or improving a table consists of adding new and necessary columns that were not previously available. This can be done in various ways. In the Datasheet View of a table, you can only insert a column in the middle of two existing columns or you can insert a new column to the beginning, that is, to the left of the first column. You cannot simply add a new column at the end of, that is, after the most right column of, the table. To add, that is, to insert a new column, you can right-click the column header that will succeed the new column and click Insert Column. Alternatively, if the caret is positioned in any cell under the column that will succeed it, on the main menu, you can click Insert -> Column.

Practical Learning: Inserting a Column


1. The Clarksville Ice Cream database should still be opened and the Tables button should be
selected in the Database window On the Database window, double-click the CustomersOrders table to open it

2. To add a new field, right-click the OrderDate column header and click Insert Column

47

3. Right-click the new Field1 column header and click Rename Column

4. Type Clerk and click the cell under Container


5. To insert another column, while the Container column has focus, on the main menu, click Insert -> Column 6. While the caret is under Field1, on the main menu, click Format -> Rename Column

7. Type Flavor and press Enter


8. Enter the following records in the table: Clerk Paulette McIntyre Ralph Ammian Alex Mendy Ralph Ammian 9. Close the table 05/10/2000 OrderDate 05/10/2000 05/10/2000 OrderTime 10:16 AM 10:28 AM 11:35 AM Flavor Vanilla Butter Pecan Vanilla Container Cup Cone Cone

Chocolate Cream Bowl

Column Selection
Many times during design or once users have started using your database, you will find that a sequence of fields is not appropriate. In order to move fields, you should know how to select them: To select a column, click the desired column header and release your mouse To select more than one column, click and hold your mouse on one of them, then drag to cover the other desired column or columns, when all desired columns are highlighted, release the mouse To select more than one column, click one column that will be at one end, press and hold Shift, and then click the column that will be at the other end

Practical Learning: Selecting Columns


1. Right-click the CustomersOrders table and click Open

2. To select a column, position the mouse on OrderTime until the mouse cursor turns into a
down-pointing arrow

3. Then click

48

4. Notice that the whole column has been selected 5. To select columns in a range, click and hold the mouse on Container

6. Then drag left until you get to OrderTime

7. Then release the mouse 8. To use another technique of selecting columns, click Flavor 9. Press and hold Shift 10. Then click Clerk and release Shift 11. Close the table

Column Deletion
After creating a column, if you find out that you do not need it anymore, you can delete it. If you had created a relationship that the column is involved in, you cannot delete it until you break or delete the relationship first. To get rid of a column you do not need anymore, you can right-click it and click Delete Column.

Practical Learning: Deleting Columns


1. Double-click the CustomersOrders table to open it 2. Right-click OrderTime and, from the context menu, click Delete Column 3. When a message box displays, read it and click Yes 4. Close the table

Column Moving
If you find out during design, data entry, or database maintenance that a particular field is misplaced, you will likely want to move it for better navigation or to ease data entry. To move a column or group of columns in Datasheet View, first select that column or those columns. Click and hold your mouse on it (or one of them). Then, start dragging left or right in the desired direction. While your mouse is moving, a thick vertical line will guide you. Once the vertical line is positioned to the desired location, release the mouse.

Practical Learning: Moving a Column


49

1. Open the ROSH database and, on the Database window, click the Tables button. Open the Staff table in Datasheet View 2. Scroll right or left so you can see the Sate and the ZIPCode fields at the same time

3. To move a field, position the mouse on the ZIPCode column header until the mouse cursor
turns into a down-pointing arrow:

4. Click to select the whole column (that means click once and release the mouse) 5. Click the selected column header again and hold the mouse down.

6. Drag in the left direction until the guiding vertical line is positioned between State and
HomePhone:

7. Then release the mouse. Notice that the ZIPCode column has moved 8. Make sure you can see the HomePhone, the WorkPhone, and the MaritalStatus fields. To select two fields, position the mouse on HomePhone. With the mouse cursor pointing down, click and drag in the right direction until WorkPhone is selected, then release the mouse. 9. Click one of the selected column headers and hold your mouse down 10. Drag in the right direction until the guiding vertical line is positioned on the right side of MaritalStatus 11. Then release the mouse 12. To select a group of columns, click the MaritalStatus column header to select it 13. Press and hold Shift, then click the WorkPhone column header and release Shift 14. Click one of the selected column headers and hold your mouse down.

15. Drag in the left direction until the guiding vertical line is positioned to the left of
Extension:

16. Then release the mouse 17. Save and close the table

Record Selection
50

To select a row or record in Datasheet View, click the desired row header and release your mouse. To select more than one record, click and hold your mouse on one of them, then drag to cover the other desired row or rows. When all desired rows are highlighted, release the mouse. Another technique used to select more than one row consists of clicking one row that will be at one end, press and hold Shift, and then click the row that will be at the other end.

Practical Learning: Selecting Records


1. Open the Clarksville Ice Cream database (it should still be in the list of Most Recently Used files under the File menu category) 2. Double-click the CustomersOrders table to open it

3. To select one record, position the mouse on the gray button to the left of the third record
until the mouse turns into a right pointing arrow

4. Then click 5. Notice that all cells of the second records are highlighted 6. To select a range of records, click the gray button to the left of the fourth record. Then click once

7. Press and hold Shift. Then click the gray button to the left of the second record, and
release Shift

8. Notice that three records have been selected 9. Close the table

Record Deletion
If a record is not needed anymore or has become irrelevant in a database, you can delete it. To do this, right-click the record selector button, which is the gray box, on the left side of the most left field of the record, and click Delete Record from the context menu.

Practical Learning: Deleting Records


1. Open the CustomersOrder table

2. To delete a record, right-click the gray button to the left of the second

51

3. Click Delete Record 4. A warning message box will appear. Read it and click Yes 5. To delete more than one record, click and hold the mouse on the gray button to the left of the second record, then drag down to include the third record in the selection 6. On your keyboard, press Delete 7. Read the warning message box and press Enter 8. To close the table, press Ctrl + F4

Columns Width and Rows Height


The columns and rows of a table use some default values to display their records and fields. When data exceeds the regular width of a column, part of the information would be hidden. If a particular column contains data that you want to display at all times, you can enlarge the column. On the other hand, if a column displays short pieces of information, such as one character for middle initial or two characters (US states or Canadian provinces), you can narrow the column to let it just fit the data as desired. In the same way, you can heighten or shrink rows of a table as you see fit. There are various techniques you can follow to widen or narrow a column. You can position the mouse on the right border of the column header. The mouse pointer would change into a horizontal double arrow crossed by a vertical beam. If you double-click, the column would be sized to the widest value of the column, provided the widest value is wider than the column header. If the widest value is narrower than the column header, the column width would be wide enough to display the caption of the column. On the other hand, you can change a column's width by clicking on the column's right border and dragging in the desired direction. To set or change the rows height, you can position the mouse on one of the rows lower border, then click and drag in the opposite direction.

Practical Learning: Changing Columns Width and Rows Height


1. Open the Rockville Techno database that you started in Lesson 2 and, in the Database window, click the Tables button 2. From the Tables section of the Database window, double-click the Employees table to open it

3. To resize the First Name column, position your mouse on the line between First Name and
Last Name until the mouse pointer appears as an I-beam (also called a pipe) with a horizontal double-arrow:

4. Then double-click

5. To resize the Address column, position your mouse on the line between Address and City:

52

6. Then click and drag in the right direction until the mouse is positioned in the middle of
City:

7. Release the mouse 8. Right-click the Country column header and click Column Width...

9. In the Column Width dialog box, type 12.50 to replace the default value

10. Click OK 11. Click and cell under the Title column 12. On the main menu, click Format -> Column Width... 13. On the Column Width dialog box, click Best Fit and click OK 14. Save and close the table

Exercises
Yugo National Bank
1. Create a blank database and name it Yugo National Bank 2. Using the Table Wizard, create a table based on the Accounts sample table of the
Personal category. Include the following fields: AccountTypeID, AccountType, and Description. Save the table as AccountTypes and fill it up as follows: Account Type ID Account Type Description 1 Checking 2 Saving 3 CD

3. Using the Table Wizard, create a table based on the Employees sample table of the

Business category. Include the following fields: EmployeeID, DepartmentName, EmployeeNumber, FirstName, LastName, Title, EmailName, WorkPhone, Extension, Address, City, StateOrProvince, PostalCode, Country, HomePhone, Salary, and Notes. Save the table as Employees and fill it up with employees records Customers sample table of the Business category. From the Accounts sample table of the Personal category, include the following fields: AccountNumber, AccountTypeID, AccountName. From the Addresses sample table, include the following fields: Address, City, StateOrProvince, PostalCode, Country, EmailAddress, HomePhone, WorkPhone, WorkExtension, DateUpdated, and Notes. Save the table as Customers and fill it up with sample customers records

4. Using the Table Wizard, create a table including the CustomerID field from the

53

Watts A loan
1. Catherine Watts lives in Baltimore, Maryland, US. Eight months ago, while living with her
father, one weekend, she went to attend the wedding of her friend in Chicago. Meanwhile, her father had a heart problem and was rushed to the hospital after a neighbor found him on the floor of his dining room. The attending doctor wrote on a chart that Catherine's father would be kept nightly for further examinations. While her father was still lying in bed in the hallway and sleeping, a nurse came back and from some events that nobody recalls, Mr. Watts' chart was modified. Next, he was taken to a surgery room since his chart now indicated that he had been in an unrecoverable accident but that he was a happy organ donor. In the next few minutes, his body was cut in various pieces. His right liver was sent to Canada while the other gave new hope to a patient in California. His left eye gave new site to a woman in Mexico and his skin allowed a man who had been in the center of a mass fire a new cover for his body. The rest of his organs were spread in the region like salt in boiling water. When the attending doctor came back to look for his patient, he found out what had happened but it was quite late to undo anything. When Catherine came back from Chicago and was asked to recognize at least what was left of her father, she was furious but calmly considered it was an accident. At her friend's insistence, she sued the hospital and got a five-million-dollar settlement. To make sure she would not spend all that cash picking up men in bars and night clubs, her friend encouraged her to open a business. Since Catherine had taken some classes in banking management, she decided to open a money lending institution. She would lend money to individuals through car dealers, music instrument stores, furniture stores, and personal loans, etc. She has contracted you to create an application that can help her manage her business. Create a blank database and name it Watts A Loan Mailing List sample table) FirstName, MiddleName, LastName, Address, City, State, PostalCode (rename it ZIPCode), Country, HomePhone, WorkPhone, EmailAddress, and Notes. Name the table as Customers

2. Using the Table Wizard, create a table with the following fields: CustomerID, (and from the

3. Using the Table Wizard, create another table with the following fields: TransactionID,

TransactionNumber, TransactionDate, TransactionAmount, and Notes. Save the table as Transactions

Managing Data Fields


Table Design and Fields
Introduction
So far, to get acquainted with database fields, we have used two techniques of creating a table and some techniques of adding fields to a form. One of the techniques we used, the Datasheet View, provides a very simplistic way. The Datasheet View is mainly used to perform data entry or to test some fields. It has so many limitations that you will hardly use it. For example, you cannot control or customize the behavior of fields if you create the table in Datasheet View. The other technique we used, the Table Wizard, allows you to use some already created and customized fields. For one thing, you would not know what exactly those fields are configured to do and whether they can control data entered in them. For another thing, if you do not like the way they behave, you would have to modify the configuration that was already done. This is why you should know how to design your tables. Table Design consists of creating a list of columns, specifying the type of information they can receive, and controlling their behavior. To design a table, you should display it in Design View, which is a display other than Datasheet View. To create a new table in Design View, on the menu bar, you can click Insert -> Table. You can also click the arrow of the New Object button on the Database toolbar and select Table. As another alternative, you can click the New button on the Database Window's toolbar while in the Tables section. Any of these actions would call the New Table dialog box. In the New Table dialog box, you can click Design View and click OK.

54

The quickest way to create a table in Design View when using Microsoft Access 2000 and later versions is to double-click the Create Table In Design View link from the Database Window.

Practical Learning: Introducing Table Design


1. Open the Clarksville Ice Cream database that you started

2. In the Database Window, if necessary, click the Tables button


From the Database Window toolbar, click the New button to create a new table

3. On the New Table dialog box, click Design View and click OK

The Table in Design view


The title bar of a table in Design View presents the tables icon on the left section. Like most other windows, the table's icon holds the table's system menu. This system icon can also be double-clicked to close the table. The long empty section of the title bar is different from a classic window. Instead of being used to maximize, minimize, move, or close the table, it provides features adapted for the database object it is. For example, at a minimum, it can be used to switch views. To use its function, you can right-click it. This would present a menu you can select from:

The right section of the title bar presents the system buttons of a regular window. They can be used to minimize, maximize, restore, or close the table. On the left side of the view, the row headers allow you to select a row completely. The most left gray button allows you to select everything on the table while in Design View:

55

The File Name column is used to type a name for each field. The rules we used when in Datasheet View apply here. A field can have any name but keep a name with one word and no space.

Practical Learning: Creating Columns in Design New


1. While in Design View, click the first empty box under Field Name, type EmployeeID 2. Press the Tab key three times and type DateHired 3. Press the down arrow key and type EmployeeNumber 4. Press the down arrow key and type FirstName 5. Press the down arrow key and type MiddleInitial 6. Press the down arrow key and type LastName 7. Press the down arrow key and type WorkPhone 8. Press the down arrow key and type Extension 9. Press the down arrow key and type EmailAddress 10. Press the down arrow key and type Address 11. Press the down arrow key and type City 12. Press the down arrow key and type State 13. Press the down arrow key and type ZIPCode 14. Press the down arrow key and type Country 15. Press the down arrow key and type Salary 16. Press the down arrow key and type MaritalStatus 17. Press the down arrow key, type Notes and press Tab 18. To save the table, on the Table Design toolbar, click the Save button 19. Change the name of the table to Employees and click OK

56

20. You will receive a long message box about a lack of a primary key (we are not there yet). Click No 21. Close the table

Field Renaming
One of the jobs involved with database design and maintenance is to review fields and make sure they are explicit enough for the user. There are three issues related to a field's name. Some fields, as you will find out, are involved in relationships, and you will have to be careful when deciding to change their name. The other issues are related to a field's actual name and its caption. A field's name is mainly made of two parts from the developer's standpoint: the actual name and the caption. A field's name is stored as part of the table and is involved with any business dealing the table has to cope with. The caption simply guides the user in identifying the use of a particular field. These two items are not strictly related. For example, you could have a field whose name is SocSecNbr while its caption displays Nat Number From Gvt and this will not affect the functionality of the table. Overall, as a developer, you should pay attention to your fields names because these are the names you will refer to when performing calculations and other programming issues. To rename a field in Datasheet View, use any of the techniques we learned to change a field's name. After you have typed the name, the new name will replace the old one. To rename a field in Design View, click it and type the new name.

Practical Learning: Renaming a Field


1. Open the Rockville Techno database. In the Database window, if necessary, click the Tables button 2. Double-click the Employees table to open it 3. Complete the records as follows: First Name Christine Joseph Joanne Last Name Barley Kumar Herbie Title Administrative Assistant Network Administrator Accountant Extension 106 105 108 Billing Rate 16.82 20.65 22.48

4. To switch the table to Design View, right-click its title bar and click Table Design

5. In StateOrProvince, click between the most left e and O. Then press and hold Delete until
the Field Name displays State

6. Press the down arrow key to select PostalCode and type ZIPCode 7. Double-click EmailName, type EmailAddress and press Tab
8. Save the table and close it

Field Selection in Table Design View


57

In the Design View of a table, there are various types of operations you can perform for database maintenance. Operations include naming or renaming fields, moving or deleting fields, and changing various other properties. In order to perform some of the operations on a field or a group of fields, you must first select one. To select one field, you can position the mouse on the gray box to its left and click To select more than one column, you can click and hold your mouse on one of the left gray boxes, then drag up or down to cover the other desired field names. When all desired field names are highlighted, release the mouse To select more than one column, you can also click one column that will be at one end, press and hold Shift, then click the column that will be at the other end To select columns at random, click the left gray box of one of them, press and hold Ctrl, then click the gray box of each of the desired boxes

Column Moving in Table Design View


The columns of a table are displayed in the sequence in which they were created. We learned earlier how to change this sequence in Datasheet View. You can also change the sequence of fields in the Design View of a table. To move a column or a group of columns, after making the selection, click the gray box of the field name or one of the gray boxes of one of the selected fields and hold the mouse down. Then drag up or down. A horizontal line will guide you. Once it gets to the desired location, you can release the mouse

Practical Learning: Maintaining Fields in Table Design View


1. The Rockville Techno database should still be opened. To open the Employees table in Design View, in the Tables section of the Database window, right-click the Employees table and click Design

2. While in the Design View of the table, click the gray box on the left of Extension to select
it

3. Click the same box again and hold the mouse down. Then drag it down until the guiding
horizontal line is positioned under WorkPhone

58

4. Release the mouse

5. To select various fields, position the mouse pointer to the left gray box of the HomePhone
field until the mouse pointer changes into a right pointing arrow:

6. Click and hold the mouse down. While holding, drag down to Extension to select those 3 fields, and release the mouse 7. To move the selected fields, click and hold the mouse on one of the black selected boxes on the left of the field names

8. Drag up until the guiding horizontal line is positioned on top of Title:

9. Then release the mouse 10. Save and close the table

Field Insertion
When it comes to tables, the best place to add new fields is in Design View because this view provides more flexibility. In Design View, you can insert a new field at any position. You can also add a new field to the end of the table, a feature that is not available in Datasheet View. You can also use one of the same fields as we saw when using the Table Wizard: To insert a new column, you can right-click the field that will succeed it (you can right-click anywhere on the horizontal boxes of the column, that is, on the Field Name, the Data Type, or the Description columns), click Insert Rows, and type a name for the new column To insert a new column, you can also click anywhere on the column that will succeed it. Then, on the main menu, click Insert -> Rows. Alternatively, when a column has focus, on the Table Design toolbar, you can also click the Insert Rows button To add a new column at the end of the table, click the first empty field under Field Name and type the desired name To use one of the fields available from the Table Wizard, right-click either the first empty field under Field Name or right-click the field that will succeed it and click Build On the Field Builder dialog box, select the category (Business or Personal), select the desired field, and

59

then click OK

Practical Learning: Inserting New Fields in Table Design View


1. The Rockville Techno database should still be opened. To open the Employees table in Design View, in the Database window, click it to select it if necessary. Then, on the Database window, click the Design button

2. To add a new field at the end of the table, click the first empty box under BillingRate. Type
Observations and press Enter 3. To insert a new field before LastName, right-click LastName and click Insert Rows

4. Type MiddleName and press Tab


5. To insert an already configured field, right-click EmployeeNumber and click Build 6. In the Field Builder, click the Business radio button if necessary. In the Sample Tables list, click Employees

7. In the Sample fields list, scroll down and click DateHired

8. Click OK 9. To add another field, click Address 10. On the main menu, click Insert -> Rows

11. Type WebSite and press Enter


12. Save the table

Field Deletion
When in Design View, you can delete a field you don't need anymore or if it was added by mistake. To delete a column, you can right-click anywhere on its line (on the Field Name, the Data Type, or the Description columns) and click Delete Rows. When a column has focus, you can also click the Delete Rows button on the Table Design toolbar to delete it.

Practical Learning: Deleting a Field in Table Design View


1. To get rid of a column, right-click WebSite and click Delete Rows 2. When asked whether you want to permanently delete the field(s), click Yes 3. Save and close the table

60

Queries and Fields


Introduction
We previously learned that fields could be easily added to a query by using the Query Wizard. Fields can also be added while designing a query. To proceed with this approach, the query should be displayed in Design View. To display a query in Design View, if you are using Microsoft Access 2000, from the Queries section of the Database Window, you can double-click Create Query in Design View. Alternatively, do one of the following: On the Queries section of the Database Window, you can click the New button On the main menu, you can click Insert -> Query On the Database toolbar, you can click the arrow of the New Object button and select Query

Any of these techniques would call the New Query dialog box where Design View is selected by default. Otherwise you can select Design View and click OK. To start a fresh query, the database needs to know where data would come from. Therefore, the Design View displays a list of already existing tables and queries so you can choose which one(s) would provide the needed information:

A simple query can have its data originate from a single table. Therefore, to choose the table that holds the information needed for this query, you can click that table and click Add. You can also double-click it. A simple query can also be built from an existing query. To use such a query, in the Database window, click the Queries button and select the query you want. You can also create a query whose data would originate from more than one table. In this case, the tables must have been previously joined. To select the tables, from the Tables property page of the Show Table dialog box, you can double-click each one of the tables you need. More advanced queries can be built from more than two queries, a table and a query, or a combination of tables and queries. After selecting the table, tables, query, or queries, you can click the Close button of the Show Tables dialog box. If the Show Tables dialog box is closed or for any reason and you want to display it, on the menu bar, you can click Query -> Show Table...

Practical Learning: Introducing Query Design


1. Open Windows Explorer or My Computer. From the resources that accompany this site, copy the Bethesda Car Rental1 database and paste it in your Exercises folder

61

2. Open the Bethesda Car Rental1 database and, in the Database Window, click the Tables button 3. Click the Cars table to select it. Then, on the toolbar of the Database window, click the Open button 4. Scroll to the right of the table to review the columns 5. Close the Cars table

6. On the Database Window, click Queries and click the New button

7. In the New Query dialog box, click Design View and click OK. Notice that you are presented with a list of existing tables 8. On the Show Table dialog box, click Cars

9. Click Add and click

Query Design
The Select Query window presents another classic window. Its title bar displays its system button on the left section. This can be used to minimize, maximize, restore, move, resize, or close the window. Like all Microsoft Access window objects, the title bar displays a special menu when right-clicked:

The right section of the title bar displays the classic system buttons of a regular window. In the top wide area of the Select Query window, the query displays an object (table(s), query (queries)) or a group of objects that was selected to create the query. The lower portion of the query displays boxes that would be used to perform various operations related to the query. The upper and the lower sections of the Select Query window are separated by a splitter bar that you can use to resize them by dragging the splitter bar up or down:

62

Column Insertion
To create the fields for a query, you use the table, query, tables, or queries displayed in the upper section of the window. Once you have decided on the originating object or objects, you can select which fields are relevant for your query: To select one field from the list, just click it To select many fields on the same range, you can click one of them, press and hold Shift. Then click one field on the other end of the desired list To select fields at random, click one of the desired fields, press and hold Ctrl; then click each one of the desired fields To select all fields, you can either double-click the title bar of the list or click the * line on the list of fields.

Once you have made your selection on the list, you can drag it and drop it on the query. Instead of dragging a field or all fields, you can either double-click a field to add it to the query, or double-click the * line to add all fields to the query.

Practical Learning: Select Fields to Build a Query


1. From the list of fields, click and drag Make, then drop it anywhere on the first empty field
on the lower section of the view:

2. On the list, scroll down and click AMFM 3. Press and hold Shift, then click CDPlayer and release Shift. Notice that three fields have been selected

4. Drag the group of items and drop it on the empty column right to Make 63

5. Notice all the selected fields have been added to the query

6. To view the query, on the Query Design toolbar, click the View button 7. After viewing the query, to save it, on the Query Datasheet toolbar, click the Save button 8. Type Cars Audio Options as the name of the query and press Enter 9. After viewing the query, to close it, click its Close button

Column Selection
Sometimes, the idea of using a query is to test data or verify a condition. Therefore, a query, as compared to a table, could provide just a temporary means of studying information on your database. When performing such assignments or when testing values before isolating an appropriate list, you can add, insert, delete, replace or move fields at will. We have already covered different techniques of adding or inserting fields: To select a field in the lower section of the view, click the tinny gray bar of the column header. The whole column will be selected To select a range of columns, click the column header of one at one end, press and hold Shift, then click the column header at the other end

Column Replacement and Deletion on a Query


As seen above, a query is built by selecting columns from the originating list and adding them. If you do not need a column anymore on a query, which happens regularly during data analysis, you can either delete it or replace it with another column: To delete a column, once it is selected, you can press Delete To delete a group of columns, select them and press Delete To replace a column, click the arrow on the combo box that displays its name and select a different field from the list

64

Column Moving
Columns on a query are positioned incrementally as they are added to its list. If you don't like the arrangement, you can move them and apply any sequence of your choice. Before moving a column or a group of columns, you must first select it, then: To move a field, click its column header once. Click it again and hold your mouse down, then drag in the direction on your choice To move a group of columns, first select the group and then proceed as if it were one column

Practical Learning: Manipulating Fields


1. The Bethesda Car Rental1 database should still be opened In the Database Window, click the Tables button and click Cars to select it 2. On the menu bar, click Insert -> Query 3. In the New Query dialog box, double-click Design View Notice that the Cars table is already selected as the originating object 4. In the list of fields, double-click Make, Model, NbrOfDoors, AMFM, Cassette, and CDPlayer

5. To view the query, on the Query Design toolbar, click the View button 6. After viewing the query, to switch back to Design View, on the Query Datasheet toolbar,
click the View button 7. To replace a field, in the lower section of the Design View, click NbrOfDoors and notice that an arrow of a combo box appears

8. Click the arrow of the NbrOfDoors combo box and select CarYear

9. Scroll to the right on the lower section of the view to display the first empty field 10. To add a new field, click CDPlayer and press Tab. Notice the combo box 11. Press and hold Alt, then press the down arrow key and release Alt. This displays the list of the combo box 12. Press the down arrow key a few times until Picture is selected, then press Enter 13. Scroll back to the left 14. To insert a field, drag TagNumber from the Cars list and drop it on top of AMFM 15. Notice that the newly inserted field has been added to the left of the field it was dropped on (In the same way, you can select various fields and decide to insert them to the left of a field of your choice)

16. Scroll to the right side of the lower section of the view until you can see Picture. 65

To delete a field, in the lower section of the view, position the mouse on the tinny horizontal bar above Picture until the mouse turns into a down pointing arrow:

17. Click. Notice that the whole column is selected 18. Press Delete. Notice that the field is removed from the query

19. To view the query, click the View button


20. To switch the query back to Design View, on the main menu, click View -> Design View 21. Scroll back to the left of the lower view and make sure you can see the TagNumber and the Make columns In the lower section of the view, click the bar on top of TagNumber and release the mouse 22. Click the TagNumber header bar again and hold your mouse down

23. Notice a vertical line that guides you. Drag left until the vertical guiding line gets between
Make and Model:

24. Release the mouse

25. To view the query, on the Query Design toolbar, click the View button
26. Switch the query back to Design View 27. Scroll the lower section right to see CDPlayer 28. Click and hold your mouse on the bar on top of AMFM. Then drag right to CDPlayer to select the AMFM, the Cassette, and the CDPlayer columns. Then release the mouse 29. Click and hold your mouse again on the bar on top of AMFM 30. Drag left until the vertical line is between the Model and the CarYear columns 31. Then release the mouse 32. To run the query, right-click its title bar and click Datasheet View 33. To close the query, double-click its system icon 34. A message asks you whether you want to save the query, click No (this was a test; it was just a test)

Exercises
66

Yugo National Bank


1. Open the Yugo National Bank database and open the Customers table in Design View. Insert a new field between CustomerID and AccountNumber. Name it DateCreated and close the table

2. Use the Table Wizard to create a new table based on the Accounts sample table of the
Personal category and include only the AccountTypeID field. Rename AccountTypeID as TransactionTypeID. Save the table as TransactionTypes and open it in Design View. Under the existing field, add another field named TransactionType. Using the Field Builder, add a field based on the Notes sample. Rename it Description. Save the table and perform data entry as follows: TransactionTypeID TransactionType Description 1 Deposit 2 Withdrawal 3 Fund Transfer 4 Money Order Used if a customer is depositing money, regardless of the type of account Specifies that a customer is receiving money. This also applies when a check is cashed from the customer's account This applies to an operation that consists of transferring money from one account to another This is selected if a person is purchasing a money order from this bank There are various types of service charges. This category applies to all of them, regardless of the reason, as long as the Bank Management decides to withdraw money from the customer's account as a fee or a penalty

5 Service Charge

3. Close the table

Watts A Loan
1. Open the Watts A Loan database. In the Datasheet View of the Customers table, insert a new field between CustomerID and FirstName. Name it AccountNumber

2. Using the Table Wizard, create a table with the following fields of the Employees sample

table: EmployeeID, DepartmentID , FirstName, LastName, EmailName, Address, City, StateOrProvince, PostalCode, Country, HomePhone, WorkPhone, Salary, and Notes. Name the table Employees and close it new field at the end of the table (under Notes) and base the field on the OrderDate field from the Orders sample table of the Business category. Rename the field as AccountDate then move it up to position it between CustomerID and AccountNumber. Save and close the table Open the Employees table in Design View and change the names of the following fields: Field Name EmailName StateOrProvince PostalCode Salary New Name Username State ZIPCode HourlySalary

3. Using the Design View of the Customers table, use the Field Builder dialog box to add a

4. Save and close the table

Database Fields on Forms and Reports


67

Common Fields of Forms and Reports


Introduction
As we saw in previous lessons, fields are created on a table, then they can be added to a query. Based on the way Microsoft Access deals with fields, a field on a table cannot be created as a combination of other fields, as if it were an expression (unless the field is created as lookup)(We know that other database environments, including Microsoft SQL Server and MySQL, allow using an expression as the value of a column of a table but MS Access doesn't). Instead, the fields on a table are primarily created to store data. On the other hand, as we will see in the next few lessons, a new field can be added to a query as a combination, through an expression, of other fields. Forms and reports present this same solution. Besides using the fields of a table or a query, a new field can be added to a form or report. This is because forms and reports use objects called Windows controls.

Labels
A label is a static object that presents a word or a group of words. The user cannot (directly) change the value that a label is displaying. By default, a label displays its sentence on a gray background.

Text Boxes
A text box is a rectangular object with a white background and thick borders. On a form, a text box either presents information to the user, requests data from the user, or does both. On a report, a text box is used like a label: to display information that would be printed. A text box may not be explicit enough to indicate what it is used for. For this reason, it is usually positioned next to a label. The label is usually positioned on top, or to the left, of the text box it is accompanying. For this reason, a text box is named after the label close to it. For example, and throughout this site, if a text box is placed under, or on the right side of, a label that displays First Name, the text box would be called The First Name Text Box.

Combo Boxes
A combo box is a type of text box that displays an item selected from a list it is holding. On a form, to change an item in a combo box, you can click its arrow and make your selection from the list. On a report, a combo box appears as such only when in design. When printed, only its data displays. Although it depends on the programmer's configuration of the combo box, the user may not be allowed to enter in a combo box something that is not part of the preset list.

Navigation Buttons
Forms and reports are equipped with the same navigation buttons used on tables (and queries). This time, they are used to navigate left and right to the previous or the next records instead of up and down. Object Role First Record: allows moving to the first record Previous Record: allows to move one record back (if there is one) from the current record Record Indicator: Displays the number representing the current record Next Record: allows moving one record ahead Last Record: Allows moving to the last record New Record: Used to enter a new record

Object

Role First Record: allows moving to the first record Previous Record: allows moving one record back (if there is

68

one) from the current record Record Indicator: Displays the number representing the current record Next Record: allows moving one record ahead Last Record: Allows moving to the last record New Record: Used to enter a new record for a form Since you cannot create a new record on a report, this button is not available on it

Practical Learning: Reviewing Controls on Forms and Reports


1. Start Microsoft Access and open the Rockville Techno database that you started 2. On the Database window, click the Forms button. Then double-click the Clients form to open it

3. On the Clients form, click the Time Cards button

4. Notice the Employee and Date Entered labels 5. Also notice the Employee combo box 6. Notice also the Date Entered, the Total Hours, and the Total Expenses text boxes

Forms Fields
Introduction
Microsoft Access is an MDI application. This means that it allows you to open many objects, such as different forms and/or reports at the same time. This lets you switch from one window to another to perform data entry on related objects. A form, by design, provides a friendlier interface and should make its navigation easy for the user. To provide this functionality, a form can be equipped with various types of Windows controls. Some of the objects are used only to display information to the user. Some others allow the user to change data.

69

Subform
A subform is a form that is glued or embedded in another form. It is used to display related data that would otherwise be accessible from another form.

Record Selector
A form is equipped with a special area that allows selecting the currently displaying record. The Record Selector is on the left side immediate to the left border of the form. The Record Selector is not available on all forms. The database developer decides on its availability or not.

Practical Learning: Reviewing Controls on Forms


1. Notice the Time Worked and the Expenses sub forms

2. To view the design of subform, right-click the title bar of the Time Cards form and click
Form Design

3. After viewing the form, right-click its title bar and click Form View

Reports and Controls


Introduction
Like a form, a report uses the same label, text box, combo box, and list box controls. As mentioned already, the appearance of the controls may not be printed as we will see when studying properties of controls, the background and borders of controls can be changed for aesthetic reasons. Such background and borders would be printed.

Subreport
A subreport is a report added to a parent report in a master-detail layout. It allows the user to view data from different tables but that is related to create a more realistic report. Although playing the same roles, subforms and subreports are not created the exact same way.

Practical Learning: Reviewing Controls on Reports


70

1. On the Time Cards form, click the Preview Time Card button 2. To view the design of a subreport, on the main menu, click View -> Design View 3. Notice the Time and Expenses subreports in the Detail section 4. To preview the report, on the main menu, click View -> Print Preview 5. Close the Time Sheet report 6. Close the Time Cards form 7. Close the Clients form

Database Fields on Forms and Reports


Design of Forms and Reports Fields
Common Field Design on Forms and Reports
Forms provide a friendlier look for data entry to the main user of the database. As such, you will spend a great deal of time designing their look, tuning their functionality, and checking their efficiency. Even when creating a product from the Database Wizard, you will usually realize that various objects are lacking critical fields for the role of the object, or the database itself, as software, needs a few more objects. As we have learned already, the quickest way to create forms and reports is by using the Database Wizard. Even if you create your database from scratch, you still can use the AutoForm or AutoReport to get very easily rendered and readily available objects. As it happens, the Database Wizard was configured to create only a limited number of objects. If you need additional objects, you can create your own. If you want to control everything or almost everything on the forms and reports, you will have to get into design. To add fields to a form or a report, you must display the object in Design View. This gives you access to the Controls toolbox, which hosts some of the Windows controls used on forms and reports.

Field Insertion on Forms and Reports


Data on fields of forms and reports fall in three main categories: fields that directly originate from a table or a query, fields created as a combination of existing fields, and fields independent of any other fields. The techniques used to create these fields are different but a field created using one technique can be changed into another category as necessary. If you want to use a field that is already part of a table or a query, before, or when, creating the form or report, you must specify the list that holds the fields. There are three main ways you can do this: While in the New Form or the New Report dialog boxes, or if you are using the Form Wizard or the Report Wizard, you can select the object (table or query) that holds the list of fields from the combo box

If you have already started a form or a report and it is displaying in Design View but you did

71

not yet select the table or report that holds the list of fields, on the Properties window for the form, you can click the arrow of the Record Source field and select the table or query from the list If you want to use only a selected list of fields from a table or a query, start the form or report in Design View without selecting an object. Then, on the Properties window, click the Record Source field and click its ellipsis button. This will allow you to use the Query Builder to create a query that is a list of the needed field. After creating the query, close it. Its Field List would display only the previously selected fields

To add a field to a form or a report, you can either click a control from the Toolbox and click the form or report, or drag a field from the Field List to the form or report.

Introduction to Form Design


When it comes up, a form is presented as a rectangular box made of a form selection button, two rulers, two scroll bars, a horizontal bar labeled Detail, and a gray area:

By default, a form presents a section referred to as the Detail section. This section starts from the Detail bar to the lower end of the section. Besides the Detail section, a form can be equipped with additional sections. To add these sections, you can: Right-click the middle of the form and click either Page Header/Footer or Form Header/Footer On the main menu, you can click View and click either either Page Header/Footer or Form Header/Footer

If you click Form Header/Footer after right-clicking the form, two new sections will be added to the form: the Form Header section on top and the Form Footer section at the bottom:

Although two sections are added, you can reduce one completely so it would not appear to the user. Therefore, you can keep one section and hide the other. If you create a form using the Form Wizard, both the header and the footer sections are added but they are completely

72

reduced so they would not appear to the user. If you want to display them to the user, you must expand them. If you click Page Header/Footer after right-clicking the form, two sections would be added to the form: a Page Header and a Form Header sections. These sections would not appear to the user. They appear only if the user decides to print a form, in which case they would appear on the printed paper. Like the Form sections, you can change either or both the Page Header and the Page Footer sections To create a field on a form, you can click a control on the Toolbox and click one of the sections. You can also drag a control from the Fields List to a section of the form. Normally, you are allowed to add any control on any section but there are suggestions you should follow: You should add in the Form Header section a control that would display a common message of all records. An example would be the title of the form since the Form Header appears on top of the form. Such a field can be made independent of any other field. In some cases, you can also include an expression that can remind the user of the data on the current record. You can also add a companys logo to the Form Header so it can display the same for all records The Detail section is the most commonly used section of a form. It can be used to display any control. It is also the favorite place to display the current record of the form. Every form should (in fact must) have a Detail section. As mentioned already, the Page Header and the Page Footer sections do not appear to the user. If you allow the users to print a form, you can add these sections and create fields on them. On the other hand, if you think the users would not print the form or if you prevent this, you can use these sections to add controls that can be used by the form or database but must be hidden from the user (for example, since you cannot declare (VBA) variables in Microsoft Access, you can include pseudo-variables in the Page sections and refer to these pseudo-variables in your expressions; the pseudo-variables can be added like normal controls and their contents would be used as variables: only you are aware of such controls, not the user).

Practical Learning: Creating Forms Fields


1. The Rockville Techno database should still be opened On the Database window, click the Forms button if necessary. Then, on the main menu, click Insert -> Form

2. On the New Form dialog box, make sure Design View is selected and the combo box is empty. Then click OK

3. If the Toolbox is not displaying, on the Form Design toolbar, click the Toolbox button
On the Toolbox, click Text Box under the Detail bar) and click anywhere in the Detail section (the wide area

4. To add two new sections, right-click the Detail section and click Form Header/Footer 73

5. To save the form, on the Form Design toolbar, click the Save button 6. Type EmployeesOfficeContact as the name of the form and press Enter
7. Close the form

Introduction to Report Design


By its structure, a report resembles a piece of paper that you can use to prepare printable information to the user. Like a form, a report is made of a Selector button, two rulers, two scroll bars, and a Detail section. Unlike a form, by default, a report presents a Page Header and a Page Footer sections:

As you can see, a report appears with three default sections. Like a form, you can add another section on top and another at the bottom of the report. To do this, you can right-click the body of the report and click Report Header/Footer. You can also click View -> Report Header/Footer on the main menu. Additionally, unlike a form, you can create as many sections on a report as you see fit. This is referred to as grouping fields. As mentioned for the form, you can add any control in any section of the report but, unlike a form, it is very important how you use the sections of a report as they have greater influence on the printed product. For this reason, each section can be configured for a specific task. If you are creating a regular report that displays one record per page, you may not need a Report Header and a Report Footer sections. If you are creating a brochure or a document that appears as a catalogue or a book, you may need a Report Header and a Report Footer sections. The sections would appear as follows: The Report Header section is the first page of the report. It can be created and configured like the cover of a magazine or brochure. If you are creating a regular report, you can use the Report Header to display a label that would appear in the beginning of the printed document even if it doesn't appear on its own page. For example, a Report Header section can be used to create a title for the report The Page Header appears on top of each piece of paper printed with the following exception: if the report contains a Report Header section and the Report Header section is configured as a whole page, the Page Header would not appear on the first page printed The Detail section is used to display regular data of the report. It is presented on each page except on the first if the report includes a Report Header and on the last if the report includes a Report Footer sections The Page Footer section is like the section that displays page numbers or footnotes of a book. It appears on each page The Report Footer section is the last page of the document. It is like the back page of a book or a magazine.

Practical Learning: Creating Reports Fields


74

1. On the main menu, click Insert -> Report

2. On the New Report dialog box, make sure Design View is selected and the combo box is empty. Then click OK

3. To add a control, on the Toolbox, click Text Box


section

and click anywhere in the Detail

4. To add two new sections, right-click anywhere in either section of the report and click Report Header/Footer

5. To save the report, on the Report Design toolbar, click the Save button 6. Type ListOfAssets as the name of the report and click OK
7. Close the report

Exercises
Yugo National Bank
Open the Yugo National Bank database. Start a new form in Design View. From the Toolbox, add two text boxes to the Detail section. Save the form as AccountTypes and close it.

Data Field Design


Fields Design Techniques
Introduction
As a database is expanding, so are its objects. For example, many of the tables created by the Database Wizard lack some fields that otherwise would not suit a particular scenario. As we learned already, you can add new fields to a table. Since such new fields are not added to the corresponding forms or reports, you have to insert these fields in the appropriate objects. Even though the Form Wizard or the Report Wizard can be used to create quick objects, you still have the option of changing or improving their look by moving fields around and changing the sequence of fields navigation. The modification and design of a form or a report is done in Design View. A form or report in Design View displays the same window controls we have used when performing data entry. This time, these controls are equipped with handles that allow you to move them anywhere on the object. To perform your design, a form is equipped with two rulers, one horizontal on the top section of

75

the form, and one vertical on the left section, to help you be more precise with dimensions. To assist with controls design, you can use a toolbox equipped with buttons, text boxes and other items to give a lot of flexibility to your application. You also have the originating table, the field list, on your screen in case you want to add an item that you did not include in the beginning. When you do not need any or both of these two items, you can hide them by clicking their buttons on the toolbar.

Form and Report Design Accessories


During form design, there are accessories you will display and dismiss at will. These are the Field List, the Toolbox, and the Properties window. All of these objects are modeless windows. Therefore, you can display one at a time or all of them at the same time and continue designing your form. The Field List is a small window that displays a list of items that are related to the form you are building. These items are from the data source that could be a table or a query. To display the Field List, on the Form Design toolbar, you can click the Field List button . When the Field List is displaying on your screen, the button appears clicked. To dismiss the Field List, click the same button. You can also close it by clicking its Close button . When the list is not displaying, its button looks "normal". You can also perform these operations of displaying and dismissing the Field List using the menu bar under View. You can resize the list as needed by dragging one of its borders or corners. The Field List

The Toolbox The Toolbox presents a list of some of the most common window controls, Some of these controls can be associated with fields of your Field List; some others can be configured to relate to another existing control on the form. Yet, another control can behave independently of anything else that is on the form. To display the Toolbox, on the Form Design toolbar, click the Toolbox button . You can also close it using either the same button on the toolbar, or clicking its own Close button . You can also use the menu under View.

The Properties Window

Made of five property pages, this Properties window displays the characteristics associated with the object or the control that is selected on the form. To get the Properties window of the properties associated with a control, right-click that control and click Properties. To display the Properties window for the form, double-click the button that is at the

76

intersection of both rulers . You can also click the Properties button toolbar to toggle the Properties windows.

on the Form Design

Forms, Reports, and Data Existing Fields


As mentioned already, on forms and reports, you can create fields that do not exist on tables or queries, as we have done so far in this lesson. Alternatively, when in the New Form or the New Report dialog box, you can select the object that holds the list of fields in the combo box.

If you had started the design of a form or report already, you can display its Properties window and select an object in the Record Source combo box

Practical Learning: Using Existing Fields of a Table or Query


1. Open the Rockville Techno1 database 2. On the Database Window, click the Forms button if necessary and double-click EmployeesOfficeContact

3. After viewing the form, to switch it to Design View, on the Form View toolbar, click the
View button If the Field List window is not displaying and if you are using Microsoft Access 2000 and above, on the Form Design toolbox, click the Field List button

4. On the form, double-click the button at the intersection of both rulers


Properties window of the form

to display the

5. In the Properties window, click the Data property page. Click the arrow of the Record

Source button and click Employees. Notice that the Field List is now equipped with fields (If you are using Microsoft Access 97, now you can display the Field List button)

Data Field Design


77

Fields Design Techniques


Forms, Reports, and Queries Fields
If you want to use just a few fields from a table or an existing query, you can set it as the source of a form or report. Otherwise, you can create a new list of fields that are retrieved from a table or an existing query. To do this, you must build a query. To build a new query that would serve as the source of a form or report, when in Design View, display the Properties window for the form or report and click the ellipsis button of its Record Source. Then proceed as we learned to add or insert fields for a query. Once you have finished, you can close the query. It would become the source of data for the object. If the form or report had already been created with fields that do not exist on the list, these fields on the form or report would become orphans. For example, suppose you create a form or report based on a Record Source such as Employees:

Because you can, suppose you don't want to start the design of a new form but instead decide to change the Record Source of the form to something else like Customers:

Consequently, the fields that were created from the Employees set of records but that don't exist on Customers would have lost their "ties". When such a form or report displays, the "orphaned" controls would display #Name? error:

78

For such controls, you can then either delete them or change their own data source.

Practical Learning: Creating a Query as a Record Source


1. Press F11 to display the Database window On the Database window, click the Reports button and double-click the ListOfAssets report

2. To switch it to Design View, on the Print Preview toolbar, click the View button 3. Click the button at the intersection of both rulers
. In the Data tab of the Properties

window, click Record Source and click its ellipsis button 4. On the Show Table dialog box, make sure the Tables tab is selected. Double-click CompanyAssets and click the Close button 5. On the list of fields, double-click AssetType, Make, Model, and PurchasePrice

6. Close the Query Builder window 7. When asked whether you want to save the statement, click Yes 8. While the caret is still in the Record Source field of the Properties window, press Enter 9. Notice that the Field List got filled with the fields that were selected 10. Close the Properties window 11. Close the report. When asked whether you want to save it, click Yes

Form and Report Design: Controls Insertion


79

When designing a form or a report, one of the most usual actions you will perform consists of inserting items from the Field List to the form or the report. To add a field, you can drag it from the list to the desired section on the form or report. To drag many fields at the same time, first select them. To select all items at the same time on the Field List, you can: Double-click the title bar of the field list Click the item on one end of the list, press and hold Shift, and click the item on the other end. In fact, you can use this same process to select fields in a range.

To select fields at random, press and hold Ctrl, then click each one of the desired fields. If you had selected an item but want to remove it from the selection. While still holding Ctrl, you can click the undesired item. After selecting items on the Field List, to add them to a form or report, you can drag one of them and drop it on the form or report.

Practical Learning: Inserting Fields


In the following exercises, there is a 100% guaranty that the fields on our form do not display as those on your form. Therefore, the screenshots are provided only as a guide: they are not showing how your form should or must appear. When we would like you to have the same type of design, we will let you know and we will show you. Based on this, follow only the instructions and don't make any other attempt to change the way your form appears. Don't make it look like ours We have a pretty good idea of what your form looks like. And, if it helps, at least for this exercise: Trust Us. 1. The EmployeesOfficeContact form should still be opened in Design View but behind the Database window. To display it, click any of its sections in the background, avoiding any of the system buttons If you have any of the form's accessories (Field List, Toolbox, Properties window), close all of them leaving only the form open. On the Form Design toolbar, click the Field List button

2. On the Field List, click DateHired and hold your mouse down. Then drag it (DateHired)
from the Field List and drop it in the top left area of the Detail section:

3. Drag EmployeeNumber from the Field List and drop it somewhere in the middle of the Detail section 4. In the Field List, click FirstName. Press and hold Shift, then click LastName, and release Shift. This allows you to select a range of fields

5. Click and hold the mouse on the selection. Then drag and drop it under the
EmployeeNumber field on the form

80

6. To select fields at random, on the Field List, click HomePhone. Press and hold Ctrl. Then click EmailAddress, and BillingRate. Then release Ctrl

7. Click and hold the mouse on the selection. Then drag and drop it in the upper right area
of the Detail section

8. Close the Field List 9. To save the form, on the Form Design toolbar, click the Save button

Rulers and Dimensions


Since the rulers are dimensionally configured, there are divisions inside of the rulers to help you be more precise. Between two numbered dimensions, there are 7 marks that create 8 divisions. The mark in the middle, a little taller than the others, represents the middle of two dimensions. In this site, the middle division will be referred to as . The first division on the right side of a number represents 1/8 of a dimension, the 2nd represents 2/8 = of a dimension, the 3rd represents 3/8, and that is why the 4th represents 4/8 = . This is how we will refer to these dimensions.

Data Field Design


Form and Report Design
Controls Selection
To manipulate controls on the form, you will regularly need to select them. When one control is selected, you can change only its characteristics. When many controls are selected, you can make a change that would impact all of them. To select a control, you can just click it. A control that is selected displays 8 handles around it:

To select more than one control, at random, click one, then press and hold Shift. While holding Shift, click each of the desired controls. After selecting the controls, release Shift.

81

To select controls aligned vertically, click inside of the horizontal ruler above the highest positioned control: everything that would be touched by the fake line will be selected. In the same way, you can select controls that are horizontally aligned by clicking inside the vertical ruler. To select many controls in the same area on the form, click next to one of them and draw a fake rectangle that covers each of the desired controls. All controls touched by the fake rectangle would be selected when you release the mouse. To select all controls on the form, press Ctrl + A. You can also click inside of one of the rulers on one end and drag to the other end.

Practical Learning: Selecting Controls


1. On the form, click the EmployeeNumber text box. Notice that although only the text box was selected, the corresponding label has its upper-left corner selected also 2. Press Ctrl + A. Notice that all of the controls/items on the form have been selected:

3. To dismiss the selection, click an unoccupied area in one of the sections of the form 4. Click the EmailAddress text box. Press and hold Shift. Then click the Middle Name label and the EmployeeNumber text box. Release Shift 5. Notice that these controls have been selected at random 6. Position the mouse inside of the horizontal ruler on an eye drop above the FirstName text box until the mouse cursor turns into a down pointing arrow:

7. Then click. Notice that all items under the mouse cursor when it was clicked have been selected

8. Position the mouse inside of the horizontal ruler at 41/2 until the mouse cursor points down Click
and hold your mouse at that position

9. With your mouse still held, drag left until the mouse pointer is at 27/8: 82

10. Release the mouse. Notice that all controls that were touched by the waving line have been selected 11. Position the mouse inside of the vertical ruler to the left of either FirstName, MiddleName, or LastName labels until the mouse pointer turns into a right pointing arrow, then click 12. Notice that everything horizontally positioned on the right side of the mouse pointer has been selected

13. Position your mouse inside of the vertical ruler at 11/2 until the mouse turns into a right pointing
arrow. Click and drag up until the mouse pointer reaches 5/8:

14. Notice that all controls on the right side of the covered area have been selected. Click an empty area on the form to deselect 15. Click and hold your mouse on an unoccupied area in the lower-right area of the Detail section without touching any control 16. While holding the mouse, drag up and left as if you were drawing a rectangle. While dragging, make sure your rectangle covers a few but not all controls. Then release the mouse 17. Notice that the controls that were touched have been selected 18. Click an unoccupied area on the form to dismiss the selection

Controls Moving
Once a control is selected, as your mouse moves over a selected control, its pointer displays a different cursor. Two of these cursors can be used to move a control: Pointer Role

83

Moves the (one) selected control Moves the control and includes its dependent, if any. Also moves a group of selected controls

Practical Learning: Moving Controls


1. Click the EmployeeNumber label to select it 2. Position the mouse on the upper left corner of the selected control until you see a pointing finger:

3. Click and drag left and right to move the label and position it somewhere 4. Click the EmployeeNumber text box to select it 5. Position the mouse on the selected text box until the mouse pointer turns into an open hand:

6. Click and drag right. Notice that the text box and its label have been moved

7. To see what the form looks like at this time, on the Form Design toolbar, click the View
button

8. To switch the form back to design view, on the Form View toolbar, click the View button
9. Position the mouse on the left side of the MiddleName text box. Click and drag down and right as if you were drawing a rectangle. When the mouse reaches and touches the LastName text box, release it. Notice that all the text boxes that the rectangle touched have been selected 10. Position your mouse on one of the selected controls until you see an open hand. Click the drag left until the MiddleName label is at 1 unit right from the vertical ruler. Notice that all text boxes and their labels have moved 11. Click the First Name label. Press and hold Shift. Then click the following labels: Middle Name, Last Name, Home Phone, and Email Name to select them. Release Shift 12. Right-click any of the selected label. Position the mouse on Align and click Left 13. Click an unoccupied area on the form to dismiss the selection

Controls and Sections Sizing


Resizing an object allows you to change its height or its width. This can be applied to forms, reports, their sections, or the controls they are hosting. To physically change the width of a form or a report, position the mouse on its right border until the cursor turns into a vertical beam with a double-horizontal arrow:

84

Then click and drag left or right until you are satisfied. The height of a form or report is controlled by its sections. For this reason, each section controls its own height. The total heights of all sections constitute the height of the form. Based on this, to resize a form, you must actually resize one or some of its sections. To heighten a section on a form or a report, position the mouse on the lower portion of the section. For the headers or the Detail sections, that will be the upper border of the lower bar. For the lowest section, the mouse must be positioned on the lower border. The cursor turns into a narrow horizontal line with a vertical double-arrow:

To change the width of the form or report and the height of the lowest section at the same time, you can position the mouse on the lower-right corner. The cursor would change into a small square with 4 arrows:

You

can

then

click

and

drag

left,

right,

up,

down,

or

diagonally.

When the mouse moves over a selected control and reaches one of the handles, the mouse pointer displays a double-arrow cursor. The possible mouse pointers are: Pointer Role Shrinks or heightens the control Resizes the control in North-East <-> South-West direction Narrows or widens the control Resizes the control in North-West <-> South-East direction Although these pointers can be used to resize one control, they can also be applied to a group of controls.

Practical Learning: Resizing Controls


1. To increase the height of the Form Header section, position the mouse on the upper border of the Detail bar. Click and drag down until the line reaches the third mark inside the vertical ruler:

2. To narrow the form, click and drag the right border of one of the sections to the right until

85

it is at 4 grid units right from the most right control 3. Click and unoccupied area on the form to dismiss the selection (just in case a control is selected) Click the EmployeeNumber text box to select it 4. Position the mouse on the lower border of the selected control until the cursor turns into a vertical double arrows:

5. Click and drag down by 2 units. Then release the mouse 6. Click the FirstName text box to select it 7. Press and hold Shift 8. While Shift is still down, click the MiddleName text box followed by the LastName text box and release the Shift 9. Position the mouse on the middle right handle of one of the selected controls:

10. Then click and drag left by one unit of the horizontal ruler. Notice that all three text boxes have been narrowed 11. Click the EmailAddress text box. Press and hold Shift. Then click the DateHired text box, and the FirstName text box. Release Shift 12. On the main menu, click Format -> Size -> To Narrowest. Notice that all of the selected text boxes have been resized to the narrowest of the group, in this case the FirstName text box

Controls Deletion
If you have added a control or it was created by the Form Wizard or the Report Wizard, you can delete it. You can also delete a group of controls in one step. To remove a control from the form or report, first click it and press Delete. If you click a text box or a control that is accompanied by a label and delete it, its label is deleted also. To remove a group of controls, select them and press Delete.

Practical Learning: Deleting Controls


1. On the form, click the EmployeeNumber text box to select it and press Delete. Notice that the text and its accompanying label have been removed 2. Click the MiddleName label and press Delete. Notice that only the label has been removed, leaving the MiddleName text box Here is what we have learned so far:

86

What we have learned in this section about form and report design At this time we have learned how to select: o One control on the form: You click it

o Controls on the same area of the form: You draw a fake rectangle that would touch everyone of them o A few controls on the form: You click one, press and hold Shift, then click each of the desired controls o Select all items that are vertically aligned: you click inside of the horizontal line as if you were dropping a ball that would touch all of them o Select all items that are horizontally aligned: you click inside of the vertical line as if you were throwing a ball that would touch all items on the same line o Select everything on the form: Press Ctrl + A

We also learned how to move: o One control: Drag a pointing finger mouse pointer on the control's upper left corner o A text box with its corresponding label: drag an open hand mouse pointer on it o Many controls: Drag an open hand mouse pointer on one of the selected controls And we learned how to align: o A control relative to another: once both are selected, rightclick one of the selected controls, position the mouse on Align, and make your selection o Many controls relative to another or others. Same thing as above We learned how to resize a control: o after selecting it, position your mouse on one of its borders or corners and drag the double arrow mouse pointer 3. Based on this, design the form as follows:

87

4. After designing the form, to preview it, on the Form Design toolbar, click the View button 5. Press Tab a few times to move the cursor from one text box to another

Tab Ordering
The controls on a form are aligned in the order you desire for their sequence. Unfortunately, when you add a control on the form that already has other controls, regardless of the section or area you place the new control, it is sequentially positioned at the end of the existing controls. If you don't fix it, the data entry personnel could have a hard time figuring out how the sequence should be followed. When writing Visual Basic code, you will also find out that the sequence of navigation of controls on a form is very important. The sequence of controls navigation is set using the Tab Order dialog box. The Tab Order dialog box is available when the form is opened in Design View. Once in Design View, either (1) on the menu bar, click View -> Tab Order; or (2) right-click on the form and click Tab Order. The simplest and quickest way to rearrange the order of items is to click the Auto Order button. Sometimes, you will not like the arrangement made by the Tab Order dialog box. To rearrange items manually, move a row or a group of rows using the same technique we used to move field names on a table's Design View.

Practical Learning: Sequentially Order Controls


1. To switch the form to Design View, on the Form View toolbar, click the View button
2. On the main menu, click View -> Tab Order

3. Position your mouse on the left of LastName, on the row header until the mouse turns into a
right pointing arrow: 4. Click to select the row, and release the mouse 5. Click and hold your mouse on the same row header 6. Drag down by two rows and notice the horizontal line that guides you 7. Then release the mouse 8. Now that you have seen how to reorder the list of controls, arrange it to have the following sequence (this sequence assumes that your form looks like ours in design):

9. Click OK to acknowledge the order 10. To preview the form, right-click its title bar and click Form View 11. On the main menu, click Window -> Size To Fit Form 12. To save the form, press Ctrl + S 13. To close the form, press Ctrl + F4

Opening an "Un-Openable" Form


88

Some of the forms created by the Database Wizard were programmed not to be opened from the Database Window, for good reasons. To explain why, here is an example. Imagine that you create a form to process credit card payments when a customer has chosen to perform such a form of payment. The form used to process this payment should be opened only when the customer has decided to make a payment with a credit card. The user does not need to open such a form from the Database Window. Therefore, you would prevent this form from being accessed in any other way than from the form that is supposed to request its service. In the Rockville Techno database, such forms are the Project (since every project is related to a particular client, the Projects form should be opened from a chosen client), the Payment (unless performing a payment, and we want a particular payment to be related to the appropriate project, the Payment form should not be opened otherwise), and etc forms. To open such a form, you have two alternatives: from its parent form or in Design View. To open such a form in Form View (or in Datasheet View if that is the way the database developer wanted to display it), open its parent form, and click the appropriate button to open the desired form (all these dependent forms have their button on the parent form). To open the form in Design View, you don't have to have its parent form; you can (1) right-click the desired form in Database Window and click Design View, (2) click the form to select it and click the Design button on the Database Window.

Practical Learning: Opening a Form in Design View


1. Make sure any form is closed (this is not necessary but desired) 2. On the Database Window, make sure the Forms button is clicked 3. From the Database Window, double-click Projects. Notice that a small message form requests an entry from you; otherwise it would not open the form. Click Cancel. 4. Right-click Projects and click Design View. Notice that this time, it opens. 5. Close the Projects form by clicking its system Close button 6. On the Database Window, click Payments to select it 7. On the toolbar of the Database Window, click Design. That opens the Payments form in Design View 8. To close it, click its system Close button

Exercises
Yugo National Bank
1. Open the Yugo National Bank database and open the AccountTypes form in Design View. Set its Record Source to AccountTypes and delete the text boxes on the form. Using its Field List, add its fields to the form and design it as follows:

89

Save and close the form 2. Use AutoForm to generate a form for each of the following tables and save the form with the following name Table Name Customers Employees TransactionTypes Form Name Customers Employees TransactionTypes

3. Design the forms as follows and save them:

90

Properties of Database Fields


Overview of Windows Objects
Introduction
In everyday life, an object is an entity that displays or provides some characteristics that set it apart. These characteristics are used to describe the object. For example, an object called Car has such characteristics as its make, model, color, year made, price, and mileage, etc. When put together, these aspects can be used to get good knowledge of what the object looks like and perhaps how it functions. The same concept is used in computer programming, in database development, and in Microsoft Access. Referring to Microsoft Access, an object is a database field or control that owns some characteristics that define or control such aspects as its appearance, its behavior and probably its relationship with other objects of either the same parent or the same database. As objects are different one from another, so are their characteristics. Still, the techniques used to access, read, or change the characteristics of a control or field are shared by all of them, as long as they are being operated upon using Microsoft Access development environment..

Access to Controls Properties


In computer programming or database development, a characteristic of an object is also referred to as its property. On this site, both words will be used interchangeably. When designing a form or report, you can display and review the characteristics of an object using its Properties window. The properties of an object are divided in three main categories: Characteristics that control the object's appearance are listed in the Format property page Characteristics that control internal or external relationships, as far as data is concerned, are listed in the Data property page The Other property page lists characteristics that don't fit in one of the other groups

When dealing with a particular characteristic, you can access it from one of those property pages or you can use the whole list of properties from the All tab

91

Practical Learning: Creating a New Form


1. Start Microsoft Access and open the Rockville Techno database that you started 2. To create a new form, in the Database Window, click Forms and double-click Create Form In Design View. If you are using Microsoft Access 97, in the Forms property page, click the New button. In the New Form dialog box, click Design View, make sure nothing is selected in the combo box and click OK

3. To display the Properties window, double-click the button at the intersection of the rulers

Properties of Database Fields


Properties Categories
Introduction
Properties are set by changing their values and there are various types of properties. A property is made of two parts: its name and its value:

The name of a property displays on the left gray section. Although you can click it to select it, you cannot change it. The property name can be made of one word such as Width. It can also be made of a combination of words, such as Border Style. On this site, a property will be called by what displays on that left gray section. This means that, if a property displays "Height", we will call it "The Height Property". If it displays "Whats This Button", we will call it "The Whats This Button Property". The second part of a property displays on the right side of the property name. This is called the value of the property. As properties are intended to fulfill different purposes, there are various

92

categories of properties.

String Properties
When a property value displays a word or a group of words, such a word or group of words on a field is called a string. Some of those properties already display a value while some others are empty. To set or change such a string, if it is already displaying something, it depends on whether you want to replace the property value or edit it. To replace the value of a string property, you can click the property name. This would highlight the value. You can then type the desired value, which would replace whatever text the property was displaying. If the property value was empty, you can click the property name and type the desired value. If the property already had a value and you want to edit it, you can click in the value field to position the cursor in the string; then you can use your knowledge of text editing (Home, End, Backspace, Space, and arrow keys) to change the text. To put the string into edit mode, you can also click the property name, which would highlight the value, then press F2 to position the cursor into the field. If you press F2 again, you would highlight the contents of the field. This means that F2 toggles edit and selection modes. To edit a string already contained in the field, you can also double-click it, which would put it into edit mode. There are various types of string properties on forms, reports, and other controls. Examples include, among others, the control's name or its caption.

Practical Learning: Viewing String Properties


1. To see examples of string properties, in the Properties window, click the Data tab and click Filter. Notice that it is empty and expects a value 2. Click Order By to see an example of another string property

Boolean-Based Properties
Some fields behave like a True or False answer to a question. Such fields can display only one of two values. Both values come in a combo box that displays as the propertys value. There are three categories of these fields in combinations

of Yes/No, True/False, or On/Off. To change the value of the field, you can first click the property name to reveal its combo box. Then click the arrow of the combo box and select the other value. You can also double-click the property name or its value. This would toggle with the opposite value. With experience, you can also type the first letter of the value, such as y or n and Microsoft Access would complete with the corresponding value.

Practical Learning: Viewing Boolean Properties


1. To see examples of Boolean properties, in the Properties window, click the Format tab 2. Click Record Selectors and notice that it displays an arrow in the property value side. Click that arrow and notice that the list is made of Yes and No 3. In the same way, examine the Navigation Buttons and the Dividing Lines properties

Enumerated Properties
93

A set is a list of words that composes the possible values of a property. The list, which is static, which means it cannot be changed, comes as a combo box where the user (in this case the user is the database developer) can select one item from. To access the value of such a property, you can click the property name to reveal its combo box. To change the property value, click the arrow of the combo box and select the desired value from the list. You can also double-click either the property name or the property value. This would display the next value in the list. You can keep double-clicking until the desired value comes up. If you know the values in the list (from experience), you can type the first letter of the desired value and Microsoft Access would complete it with the corresponding value. If you try typing a value that is not in the list, you would receive an error.

Practical Learning: Viewing Enumerated Properties


1. In the Properties window, click the All tab and click Default View 2. Click its arrow to see its list of values 3. Scroll down and click Border Style. Then click its arrow to view its list

Numeric Properties
Some properties, like the string fields, expect you to provide a value. In this case the value must be numeric. There are two types of numbers you will be asked to provide, depending on the property. An integer is a natural number that does not take a decimal portion. Such a number can be made of digits only. For such a field, make sure you provide an integer of appropriate range, as you will possibly be directed to do. The other type of number will be decimal. A decimal number, also called a floating-point number, can be made of digits or a combination of digits and one period (or the symbol used as the decimal separator in your language; you can find this out in the Regional Settings of the Control Panel) in between. When setting such a value, make sure that either you type only digits, or you type digits and one decimal separator. The decimal separator can be anywhere in the value, Microsoft Access would take care of formatting it if it judges it necessary. To change the value of a numeric property, you can click the property name to highlight the property value. Then you can type the desired value. You can also edit the value by clicking the value itself, which would put it into edit mode. Some numeric properties, such as the color properties, allow you to either type a number (provided you know what number you are typing) or to use an intermediary approach (namely a dialog box) to select an appropriate value.

Practical Learning: Viewing Numeric Properties


1. In the Properties window, click the Format tab 2. Scroll down to examine the Width and the Grid X properties

Expressions Properties
Some properties display a value that is a more elaborate string. If you know what value the property should display, namely an expression, you can just type it. Otherwise, Microsoft Access provides intermediary steps that you can follow to create or build the value. We will see examples of those when we study expressions and queries.

Practical Learning: Viewing Expression Properties


94

1. In the Properties window, click the All tab. Scroll down and click Picture 2. In the right section, click the ellipsis button. Notice that a dialog box is called 3. Click Cancel on the Insert Picture dialog box 4. Close the form. If you are asked whether you want to save it, click No

Properties of Database Fields


Common Characteristics of Database Fields
Name
We have seen so far that, in order to use anything in your database, you must first create it, but the process of creating something depends on its type. For example, tables are created in Datasheet View or designed in Design View. Queries are created by adding fields from existing tables or other queries. Forms and reports are created by adding existing fields or adding independent fields to them. Fields are created and added to these objects. Like every thing else in your computer, every object or field you use in a database must have a name. In fact, when creating an object, the first property that must be set is its name. When you start a brand new table in Datasheet View, Microsoft Access assigns various names to its fields (or columns). These are Field1, Field2, etc. We saw how to change these fields. If you start a brand new table in Design View, you must specify a Field Name for each column that will be used. When you create a simple query, as you select fields from a table or query and add them to the new query, they keep their names and, in this case, the names are held in the originating object (the original table or query). You can still create new fields by combining existing fields from the original table or query. When you create such a new field, you must give it a name. To create a new field in a query, you can select an empty column and, in the field box, assign an expression to it. After doing this, the query would provide a suggested name like Expr1. You can then change the name to something else than Expr1. If you drag an existing field from a Field List to a form or report, the field is added and it keeps it name. You can check this in the Properties window. If you click a control on the Toolbox and click a form or a report, Microsoft Access would assign in a name based on the control. For example, if you add a Text Box control to a form or report, it would named Text0. If you add a second Text Box, it would be named Text2. Whether you drag a field from the Field list or add a control from the Toolbox, after placing it on a form or report, you can change the name it received. In the Table Datasheet View, we saw that, in order to change the name of a field, you can doubleclick it; you can also right-click it and click Rename Column. This puts the field in edit mode and selects it. You can then type the new name and press Enter. In the table Design View, to change the name of a field, you can double-click its name, which would put it in edit mode. Then you can either edit the name or change it completely. In a form or report, you can change the name of a field only while in Design View. To do this, you can access the Properties window of the object. Then, edit or change the string of its Name value.

Practical Learning: Naming Objects


1. The Rockville Techno database should still be opened On the Database window, click the Reports button 2. Double-click the ListOfAssets report to open it in Print Preview

3. After viewing it, to switch it to Design View, on the Print Preview toolbar, click the View button 4. In the Detail section of the report, you should have a text box and its accompanying label. If
you do, click the Unbound text box and press Delete

95

On the Toolbox, click the Text Box control bar

and, on the report, click anywhere under Detail

5. Since the text box was accompanied by a label, click its label and press Delete 6. On the report, click an unoccupied area to make sure nothing is selected. On the report, double-click the newly added text box to select it and display its Properties window

7. In the All tab of the Properties window, click Name, type txtCategory and press Enter
8. In the same way, add a new Text Box in the Detail section. Delete its label and change its Name to txtManufacturer 9. Add another Text Box control in the Detail section. Delete its label and change its Name to txtModelName 10. Add another Text Box control in the Detail section. Delete its label and change its Name to txtDatePurchased 11. Add another Text Box control in the Detail section. Delete its label and change its Name to txtUnitPrice 12. Arrange the fields as follows:

13. Save the report

Record and Control Source


We had previously mentioned that there are fields created from tables and used on the objects, and that these objects also use fields that either existed already or fields that are independent of any other. When adding or creating a field on a form or report, if data for that field originates from a previously created column on a table, the field is said to be bound because its data is bound to an existing field. If a field is either created as an expression that combines other fields or if the field doesn't depend on any existing field, the field is said to be unbound. During the design of a form or report, if you drag a field from the Field List to the object, the new control is bound to the field from the table or query on the Field List. If you click a control on the Toolbox and click a section on the form or report, you can then decide whether the field is bound or not. If it is, you can access its Control Source in the Properties window and from the combo box, select a field from the list. Even if you had dragged a field from the Field List, you can change the control it its bound to by selecting a different one on the Control Source combo box. In future lessons, we will see how to create expressions that use a combination of existing such as creating a full name from the first and last names.

Practical Learning: Setting Control Sources of Objects


1. The Rockville Techno database should still be opened Click the button at the intersection of both rulers on the report. Then, in the Properties window, click Record Source and click its ellipsis button 2. From the list of fields, drag DateAcquired and drop it on PurchasePrice in the lower section

96

of the query 3. Close the query. When asked to save it, click Yes and press Enter

4. On the report, click the first or left Unbound text box to select it. On the Properties

window, click the Control Source field. Then click the arrow of its combo box and select AssetType

5. In the same way, set the Control Source of the second Unbound text box to Make 6. Set the Control Source of the third Unbound text box to Model 7. Set the Control Source of the last two Unbound text boxes to DateAcquired and
PurchasePrice 8. Save the report and close it

Visibility
After adding a field to a form or report, it becomes visible and can be used. An object is referred to as visible if it can visually be located on the screen. A user can use an object only if he can see it. Most of the time, you will not be concerned with this aspect. On the other hand, there are situations that will lead you to create a control but hide it from the user. For example, since you cannot declare a (VBA) variable in Microsoft Access, you can instead create a control such as a text box, make it hold a value that you can use in an expression but hide it from the user who would never need to use such an object.

Availability
In order to use a control on a form or a report, the object that is hosting the control must allow it. For example, the user cannot type text or change the value of a combo box if this action was not made possible. This aspect is controlled in two different ways. If the value of a text box is set by an expression, the user cannot change it. The other technique that controls the availability of an object is from the Enabled property. If you set it to Yes, which is its default value, the user can type a value into it or change it, provided the controls value does not originate from an expression. If you set its Enabled property to No, the user will not be able to change the value of the control.

97

Practical Learning: Disabling a Field


1. The Rockville Techno database should still be opened From the Forms section, double-click CompanyAssets 2. Click the Asset ID text box and type 12. Notice that it does not allow any value from the user. For this reason, we will disable it

3. To switch the form to Design View, on the Form View toolbar, click the View button 4. Double-click the AssetID text box to access its Properties window. In the Properties
window, click the Data tab and double-click Enabled to set it to Yes 5. Notice that its aspect and its label have changed

6. To switch to Form View, on the Design View toolbar, click the View button
7. Click the Asset ID text box and notice that, this time, it cannot even receive focus 8. Save and close the form

Field Locking
During data entry, a user usually clicks a field to give it focus and starts typing. As we will learn, some fields get an automatic number set and controlled by Microsoft Access. Some other fields use data created from an expression. These types of fields do not support data entry and their content cannot be changed directly by the user. In some other circumstances, you will create fields but would not like the user to be able to change their value. For this reason, you can lock such a field. When a field is locked, the user cannot change its content. This characteristic is directly related to data entry and is therefore available on controls positioned on a form only. To lock a control, after selecting it in Design View, access its Locked property in the properties window and set it to Yes. If the control was previous locked, you can unlock it by setting this property to No.

Practical Learning: Locking a Field


1. The Rockville Techno database should still be opened In the Forms section, right-click CompanyAssets and click Design View 2. Click the AssetID text box. In the Properties window, double-click the Locked field to set it to Yes 3. Switch the form to Form View. Then save and close the form

Tool tip
A tool tip is a small yellow border-less box that appears when the mouse is positioned on top of a control for a few seconds. It is a fast means of providing help to the user. Because only the form displays controls in a manner suitable for them, a field can display a tool tip only on a form. To create a tool tip, while in Design View of the form, access the ControlTip Text property of the field and type anything you want in it.

Practical Learning: Setting Tool Tips


1. The Rockville Techno database should still be opened In the forms section of the Database window, double-click the Clients form and, on the Clients form, click the Projects button 2. After viewing the Project form, switch it to Design View 3. Click the Client Name text box (the text box on the right side of the Client Name label). In the Properties window, click ControlTip Text 4. Type Client company of this project and press Enter

98

5. In the same way, click the following controls and change their ControlTip Text property as follows (in the following table, the Control column only refers to text box and the combo box on the form; the name in the Control column is the control on the right side of the label indicated): Control Project Name Project Manager Client PO # Project Description Est. Total Billings Project Begin Date Project End Date Total Hours Total Expense Amount Paid Hours Billing Total Billing Amount Due ControlTip Text Identifier set by the person who created the project Employee in charge of this project Purchase Order Number Text that describes this project Project total billing estimate Date this project must start or started Date this project should end Number of hours worked on this project so far Expenses performed on this project so far Amount the client has paid so far Total amount earned so far Total amount billed to date Total amount due to date

6. Switch the form to Form View and position the mouse for a few sections on Project Manager:

7. Do the same on various controls After viewing the tool tips, save and close the form

Status Bar Text


When a field receives focus, you can display a sentence on the status bar to provide some guidance or suggestion to the user. The text that displays on the status bar should be explicit enough but not too long. When creating it, make sure it can fit in the left section of the status bar, which should be long enough to explain anything. The process of creating a status bar text depends on the control. To create a status bar text for a table, in the Description section for the field, type the string you want. Such a string would appear when the field receives focus in the table or query Datasheet View. If the field participates in an expression for a field of a query, the status bar text would not appear. To create a status bar text for a field on a form, while in Design View, access the Status Bar Text property of the control and type the desired string. Only the controls that can receive

99

focus have a Status Bar Text property. For the same reason, because no field can receive focus on a report, this property is not available for fields on a report.

Practical Learning: Setting Status Bar Text for Fields


1. Open the Bethesda Car Rental1 database you created and click Tables in the Database window 2. Right-click the Employees table and click Design View

3. Click EmployeeID and press Tab twice 4. In the Description field for the EmployeeID field, type
Automatic number set by the database engine

5. Press the down arrow key twice. That puts the cursor in the Description field for the
DateHired field. Type Date the employee was hired

6. For the description of the EmployeeNumber, type Number set by Management 7. In the Description of the FirstName field, type Employees first name 8. In the Description of the MI field, type Middle Initial made of one letter 9. Complete the descriptions of fields

10. Save the table

11. To switch to Datasheet view, on the Table Design toolbar, click the View button
12. Click a cell under the Date Hired column and observe the sentence on the Status bar 13. Click under EmailAddress and observe the Status bar 14. Close the Employees table 15. Open the Rockville Techno database 16. From the Forms section of the Database window, open the CompanyAssets form and switch it to Design View

17. On the form, click the Asset Type text box to select it. In the Other tab of the Properties
window, click Status Bar Text

18. Type Category of asset and press Enter 19. In the same way, on the form, click the following text boxes and change their Status Bar
Text value in the Properties window

Text Box Make Model Serial Number Date Acquired Purchase Price Notes

Status Bar Text The company that manufactures this item The model displayed on the item The serial number set by the manufacture The date this item was purchased The price paid for this item, even if it is being financed A description or a few comments about the item

20. Save the form and switch it to Form View

21. Click different field and observe the message on the status bar 100

22. Close the form

Database Objects Captions


A caption is text that guides the user to identify a window or another object. As it is the most important property of a label, it may appear as a significant guide to the user. For a table, a query, a form, or a report, the caption is text that displays on the title bar. For a label, the caption is text the user can read on the control. After creating an object such as a table, a query, a form, or a report, Microsoft Access uses its name as its caption. The captions of tables and queries cannot be changed (easily). Microsoft uses a combination of the name followed by a colon and space, followed by the category of object. For example, if a table is named Addresses, its title bar would display Addresses: Table

The caption of a query depends on the type of query. If you create the types of queries we have used so far, which consisted of selecting fields, these are called Select Queries. The title bar of such a query would use the same technique as the table but the category of object would be Select Query:

If you create a form using the Form Wizard or if you create a report using the Report Wizard, Microsoft Access would use the name you provided as its caption. If you design a brand new form or report by adding fields to it, it would have a caption as Form1 or Report1 followed by the object category as the Form or the Report. To display its caption, Microsoft Access would

101

use the same convention as seen above:

If you create a report or a form using a wizard, after you have saved the object, its name would be used as its caption:

Controls Captions
So far, we have used two techniques to create fields on a table: using the Datasheet View or using the Design View. In Datasheet View, the name you give to a column also becomes its caption. This is one of the limitations of the Datasheet View. Most programming or development environments, including Microsoft Access, separate the name of a field from its caption. The name is used by you and the operating system to identify an object. The caption is most used to guide the user. To help with this, the Design View of a table allows you to make a distinction on these two aspects of a field. In the Design View of a table, to create a caption for a field, after selecting it in the upper section of the table, in the lower section, click the Caption field and type the desired string. The caption and the name have very little in common, as far as programming is concerned. Although you can provide as caption any string of your choice, you should create it to reflect its corresponding field. For example, you can set the caption of a field named EmployeeNumber as Two Letters Followed by Three Digits as follows:

102

The caption would display as follows:

Although this works, you should set a (short) caption that indicates what the field is used for. For this example, an appropriate caption could be Empl # or Employee # or Empl. Nbr. When you select a new field for a query, Microsoft Access applies the same caption that was used in the table for that field. If the field did not receive an explicit caption (when it was created in the table), then, like the table, the query would use the name of the field as caption. You can change the caption of a querys field to display anything other than the name set in the originating table. To do this, in the box that receives the name of the field, type the desired caption, followed by a colon, followed by the name of the field that will be displayed in the column. Here is an example:

When you run the query, it would display the caption you had set:

103

To set or change the caption of a form, a report, or a label, access its Properties window. Then, click the Caption field and edit or replace it as necessary. If you delete the Caption of a form or a report, Microsoft Access would use the ObjectName: Category formula to create its caption. If you add a new label from the Toolbox to a form or report, the caret would be placed in it so you can create its caption. If you click somewhere else without typing, the label would be cancelled. Therefore, the first action to take when creating a label is to give it a caption, which is done by simply typing the desired string. If the label already exists and you want to edit it, first click it to select it. Then click it again. This would put the label into edit mode. You can then use your knowledge of text editing to change its caption. If you completely delete the caption of a label, the label would be completely deleted.

Practical Learning: Setting Objects Captions


1. Open the Clarksville Ice Cream database you started in Lesson5 and click Tables in the Database window 2. Double-click the Employees table to open it in Datasheet View. Observe the captions on various columns such as DateHired, EmployeeNumber, EmailAddress, etc 3. Switch the table to Design View 4. In the upper section of the table, click EmployeeID

5. In the lower section of the view, click Caption. Type Empl ID and press Enter
6. In the same way, set the captions of fields as follows Field Name DateHired EmployeeNumber FirstName MiddleInitial LastName WorkPhone EmailAddress ZIPCode MaritalStatus Caption Date Hired Empl # First Name MI Last Name Work Phone Email Address ZIP Code Married?

7. To save the table, press Ctrl + S and switch the table to Datasheet View

104

8. Notice that the captions on columns are different (make sure you don't type anything in the fields) 9. Open the Rockville Techno database and, in the Database window, click Tables 10. Double-click the Employees tables to open it and, after viewing it, switch it to Design View 11. In the upper section, click EmployeeNumber

12. In the lower section, click Caption. Type Empl # and press Enter 13. In the same way, set the Caption of MiddleName to Middle Name 14. Change the Caption of Extension to Ext 15. Change the Caption of EmailAddress to Email Address 16. Change the Caption of StateOrProvince to State 17. Change the Caption of PostalCode to ZIP Code
18. Save and close the table 19. On the Database window, click the Forms button 20. Open the Employees form in Design View 21. Click State/Province and click it again to put into edit mode. Double-click Province to select it and press Backspace twice

22. Click PostalCode to select the label. Double-click Postal, type ZIP and press the space bar
23. Click the Billing Rate label and, in the Properties window, click the Format tab

24. Click Caption. Type Salary and press enter


25. Switch the form to Form View to see the result

26. Save and close the form 27. Double-click the EmployeesOfficeContact form to open it to Form View 28. Notice the caption on the title bar and switch it to Design View 29. Click the button at the intersection of both rulers. In the Properties window, click Caption. Type Rockville Technologies, Inc. Employees Contact Information and press Enter 30. Preview the form

105

31. Save and close the form 32. In the Formst section of the Database window, right-click the EmployeesOfficeContact form and click Copy 33. Right-click a white area in the Database window and click Paste

34. In the Paste As dialog box, type EmployeesContact in the Form Name and press Enter
35. In the Database window, click the Reports button 36. Double-click the ListOfAssets report to view it and then switch it to Design View

37. Click the button at the intersection of both rulers

. In the Format tab of the Properties window, click Caption. Type Rockville Technologies Company Assets Inventory and press Enter

38. Preview the report and switch it back to Design View 39. On the Toolbox, click Label and, on the report, click anywhere under the Report Header bar 40. Type Company Assets and press Enter 41. Once again, on the Toolbox, click the Label control and, on the report, click under and to the left of the Page Header bar above the AssetType text box

42. Type Category 43. In the same section and to the right of the previous label, add another label and set its caption to Make 44. Add another label to the right of the previous label and set its caption to Model 45. Add another label to the right of the previous label and set its caption to Date Acquired 46. Add another label to the right of the previous label and set its caption to Price 47. Using the techniques we reviewed for resizing and moving controls, enlarge each label to the same width as its corresponding text box and move it just above its label:

106

48. Save the report

Text Alignment
Most fields or controls of a database display text. This includes labels, text boxes, and combo boxes, etc. To enhance the appearance of the fields or controls, you can specify the alignment of text of a control. This property has three values: left, center, or right. By default, the alignment of text-based fields, including any caption on a label, is set to the left (following US English). The alignment of fields that display numbers or dates is set to the right. If you don't like these suggestions or for any other reason, you can change the text alignment of a field or control. There are various ways you can change text alignment. After selecting it and while in Design View, the Formatting toolbar provides the Align Left , the Center , and the Align Right

buttons. You can click one of these to apply the desired alignment. Alternatively, while in Design View (in Microsoft Access 2000 and later versions, you can change text alignment of fields, excluding the label because it cannot receive focus, even if the form displays in Form View, as long as you display its Properties window first) you can access the Properties window for the field or the label. Then click the arrow of its Align Text combo box property and select one of the available values: Left, Center, or Right.

Practical Learning: Aligning Fields Text


1. The Rockville Techno database should still be opened and displaying the ListOfAssets report On the report, click the Date Acquired label to select it.

2. On the Formatting toolbar, click the Center button


3. To select another control on the report, on Formatting toolbar, click the arrow of the most left combo box and select txtDatePurchased

4. In the Properties window, click the Format tab and click Text Align 5. Click the arrow of the Text Align combo box and select Center 6. On the report, click the Price label and, on the Formatting toolbar, click the Align Right
button 7. Save the report

Font
A font is an art effect made of designed symbols used to represent letters and other characters on a field, a control or a label. A font is designed by an artist but usually follows a specific pattern. For example a font designed to produce symbols readable in the US English language must be designed by a set of predetermined and agreed upon symbols. These symbols are grouped in an entity called the English alphabet. When designing such a font, the symbols created must conform to that language. Because a font is primarily an art, one font can be

107

significantly different from another and a font is not necessarily a series of readable symbols. Just like everything else in the computer, a font must have a name. A font is also designed to assume different sizes. Before using it on a data field or label, the font must have been installed (in reality, when working in Design View (even in any application like Microsoft Word), you can type the name of a font in the Font combo box; if the font doesn't exist, it will simply not be used but you may not receive an error). Microsoft Windows installs many fonts during setup. The font used on the Microsoft Access application to display its menu and the names of objects is controlled by the operating system. That font is called the System Font. Unless you have a good reason, you should not be concerned with it. The names of fonts installed on your computer can be seen in the Fonts window accessible from Control Panel. Here is an example (from a Windows 98 installation):

By default, Microsoft Access uses a font called Arial to display columns and fields on tables, queries, and reports. The default font used on forms is called Tahoma. If you want to use a different font to display text on labels and fields of your database, you can changes these defaults. To set or apply a font on a label or a field, after selecting it in Design View, you can use the Formatting toolbar which is equipped with the Font combo box. You can click its arrow and select a font from the list. Alternatively, to change a font, access the Font Name property of a label or a field in the Properties window, click the arrow of the propertys combo box and select from the list. When changing the default font, in other words, if you decide to change the default font, you should use only the most popular fonts that are more likely to be found on your users computers. To set or apply a font on a group of labels and/or fields, select the group and either use the Formatting toolbar or, from the Properties window, click the Font Name combo box and select from the list. Besides its name, a font is also known for its size. The size defines how much height and proportional width would be used to represent the characters of the selected font. To change or set the size of the font used to display the characters of a label or a field, after clicking it or selecting the group of controls, on the Formatting toolbar, you can click the arrow of the Font Size combo box and select a size from the list. You can also click the label or field, access its Properties window and select a size from the Font Size combo box. In both cases, if you want a size that is not in the list of the Font Size combo box, you can simply type the desired natural number and press Enter or Tab. As done for the font names, you can also select a group of labels and/or fields and apply the same size to them. A font is also characterized by its style. The style controls how the font displays, in normal, bold, italicized, underlined, some of these characteristics or all of them. Here are examples of

108

these characteristics: Style Regular Bold Italic Underline Example Regular Text This text is bold Italicized section The words are underlined

To change or set the font style of a label or a field, after selecting it and while in Design View, on the Formatting toolbar, click the Bold , the Italic , the Underline buttons, only one of them, two of them, or all of them. You can also specify the font style using the Properties window. To do this, first select the label and/or fields. When using the Properties window, the bold style is provided in variations (this also is a setting controlled by the operating system) from the Font Weight combo box as Extra Light, Light, Normal, Medium, Semi Bold, Bold, Extra Bold, and Heavy. The italic style is provided from the Font Italic Boolean field. The underline style is specified using the Font Underline Boolean property. As mentioned for the other font characteristics, you can apply one or more styles on a group of labels and/or fields after selecting the group.

Practical Learning: Setting Fonts Characteristics


1. The Rockville Techno database should still be opened and displaying the ListOfAssets report in Design View In the Report Header section, click the Company Assets label to select it

2. On the Formatting toolbar, click the arrow of the Font combo box and click Garamond 3. With the label still selected, click the arrow of the Font Size combo box and select 24 4. Still on the Formatting toolbar, click the Bold button
5. To enlarge the selected label, double-click one of its 8 handles 6. Select all labels in the Page Header section

7. In the Properties window, click the Format tab and click Font Name 8. Click the arrow of the Font Name combo box and select Times New Roman 9. Still in the Properties window, click Font Size. From its combo box, select 10 10. From the Font Weight property, select Bold 11. In the Detail section, select all text boxes. Using the Properties window, set their Font
Name to Times New Roman and the Font Size to 10 12. Save the report

Fore Color
The color is a non-spatial characteristic applied on a Windows control or a field to define its visual density of darkness or clarity. This density itself is a numeric value created by combining three numbers that each ranges from 0 to 255 included. The first number is also referred to as red. The second is referred to as green. The third is referred to as blue. A combination of red, green, and blue creates a color. Since each number has 256 values, if you multiply them as 256 * 256 * 256, you get 16777216. This means that various combinations of red, green, and blue produce more than 16 million possible colors. There are two main aspects you will deal with as related to colors on a field or a control. The most usual way of setting a color on a field is on its characters or letters. This is also referred to as the fore color, which is simply the color of its font. There are various ways you can change the font color of a field or control. After selecting it and while in Design View, on the Formatting toolbar, you can click the arrow of the Font/Fore Color button. This would display

109

a table of colors:

After clicking a color, it becomes selected on top of the button. The next time, if you need the same color, you can just click the Font/Fore Color button and the already selected color would be applied. If, during design, you will keep changing colors, you can permanently display the Font/Fore Color as a window on your screen. To do this, click the arrow of the Font/Fore Color button and drag its short title bar:

This

would

create

window

based

on

it.

Unlike Microsoft Excel and Microsoft Word, the Font/Fore Color table of Microsoft Access does not display the names of colors. Here are the names of colors we will use on this site as they are laid on the Font/Fore Color table: Indigo BlueDark Red Orange Dark Yellow Green Teal Blue Gray Red Light Orange Lime Sea Green Aqua Light Blue Violet Pink Gold Yellow Bright Green Turquoise Sky Blue Plum Rose Tan Light Yellow Light Green Light Turquoise Pale Blue Lavender Names of Preset Colors Besides the Font/Fore Color button on the Formatting toolbar, to set the font color of a field or label, while in Design View, you can right-click it, position the mouse on Font/Fore Color and click one of the preset colors. Once again, you can use only one of the existing colors. The Font/Fore Color table presents a good and extended list of colors but it does not allow you to customize colors through the Windows Color dialog box. The most extensive way to apply a color consists of creating it from your own combination of red, green, and blue. To do this, while in Design View, access the Properties window for the field or the label and click its Fore Color property. Then click the ellipsis button. This would open the Color dialog box from where you can either select one of the preset colors or create your own. To provide the selection of colors on Microsoft Windows applications, the operating system provides a common dialog box appropriate for such tasks. The Color dialog box is used for various reasons to let you set or change a color of an object. When it displays, by default, the Color dialog box appears as follows: Black Brown Olive Green Dark Green Dark Teal Dark Blue Gray- 80% Gray-50% Gray-40% Gray-25% White

110

This displays a constant list of colors. If none of the available colors is appropriate for the task at hand, you can click the Define Custom Colors >> button to expand the dialog box:

The expanded Color dialog box allows you to either select one of the preset colors or to custom create a color by specifying its red, green, and blue values. You can change the color in four different areas: The top left section displays a list of 48 predefined colors If the desired color is not in that section, you can click and drag the mouse in the multicolored palette You can also drag the right bar that displays a range based on the color of the palette. You can scroll up and down by dragging the arrow For more precision, you can type the Red, Green and Blue values in the corresponding text boxes. Each uses a integral value that ranges from 0 to 255

After selecting or specifying a color, you can click OK or press Enter.

Practical Learning: Setting Text Font on Fields


1. The Rockville Techno database should still be opened and displaying the ListOfAssets report in Design View In the Report Header section, click the Company Assets label to select it

2. On the Formatting toolbar, click the arrow of the Font/Fore Color button and select Red
3. In the Page Header section, select all labels

4. Right-click any of the selected labels, position the mouse on Font/Fore Color and, in the
table of colors, click Indigo (7th column - 1st row) 5. In the Detail section, select all text boxes

6. In the Properties window, click the Format tab and click Fore Color. Then click its ellipsis
button

111

7. In the Color dialog box, click the Blue colors in the 5th column 4th row in the Basic Colors section

8. Click OK 9. Preview the report and switch it back to Design View 10. Save the report

Background Color
You can enhance the appearance of an object by change its background color. This aspect can be applied only to the object that is selected. Based on this, you can paint the background of one section of a form or a report without changing the other sections. In the same way, you can paint the bounding rectangle of a field or a label independent of the other fields or labels. To change the background of an object, first select it. To select a section of a form or a report, you can click the bar above it. After selecting a section, a label or a field, to change its background, on the Formatting toolbar, you can click the arrow of the Fill/Back Color button. You can also right-click the section, the label, the field or a group selected and position the mouse on Fill/Back Color. In both cases, a list of colors similar to that of Font/Fore Color would display. You can then select the desired color from the table. To get a color that is not in the list, access the Back Color property of the section or object and click its ellipsis button. This would display the Color dialog box. You can then use it as we described for the fore color. If you do not want a label or field to be painted with a particular color, you can make it transparent by setting its Fill/Back Color property to Transparent. Using the Properties window, you can also make a control such as a text box transparent by using the Back Style property. Its default value is Normal. To be able to see through the control, you can set this property to Transparent.

Practical Learning: Setting Background Color


1. The Rockville Techno database should still be opened and displaying the ListOfAssets report in Design View On the report, click the Page Header bar to select its section 2. On the Formatting toolbar, click the arrow of the Fill/Back Color button and, from the table of colors, click Pale Blue (6th column - 5th row) 3. Preview the report and switch it back to Design View

4. While the Page Header section is still selected, in the Format tab of the Properties
window, click Back Color and click its ellipsis button 5. In the Color dialog box, click the Define Custom Colors >> button. Set the colors to Red=185, Green=220, Blue=255 and click OK 6. Preview the report and save it 7. Close the report

112

Special Effects
Microsoft Access provides some special visual effects used to raise or sink, etc a section of a form or report, a label or a field. These effects can be controlled by using the Special Effect button on the Formatting toolbar, by right-clicking a label, a field or a group of labels and/or fields, positioning the mouse on Special Effect, and clicking from the list. You can also access the effects from the Special Effect property of the Properties window. The special effects appear as follows:

Practical Learning: Using Special Effects


1. The Rockville Techno database should still be opened In the Database window, click the Forms button and double-click the EmployeesOfficeContact form to open it in Form View 2. After viewing the form, switch it to Design View 3. In the Detail section, select all labels (and only the labels)

4. On the Formatting toolbar, click the arrow of the Special Effect button and click Special
Effect: Sunken

5. Preview the form and switch it back to Design View 6. In the Detail section, select all text boxes

7. In the Format tab of the Properties window, click Special Effect and click the arrow of its
combo box. Select Shadowed 8. As we learned when studying how to resize controls, position the mouse on one lowercenter handle of one of the selected text boxes and drag it down by one unit to resize the text boxes

9. Switch it to Form View and, on the main menu, click Window -> Size To Fit Form 10. Save and close the form

113

Borders
A border is a line that defines the limit of an object. You can control how the border of a label or a field is drawn. The borders of a label or field can be drawn with a variant width of a line. To specify the thickness of line applied on the borders of a label, a field, or a group of objects, click the arrow of the Line/Border Width button on the Formatting toolbar and select the desired width from the list. While the Line\Border Width button on the Formatting toolbar is convenient, it does not provide as many variances as the Properties window. The Border Style is used to control how the borders of a control would be drawn. The possible values are Transparent, Solid, Dashes, Short Dashes, Dots, Sparse Dots, Dash Dot, and Dash Dot Dot. They may appear as follows:

The Border Style characteristic can be used in combination with the Special Effect property. Some of these effects depend on the Special Effect value and may not appear as expected. The Border Color property can be used to control the color used to draw the border of a label or a field. It is used as we described for the Fore Color property. The Border Width property is used as the Line/Border Width button of the Formatting toolbar.

Location
When you add or drag a control to a section of a form or report, it assumes a distance from the left border of the section and from the lower border of the bar of that section. These two dimensions are referred to as its location. The location of an object is determined by its Top and its Left properties:

The location of an object can be set by dragging its top-left handle or its body when the object is selected in Design View, as we learned already. Alternatively, the top and the left values are set as decimal numbers and they follow the measures on the rulers. To change the location of an object, after selecting it in Design View, change the values of either or both its Top and its Left properties.

Practical Learning: Setting the Location of Fields


114

1. The Rockville Techno database should still be opened In the Database window, click the Reports button and double-click ListOfAssets 2. After viewing the report, switch it to Design View 3. In the Report Header section, click the Company Assets label

4. In the Format tab of the Properties window, click Top and type 0.417 5. Click Left, type 0.125 and press Enter
6. In the Page Header section, select all labels

7. In the Properties window, click Top. Type 0.04 and click an area in the Report Header 8. Still in the Page Header section, click Category and, in the Properties window, set its Left
property to 0.0833

9. In the Detail section, select all text boxes and, using the Properties window, set their
common Top property to 0.0417 report as follows: Label Make Model Date Acquired Price AssetType Make Model Text Box Left 1.125 2.1667 3.2451 4.375 0.0833 1.125 2.1667

10. Using the Format tab of the Properties window, set the Left property of the objects on the

DateAcquired 3.2083 PurchasePrice 4.25 11. Save the report 12. Preview the report and return it to Design View

Dimensions
The width of an object is the distance from its left border to its right border. The height of an object is the distance from its top border to its bottom border. The width and the height of an object are referred to as its dimensions. The width of a form or report is the common width of each one of its sections. All sections use the same width. The height of a form or report is the total height of all of its sections. For this reason, the form and the report do not have a height because they let each section control this characteristic. The dimensions of a control positioned on a section of a form or report can be illustrated as follows:

115

The dimensions of an object can be set by dragging one of its middle handles

, or

, when the object is selected, as we learned already. Alternatively, they can be controlled by its Width and its Height properties. Therefore, to change the dimensions of an object, after selecting it in Design View, change the values of either or both its Width and its Height properties.

Practical Learning: Setting Fields Dimensions


1. The Rockville Techno database should still be opened and displaying the ListOfAssets report in Design View

2. Click the Report Header bar. In the Format tab of the Properties window, click Height 3. Type 1 and press Enter 4. In the Report, click the Page Header bar. In the Properties window, click Height, type .
28 and press Enter

5. Click the Detail bar. In the Properties window, click Height, type .25 and press Enter 6. Click the Price label. In the Properties window, click Width. Type .3646 and press Enter 7. Click the PurchasePrice text box. In the Properties window, click Width. Type 0.5833
and press Enter

8. Click the button at the intersection of the rulers of the report


window, click Width. Type 5 and press Enter 9. Save the report and preview it

. In the Properties

10. Close the report 11. In the Database window, click the Forms button and double-click the Employees OfficeContact then switch it to Design View 12. Select all text boxes. In the Properties window, click Height. Type 0.2 and press Enter 13. Preview and save the form

116

14. Close the form

Tab Ordering
When performing data entry, we saw that the user can press Enter or Tab to navigate from one field to another. Because a label cannot receive focus, it is not affected by this navigation. The controls that participate in this navigation are part of a group. Participation to this group is controlled by the Tab Stop Boolean property. In order for a control to receive focus when the user presses Tab, the control must have its Tab Stop property set to true. When you add a Windows control to a form, it is directly made part of that group because its Tab Stop property is set to Yes. If you want to remove a control from this group, you can set its Tab Stop property to No. Of course, an alternative is to set its Enabled property to No. Once a controls Tab Stop property is set to Yes, it must receive a number. Each control that is part of the Tab Stop group must have a unique number. Fortunately, Microsoft Access makes sure that this rule is followed. The number must be a natural number whose minimum must be 0 and whose maximum must be the total number of controls that can receive focus 1. The number is set using the Tab Index property. When you add controls to the form, Microsoft Access checks whether the control can receive focus. If the control can, its Tab Stop property is set to Yes and it receives an incremental number as its Tab Index. You are allowed to change this number following the rules stated above. If you change the number to a number that already exists, Microsoft would renumber the sequence to make sure a number is not repeated. The best way to deal with this aspect is through the Tab Order dialog box as we saw but if you know how you want to control this property, you can set it as you wish.

AutoFormat
Microsoft Access Design Templates
We saw that, when you create a database using the Database Wizard, you have the option of applying one of the designs provided by Microsoft Access and you can apply it to your forms and reports. In the same way, if you create a form using the Form wizard, as we have done in previous lessons, you can select one of the designs and apply it to the form. This concept also applies to reports. If you create a form or report in Design View, you would have only the Standard design. You can still apply one of the designs supplied by Microsoft Access. To do that, open the form or report in Design View. Then, on the main menu, click Format -> AutoFormat... The AutoFormat would appear and allow you to select any of the available designs. After selecting a design, you can click OK

Creating a Form Template


If you design a good looking form or a report and want to use its design in other databases, you can add it to the list of designs of the AutoFormat dialog box. To do that, open the form or report in Design View, then, on the main menu, click Format -> AutoFormat... On the AutoFormat dialog box, click Customize. The Customize AutoFormat dialog box allows you to modify or delete one of the existing designs, or create a new one.

117

Practical Learning: Using AutoFormat


1. The Rockville Techno database should still be opened.
In the Forms section of the Database window, right-click the EmployeesContact form and click Design View 2. On the main menu, click Format -> AutoFormat... 3. In the Form AutoFormats list box, click International and click the Options button

4. Click OK

Exercises
Yugo National Bank
1. Open the Yugo National Bank database.
Open the Customers form in Design View. Change the caption of the form to Yugo National Bank - Account Setup and close it

2. Open the Customers table in Design View, change the Description property of the
following Field Names and their Caption as follows: Field Name CustomerID DateCreated Description Incremental number generated automatically Date the account was created Date Created Caption

AccountNumber Number created by this bank AccountTypeID Type of account, as Checking, Saving, etc CustomerName Address ZIPCode LastUpdate Specifies the last time any information was Name registered on this account. Can be a person Customer Name or a business Where the customer wants to receive statements. PO Box allowed ZIP Code Last Update

118

changed on this account Save and close the table 3. Open the Customers form in Design View and change the captions of the labels as follows:

4. Change the Status Bar text of the following text boxes: Name DateCreated CustomerName Address LastUpdate Status Bar Text Date the account was created Name registered on this account. Can be a person or a business Where the customer wants to receive statements. PO Box allowed Specifies the last time any information was changed on this account

AccountNumber Number created by this bank

5. Save and close the form 6. Open the Employees form in Design View. Change the caption of the form to Yugo National Bank - Employees Records and change the captions of its labels as follows:

Save and close the form 7. On the AccountTypes form, since the user cannot change the value of the AccountTypeID text box, lock it, disable it, chisel it, and make it bold 8. On the Customers form, since the user cannot change the value of the CustomerID text box, lock it, disable it, chisel it, and make it bold 9. On the Employees form, since the user cannot change the value of the EmployeeID text box, lock it, disable it, chisel it, and make it bold 10. On the TransactionTypes form, since the user cannot change the value of the TransactionTypeID text box, lock it, disable it, chisel it, and make it bold

Tenley Associates
1. Open the Tenley Associates database.

119

2. Open the Departments form in Design View and, using the AutoFormat dialog box, apply the Stone design with all options. Since the user cannot change the value of the DepartmentID text box, lock and disable it. Change the font color of the text boxes to Dark Blue. Adjust the design of the form as follows:

3.

Save and close the form

4. Redesign the Employees form as follows:

5. Save and close the form

Watts A Loan
1. Open the Watts A Loan database and open the Customers table in Design View. Change the descriptions and captions of fields as follows: Field Name CustomerID AccountNumber Address ZIPCode 2. Save and close the table 3. Use AutoForm to generate a form for the Customers table. Save the form as Customers and design it as follows: Where the customer wants statements to be sent ZIP Code Description Automatic number generated by the database itself Account # Caption

120

Save and close the form

4. Open the Employees table in Design View. Insert or add the following fields:
Field Name EmployeeID FirstName LastName Title WorkPhone Address City State ZIPCode Country HomePhone Salary Notes ZIP Code Caption No Change No Change No Change No Change No Change

Save and close the table 5. Use AutoForm to generate a form for the Employees table. Save the form as Employees and design it as follows:

121

Save and close the form 6. On the Customers form, since the user cannot change the value of the CustomerID text box, lock it, disable it, chisel it, and make it bold 7. On the Employees form, since the user cannot change the value of the EmployeeID text box, lock it, disable it, chisel it, and make it bold

Database Operators and Operands


Introduction to Operators and Operands
Introduction to Data Types
The fields we have been using allow the user to enter, view, or change data of a database. Because there are so many types of values a user can be asked to deal with, the values in the fields are categorized by types. In the next lesson, we will see how to specify what type of value should or can be entered in a field and what type of value should be prevented. At this time, we will review the categories of data that are considered in a database. A string is any word or group of words considered as an entity. A Boolean value is one that can be expressed in only one of two values. For example, either it is 1 or it is 0, either it is true or it is false, either it is yes or it is no. An integer is a natural number that displays without a decimal place. Examples of integers are 18, 16763, and 1450. A byte is a small number that ranges from 0 to 255. A double, also called double precision, value is a number that can display a decimal portion, using the character set as the decimal separator in Control Panel. For US English, that character would be the period. The expression double-precision means that this number provides a high level of precision. Valid decimal numbers are 12.55, 3.14159 or 9.80336 A date is a value that counts the number of days that have elapsed from a certain point of reference. How a date displays in a field is based on some conventions set by Microsoft Access, Microsoft Windows, or you. There are also rules you must respect. Examples of dates are 28/06/1998, 10-8-82, January 10, 1865 A time is a value that counts the number of seconds that have elapsed since midnight of a certain day. The time also displays following some conventions set in Control Panel, by Microsoft Access, or the person who created the database. Examples of time values are 10:42 AM and 18:06 A currency is a numeric type used to represent money value in a field.

Overview of Operators and Operands


The data fields we have used so far were created in tables and then made available to other objects, queries, forms, and reports, so those objects can implement their own functionality without worrying about displaying empty or insignificant fields. In various scenarios, you will need to display a field that is a combination of other fields. For example, you may need to combine a FirstName to a LastName fields in order to create a FullName field, or, to calculate an employees weekly salary, you may need to retrieve the value of a Salary field and multiply it with the value of a total number of hours worked in a week. Most, if not all, of these expressions use what we call operators and operand. An operation is a technique of using a value or a field, or to combine two or more values or data fields to either modify an existing value or to produce a new value. Based on this, to perform an

122

operation, you need at least one value or field and one symbol. A value or field involved in an operation is called an operand. A symbol involved in an operation is called an operator. A unary operator is one that uses only one operand. An operator is referred to as binary if it operates on two operands.

The Assignment Operator =


In order to provide a value to an existing field, you can use an operator called assignment. Its syntax is: VariableName = ValueOrVariable The operand on the left side of the = operator is referred to as the left value or Lvalue. This operand must always be able to be written to. In other words, it cannot be a type of constant we will review next. The operand on the right side of the operator is referred to as the right value or Rvalue. It can be a data field or a constant. There are two main ways we will use the assignment operator. Imagine you already have a field and you want to display the value of that field in another field. In the Control Source of the new field, you can write an expression that assigns the existing field. Here is an example that assigns the value of an existing FirstName field to a new field using the Control Source property:

In some other cases, the assignment operator will be part of a longer expression. We will see examples we move on.

The Positive Unary Operator +


Algebra uses a type of ruler to classify numbers. This fictitious ruler has a middle position of zero. The numbers on the left side of the 0 are considered negative while the numbers on the right side of the 0 constant are considered positive: - - -6 -6 -5 -5 -4 -4 -3 -3 -2 -2 -1 0 -1 1 2 3 4 5 6 + 1 2 3 4 5 6 +

A value on the right side of 0 is considered positive. To express that a number is positive, you can write a + sign to its left. Examples are +4, +228, +90335. In this case the + symbol is called a unary operator because it acts on only one operand. The positive unary operator, when

123

used, must be positioned to the left side of its operand. As a mathematical convention, when a value is positive, you do not need to express it with the + operator. Just writing the number without any symbol signifies that the number is positive. Therefore, the numbers +4, +228, and +90335 can be, and are better, expressed as 4, 228, or 90335. Because the value does not display a sign, it is referred as unsigned.

The Negative Unary Operator As you can see on the above ruler, in order to express any number on the left side of 0, it must be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A value accompanied by - is referred to as negative. The - sign must be typed on the left side of the number it is used to negate. Remember that if a number does not have a sign, it is considered positive. Therefore, whenever a number is negative, it MUST have a - sign. In the same way, if you want to change a value from positive to negative, you can just add a - sign to its left. In the same way, if you want to negate the value of a field and assign it to another field, you can type the operator on its left when assigning it.

Constants
Introduction
A constant is a value that does not change. The constants you will be using in your databases have already been created and are built-in Microsoft Access. Normally, Visual Basic for Applications (VBA), the version of Microsoft Visual Basic that ships with Microsoft Access also provides many constants. Just in case you are aware of them, you will not be able to use those constants, as Microsoft Access does not inherently understand them. For this reason, we will mention here only the constants you can use when building regular expressions. The algebraic numbers you have been using all the time are constants because they never change. Examples of constant numbers are 12, 0, 1505, or 88146. Therefore, any number you can think of is a constant. Every letter of the alphabet is a constant and is always the same. Examples of constant letters are d, n, c. Some characters on your keyboard represent symbols that are neither letters nor digits. These are constants too. Examples are &, |, @, or !

True or False
In Boolean algebra, something is considered True when it holds a value. The value is also considered as 1 or Yes. By contrast, if something does not hold a value, it is considered nonexistent and not worthy of consideration. Such a thing has a value of False, 0, or No. In reality, everything in your database has a value, as far as the database engine is concerned. To retrieve such a value, you can just find out if the value of a field is existent or not. The comparison for a True or False value is mostly performed on Boolean fields, such a case is the Single Parent field of the student registration objects (table, form, possibly query, and report) of the ROSH database. If a record has a check mark, the table considers that such a field is True. If the check box is not checked, then it holds a False value.

NULL
While the True and False constants are used to find out whether a check box is marked or not, the database provides another constant used to find out whether a field is empty. This can be done using the Null constant. When a field holds a value, the value would be considered using the comparison operators we will learn shortly. If a field doesn't hold a value, it is considered NULL. It is very important to understand this: the fact that a field is empty doesn't mean that it is NULL.

Microsoft Access Operators


124

The Square Brackets Operator: []


When reviewing name rules for our objects in Microsoft Access, we saw that we should use names that are made of one word (no space). In reality, Microsoft Access, as mentioned already, is particularly flexible with names. It uses a mechanism to delimit a name when such a name is involved in an operation. The operator used to specify the beginning of a name is the left or opening square bracket [. At the end of a name, a right or closing bracket is used. To be safe, whether a name is made of one or more words, Microsoft Access prefers including it in square brackets. In an operation, also called an expression, instead of using such a name as FirstName, you should use [FirstName]. Of course, if a name is made of more than one word, which is frequent on database objects created using the Database Wizard, you must always include it in square brackets. An example would be [Video Titles Subform]. The field we used earlier to assign a FirstName value to another can be written as follows:

The Collection Operator: !


The objects used in Microsoft Access are grouped in categories called collections. For example, the forms belong to a collection of objects called Forms. The reports belong to a collection of objects called Reports. The data fields belong to a collection called Controls. Based on this, all forms of your database project belong to the Forms collection, all of your reports belong to the Reports collection, and all controls you are using belong to the Controls collection. To call a particular object in an operation, using the exclamation point operator, type the name of the collection followed by the ! operator, followed by the name of the object you need to use. For example, if you have a text box called FirstName and you want to refer to it, you can type Controls!FirstName. Here is the same example as earlier that assigns a FirstName field to a text box using its Control Source property:

The name of the collection is used to perform what is referred to as qualification: the name of the collection qualifies the object. In other words, it helps the database engine locate the object by referring to its collection. This is useful in case two objects of different categories are being referred to. Since you cannot have two fields with the same name on the same form or report, it is safe to omit the Controls name of the collection when referring to a field. Whether you use the Database Wizard or you create your own objects, Microsoft Access allows two objects to have the same name, as long as they do not belong to the same category. For

125

example, you cannot have two forms called Employees in the same database. In the same way, you cannot have two reports named Contracts in the same database. On the other hand, you can have a form named Employees and a report named Employees in the same database. For this reason, when creating expressions, you should (with emphasis) qualify the object you are referring to, using its collection. Therefore, when an object named Employees is referred to in an expression, you should specify its collection, using the ! operator. An example would be Forms!Employees which means the Employees form of the Forms collection. If the name of the form is made of more than one word, or for convenience (strongly suggested), you must use square brackets to delimit the name of the form. Therefore, the form would be access with Forms![Employees]. To refer to a control placed on a form or report, you can add the name of the control at the end of the expression. Because the control belongs to its collection, it can be accessed with the ! operator:

The Period Operator: .


In previous lessons, we learned that a property is something that characterizes or describes an object. For example, users mainly use a text box either to read the text it contains, or to change its content, by changing the existing text or by entering new text. Therefore, the text the user types in a text box is a property of the text box. To access the property of an object, type the name of the object, followed by a period, followed by the name of the property you need. The syntax used is: Object.PropertyName The property you are trying to use must be a valid property of the object. In Microsoft Access, to use a property of an object, you must know, either based on experience or with certainty, that the property exists. Even so, unfortunately, not all properties are available.

Double Quotes ""


A string is an empty space, a character, or a group of characters that you type or provide to a control and you want this character or this group of characters to be considered "as is". In other words, the expression or the control that receives the string should keep it or them the way you supplied it or them, unless you specify otherwise. A string can be an empty space or one character, such as $ or w; a group of characters, like home or Manchester United or Verbally speaking, I mean Ah forget it. Most of the time, you will want the database to keep this character or group of characters exactly the way you or the user supplied them. In order to let the program know that this is a string, you must enclose it in double quotes. From our examples, our strings would be "$", "w", "home", "Manchester United", and "Verbally speaking, I mean Ah forget it". To assign a string to a field, in the Control Source of the field, you can type the assignment operator followed by the doublequoted string. Here is an example:

126

The String Concatenator: &


The & operator is used to add one string to another. It can also be used to append the contents of two controls, or expressions. This is considered as concatenating them. For example, it could allow you to concatenate a first name and a last name, producing a full name. The general syntax of the concatenation operator is: Value1 & Value2 To display a concatenated expression in an unbound field, use the assignment operator on the field. Here is an example:

Here is an example of the form in Form View:

Once again, you should include the name of a field in square brackets. To concatenate more than two strings, you can use as many & operators between any two expressions as necessary. After concatenating the strings or values, you can assign the result to another value or expression using the assignment operator. The syntax used is: =Field1 & Field2 & Field_n Here are examples =FirstName & " " & LastName This would display, for example, Boniface Dunkirk =[LastName] & ", " & [FirstName] This would produce, for example, Chang, Helene =[Address] & " " & [City] & " " & [State] & " " & [ZIPCode] & " " & [Country] This would display a complete address in a field

The Parentheses Operators: ()


Parentheses are used in two main circumstances: in procedures or in operations. The parentheses in an operation help to create sections in an operation. This regularly occurs when more than one operators are used in an operation. Consider the following operation: 8 + 3 * 5 The result of this operation depends on whether you want to add 8 to 3 then multiply the result

127

by 5 or you want to multiply 3 by 5 and then add the result to 8. Parentheses allow you to specify which operation should be performed first in a multi-operator operation. In our example, if you want to add 8 to 3 first and use the result to multiply it by 5, you would write (8 + 3) * 5. This would produce 55. On the other hand, if you want to multiply 3 by 5 first then add the result to 8, you would write 8 + (3 * 5). This would produce 23. As you can see, results are different when parentheses are used on an operation that involves various operators. This concept is based on a theory called operator precedence. This theory manages which operation would execute before which one; but parentheses allow you to control the sequence of these operations.

Arithmetic Operators
The Addition: +
The addition is used to add one value or expression to another. It is performed using the + symbol and its syntax is: Value1 + Value2 The addition allows you to add two numbers such as 12 + 548 or 5004.25 + 7.63 After performing the addition, you get a result. You can provide such a result to another field of a form or report. This can be done using the assignment operator. The syntax used would be: = Value1 + Value2

The Subtraction: Subtraction is performed by retrieving one value from another value. This is done using the symbol. The syntax used is: Value1 - Value2 The value of Value1 is subtracted from the value of Value2. After the operation is performed, a new value results. This result can be used any way you want. For example, you can display it in a control using the assignment operator as follows: = Value1 - Value2

The Multiplication: *
Multiplication allows adding one value to itself a certain number of times, set by the second value. The multiplication is performed with the * sign which is typed with Shift + 8. Here is an example: Value1 * Value2 During the operation, Value1 is repeatedly added to itself, Value2 times. The result can be assigned to the Control Source of a field as. The expression would be written as follows: = Value1 * Value2

The Integer Division: \


Dividing an item means cutting it in pieces or fractions of a set value. For example, when you cut an apple in the middle, you are dividing it in 2 pieces. If you cut each one of the resulting pieces, you will get 4 pieces or fractions. This is considered that you have divided the apple in 4 divisions. Therefore, the division is used to get the fraction of one number in terms of another. Microsoft Access provides two types of results for the division operation. If you want the result of the operation to be a natural number, called an integer, use the backlash operator "\" as the operator. Here is an example: Value1 \ Value2

128

This operation can be performed on two types of valid numbers, with or without decimal parts. After the operation, the result would be a natural number. The result of the operation can be assigned to a field using the assignment operator: = Value1 \ Value2

The Division: /
The second type of division results in a decimal number. It is performed with the forward slash "/". Its syntax is: Value1 / Value2 After the operation is performed, the result is a decimal number. The result of the operation can be assigned to a field using the assignment operator: = Value1 / Value2

The Exponentiation: ^
Exponentiation is the ability to raise a number to the power of another number. This operation is performed using the ^ operator (Shift + 6). It uses the following mathematical formula: yx In Microsoft Access, this formula is written as y^x and means the same thing. Either or both y and x can be values or expressions, but they must carry valid values that can be evaluated. When the operation is performed, the value of y is raised to the power of x. You can display the result of such an operation in a field using the assignment operator as follows: =y^x

The Remainder Operator: Mod


The division operation gives a result of a number with or without decimal values, which is fine in some circumstances. Sometimes you will want to get the value remaining after a division renders a natural result. The remainder operation is performed with keyword Mod. Its syntax is: Value1 Mod Value2 The result of the operation can be used as you see fit or you can display it in a control using the assignment operator as follows: = Value1 Mod Value2

Database Operators and Operands


Logical Operators
Introduction
Databases and other programming environments provide operators you can use to perform data analysis. The operators used are called logical operators because they are used to perform comparisons that produce a result of true or false (there is no middle result: something is not half true or half false or "Don't Know"; either it is true or it is false).

The Equality =
The equality operator is used to compare two values for similarity. The syntax of this operation is: Value1 = Value2 If Value1 and Value2 hold the same value, then the comparison produces a True result. If they hold

129

different values, the comparison renders a False value

Inequality <>
To find out if two fields hold different values, you can use the inequality operator which is represented by <>. Its syntax is: Value1 <> Value2 This comparison is performed between Value1 and Value2. If they hold different values, then the comparison produces a True value (make sure you understand this property of Boolean algebra). If they hold the same value, the comparison produces False:

This shows you that the equality (=) and the inequality (<>) operators are opposite each other.

Less Than <


The "Less Than" operator uses the following syntax: Value1 < Value2 If Value1 holds a value that is lower than that of Value2, the comparison produces True. If Value1 holds a value that is greater or similar to that of Value2, the comparison renders false:

130

Less Than Or Equal <=


When comparing two values, you may want to know whether two fields hold the same value or if one is lower than the other. This comparison can be performed with the "Less Than Or Equal To" operator. It is represented by <=. Its syntax is: Value1 <= Value2 If both operands (Value1 and Value2) hold the same value, then the comparison produces a True result. If Value1 holds a value that is lower than that of Value2, the comparison still produces a True result. By contrast, if the value of Value1 is higher than that of Value2, the comparison renders a False result:

Note that the > and the <= operators are opposite each other.

Logical Operators: Greater Than >


The > operator is used to find out whether one value is "Greater Than" another. Its syntax is: Value1 > Value2 The operation is performed on the values of Value1 and Value2. If Value1 holds a value greater than that of Value2, then the comparison produces True. Otherwise, the comparison produces False. That is, if the value of Value2 is greater than or equal to that of Value1, then the comparison produces False:

131

Greater Then Or Equal >=


If you have two values and want to find out whether they hold similar values or the first is greater than the second, you can use the >= operator whose syntax is: Value1 >= Value2 If both Value1 and Value2 hold the same value, then the comparison renders a True result. Similarly, if the left operand, Value1, holds a value greater than that of the right operand, Value2, the comparison still produces True. If the value of Value1 is less than the value of Value2, the comparison produces a False result:

Therefore, < and >= are opposite.

The NOT Operator


To deny the presence, the availability, or the existence of a value, you can use the Not operator. This operator is primarily used to reverse a Boolean value. For example, we have learned that False is the opposite of True. In the same way, True is the opposite of False. If you want to compare a value as not being True, the Not True expression would produce the same result as the False value. For the same reason, the expression Not False is the same as True.

The IS Operator
To validate something as being possible, you can use the IS operator. For example, to acknowledge that something is NULL, you can use the IS NULL expression. In the same way, to validate that something is not null, you can use the expression Is Not NULL.

The IN Operator
The IN operator is used to check whether a record or a group of records is found in a group.

132

Introduction to Data Types


Overview of Data Types
Introduction
A data type represents the kind of information that a particular field should or must hold. Every field in your database objects (tables, forms, and reports) should have the right type and it is your role to select the most appropriate of them. This helps both you and the user who performs data entry. Furthermore, a good design will cause you less headache when creating calculated expressions. Imagine trying to multiply a FirstName by a DateHired. As much as you can, you should make sure that the right kind of data is typed in the right field. Microsoft Access helps you allow or exclude categories of data in database fields. Using this, you can make sure that the user would not type a contract's date in a project's contact name. To manage different forms of information you enter in a database, Microsoft Access helps you organize data by categories.

Techniques of Controlling Data Entry Properties


To make your database efficient, in some circumstances, or depending on the project (or customer), you should exercise as much control as possible on data entry. Without considering that data entry people are not intelligent enough, it is your job to help or guide them by allowing the right type of information in a field. This control is mostly exercised at two levels: tables and forms. To control data entry at the table level, a database environment like Microsoft Access provides data types. To specify a data type for a field on a table, you must open the table in Design View and select a data type under the Data Type column for the corresponding column. Because the list of data types may appear short to you, each data type provides some options that allow you to configure how data in that column either would be selectively entered or would display. To do this, after selecting a data type in the Data Type combo box, in the lower section of the table, you can format or further configure the column. After a field has been configured on a table, when that field is used in a form, it would respect the formatting that was done on the table. Even if you create an unbound field on a form, you can still control how it accepts or rejects data. Therefore, data entry can also be configured at the form level. To provide this functionality, a form provides the same properties as the lower portion of the table. To further control how data is entered and/or how it is displayed in a field, both the table in Design View and the Properties window in Form Design provide special characteristics. The lower part of the table Design View is made of two sections: the property pages on the lower left and the properties help section on the lower right:

133

The kind of Data Type you set for a column in the upper section controls what displays in the lower section of the view. The General property page controls regular features common to the selected data type: Field Size: The Field Size property is available for a data type and since data types are specified only on a table, it is available only on a table. The Field Size depends on the type of data selected but it is available only for text and numbers. Format: The Format property is used to specify how the value(s) for a column should display The Lookup tab allows you to specify a feature that is particular with a specific data type of the upper section of the field. Once you have selected a data type for a certain field in the upper section of the view, that data type will provide its own sub-categories. To display the sub-categories of a data type, select that data type in the upper section of the view.

Strings and Data Types


Introduction
We have defined a string as an empty text, a letter, a word or a group of words considered as is. This type of data is created on a table by selecting the Text data type. A Text data type allows the user to type any kind of characters or group of characters. This field can hold up to 255 characters.

Practical Learning: Setting Appropriate Data Types


1. From the resources that accompany this book, copy the Rockville Techno1 database to
your Exercises folder and then open the Rockville Techno1 database

2. In the Database window, click the Tables button if necessary 3. Notice that the default Data Type of most fields is Text

From the Tables section, open the Employees table and switch it to Design View

Field Size
The size of a string is usually considered as the number of characters it contains or may hold. When creating a field that would hold text, the default size provided is 50 characters, as the number 50 is set in the Field Size property. You can therefore decrease or increase this size for any number between 1 and 255. The default value, 50, is enough in most cases, such as providing a (short) description for a product. When setting the Field Size property by itself, the database would make sure that the user can only type so many characters. For example, it is very unlikely to have a first name of a person that is 50 characters. In this case, you can safely reduce the number of characters to 20 or 30. On the other hand, if you are creating a column whose length is hard to predict, you can set the length to a reasonable value. There are other ways you can decrease the number of characters that are allowed in a field. Over all, you should be able to predict the types of values that would be entered in the fields of a column.

Practical Learning: Setting Field Sizes


1. In the upper section of the view, click FirstName 2. In the lower section of the view, click Field Size and type 20
This will allow the user to type only 20 characters section of the view

3. In the upper section of the view, click MI and press F6 to move the caret to the lower 134

4. As the caret is on the Field Size field, type 1 5. Set the Field Size of LastName to 20 6. Set the Field Size of Address to 100
7. Save the table

Text Input Masks


Because users can be tempted or distracted to enter just anything in a Text field, Microsoft Access provides techniques to control what goes in a field and what must be prevented. This is the role of a mask. A mask is a technique of creating sections, also called placeholders, in a field. A section can be configured to accept only a letter, only a digit, a character or a digit, any symbol, nothing, or to display a particular symbol that the user cannot change. When creating the mask, you will use some predefined characters and create a combination of your choice. Before creating a mask for a field, Microsoft Access comes with various masks you can apply to a field to control user's input such as dates, times, US Social Security Number, Currency values, etc. To apply one of these masks, you can use the Input Mask Wizard. To do this, first set the Data Type of the desired field to Text. Then, in the lower section of the table, click the Input Mask property and click its ellipsis button . This would start the wizard. In the first page of the Input Mask Wizard, you can choose one of the popular provided formulas including US and Canada telephone number, Social Security Number, ZIP Code, etc:

If none of the masks suits your need, you can create a new one and add it to the list. To do this, click the Edit List button. This would bring the Customize Input Mask Wizard dialog box:

After creating a new mask, click Close. Once you have located the desired mask, you can click it and click Next to continue. The second page of the wizard allows you to accept or customize the mask you had selected. Once you are ready, you can click Next. The third page presents an option that allows you to specify how the value in the field will be stored in the database. It presents two radio buttons and you can either accept the suggestion or select the other and click Next. The fourth page of the wizard does not do much. It simply lets you know that the wizard is ready to create the mask. Therefore, you can click Finish.

135

If none of the masks provided by the wizard suits you, you can create your own. To do that, click the Input Mask property for the desired field and use the following characters to create the mask: Character Used to enter or accept 0 9 # L ? A a & C . , :;-/ < > ! | A single digit A single digit or space A digit, space, + or An alphabetical character A letter A letter or a digit A letter, a digit, or nothing A character or space A character, space, or nothing A decimal place holder; for US English, this would be the period Thousand separator; for US English, this would be a comma Date and time separator, as specified in the Regional Settings of Control Panel A letter; the letter will be converted to lowercase A letter; the letter will be converted to uppercase Anything; the mask is filled from right to left for this position Anything; the character that follows this one will be displayed itself. For example, if you type |L, the letter L would be displayed instead of being used a mask

You can use any of these symbols to create a mask. If you want to include a word or sentence as part of the mask, type it in any section as desired. Here are examples of Custom Masks: Mask LL >LL\-00 #0L >LL\-000 000\-000\-0000 ##\-## &#\-L0\-## \(000") "000\-0000 !\(999") "000\-0000"" 00\-00\-00\-00 >00\-LLLL\-0 >L<LLL >L<????????????? Example 1 dh WE-47 8f WE-883 265-387-6498 02-37 5-u5-00 (301) 294-6464 ( ) 392-3873 28-73-68-46 78-DRUG-9 Jean Helene Antananarivo -9-5+ -6-35 16a 04t Example 2 fT Example 3 Gm

Practical Learning: Using Input Masks


1. The Clarksville Ice Cream database should still be opened and displaying the Employees
table in Design View In the upper section of the table, click EmployeeNumber

2. In the lower section, click Input Mask, type >LL-000 and press Enter 136

3. In the upper section, click ZIPCode and press F6. In the lower section, change the Input
Mask to 00000 4. Open the Clarksville Ice Cream database that you started in Chapter 4 and open its Employees table in Design View

5. In the upper section of the table, click WorkPhone and, in the lower section, click Input
Mask

6. On the right side of the Input Mask field, click the ellipsis button

7. In the first page of the of the Input Mask Wizard, click Phone Number (in Microsoft Access 2000, it should be selected by default) and click Next

8. In the second page, press Tab twice to position the caret in the Try It edit box. Type
0000000000 to test it

9. Click Next 10. In the third page, click the With The Symbols In The Mask radio button

11. Click Next and click Finish. Notice the new mask in the field 12. Save the table

Strings Formats
137

After a user has entered data in a field, without or without the influence of a mask, you can specify how the value of the field should be displayed. This is controlled by the Format property. To assist you with this configuration, the Format property depends on the type of data set for the field. After creating a mask, if you want to prevent duplicate data, remember to specify this in the Indexed property.

Practical Learning: Setting Fields Format


1. From the resources that accompany this ebook, copy the Bethesda Car Rental1
database and paste it into your Exercises folder. Then open the Bethesda Car Rental1 database 2. Open the Employees table in Design View

3. In the upper section of the view, click EmailAddress 4. In the lower section of the view, click Format. Type < to make sure the content of the
Email Address field will be converted to lowercase

5. In the upper section, click MI 6. In the lower section, click Format, type > 7. Click Input Mask, type L and press Enter 8. Open the Rockville Techno1 database and, from the Tables section, open the
Employees table in Design View

9. In the upper section of the table, click State 10. In the lower section, click Input Mask, and type >LL and press Enter 11. In the upper section of the table, click EmployeeNumber 12. In the lower section, click Input Mask. Type >LL\-000;0;_ and press Enter

The Memo Data Type


The Memo data type functions like the Text except that it can hold a longer text up to 64000 characters. The text is mostly provided as ASCII. This means that there is no formatting.

Practical Learning: Setting Memo Types


1. Open the Rockville Techno database and, from the Tables section of the Database
window, open the Employees table in Design View

2. Under the Field Name column, click Observations. Press Tab, type m and press Enter.
Notice that the data type has been set to Memo 3. Save the table

Exercises
Yugo National Bank
1. Open the Yugo National Bank database. Open the AccountTypes table in Design View and change the Data Type of the Description field to Memo. Save and close the table

2. Open the AccountTypes form in Design View. Delete the Description text box (and its
accompanying label). Using the Field List, add the Description field to the form where the other Description text box was

138

Save and close the form 3. In the Customers table, reduce the possible length of characters of the Address field to 50 characters then save and close the table 4. Reduce the possible number of characters of the Address column of the Employees table to 50 characters then save and close the table

Tenley Associates
1. Open the Tenley Associates database. Configure the EmployeeNumber field of the Employees table so that examples of possible numbers would be 648-DL-TG or 762-7DGG or 376-88-BP. That is, an employee number is made of three sections separated by a dash symbol. The first section is made of 3 digits and only digits. The first character of the second section can be a letter or a digit. The second character of the section section can and must only be a letter. The third section must be made of 3 letters 2. Change the ZIPCode of the Employees table to allow only 5 letters

Watts A Loan
1. Open the Watts A Loan database. In the Customers table, reduce the Address field to allow only 50 characters then save and close the table

2. Open the Employees form and create a few employees records 3. Open the Customers form and create a few accounts

Using Data Types


Numbers
Introduction
A number is a digit (0, 1, 2, 3, 4, 5, 6, 7, 8, or 9), a combination of digits, or a combination of one or more digits, a separator, and one or more digits. Microsoft Access provides three techniques or categories of numbers. These should be applied appropriately to make your database as effective as possible. To specify that a column will contain only numeric values, after displaying the table in Design View and selecting the column under Field Name, set its Data Type to Number, Currency, or AutoNumber. When reviewing strings, we saw that the Field Size property of a Text data type was used to specify the number of characters of the string. Numeric data types also use the Field Size property but it is used to control the type or range of numeric values that would be accepted or excluded from the field. While the Data Type column allows you to select the category of number, the Field Size property actually specifies the (Microsoft Visual Basic) data type that will (programmatically) be applied to the field.

139

Natural Numbers
A natural number is one that contains one digit or a combination of digits. Examples of natural numbers are 122, 8, and 2864347. When a natural number is too long, such 3253754343, to make it easier to read, the thousands are separated by a special character. This character depends on the language or group of languages and it is called the thousands separator. For US English, this character is the comma. The thousands separator symbol is mainly used only to make the number easier to read. To support different scenarios, Microsoft Access provides different types of natural numbers: Byte: A byte is a small natural number that is between 0(included) and 255(included). This type of number can be applied to such items as persons ages, number of students in an elementary classroom, number of rooms in a regular house, number of pages of a magazine or newspaper, etc. If you are creating a column that will need this range of values, after setting its Data Type to Number set its Field Size to Byte. Integer: An integer is a natural number larger than the Byte. It can hold a value between -32,768 and 32,767. Examples of such ranges are the number of pages of a book. For a column that would hold this range of values, set its Field Size to Integer. Long Integer: A long integer is a natural number whose value is between 2,147,483,648 and 2,147,483,642. Examples are the population of a city, the distance between places of different countries, the number of words of a book. For such a field, set its Data Type to Number and its Field Size to Long Integer. In our examples, we were giving types of columns for each kind. It is important to note that, since a long integer can hold larger numbers than the integer, anything applied as an integer can also be used as a long integer. For example, you can use a long integer to represent the number of pages of a book, even if the books in a collection are not expected to hold more than 1500 pages. In the same way, since an integer is larger than a byte, anything that fits in a byte can also be used as an integer. Based on this, an integer can be used to represent the categories items in a collection, even if the items are not expected to be higher than 200. For example, you can use an integer to count the number of keys on a computer keyboard, knowing that this number is expected to stay below 148.

Practical Learning: Using Natural Numbers


1. Open the Clarksville Ice Cream database and, from the Tables section, click the New
button 2. In the New Table dialog box, click Design View and click OK

3. Set the first Field Name to ScoopsID and make it a press the down arrow key 4. Set the second Field Name to Scoops and press Tab 5. Set its Data Type to Number and press F6 6. In the Field Size combo box, select Byte

Automatic Numbers
If you create a column that will be used to keep an index of records as they are entered and/or deleted, you can set its Data Type to AutoNumber. This would ask Microsoft Access to complete that field with automatically generated numbers for a column whose numbers you don't need to control. This technique is highly used for the first field of a table.

Practical Learning: Using an Automatic Number


140

1. The Clarksville Ice Cream database should still be opened with the Table1 in Design View In the upper section of the table, click ScoopsID and press Tab 2. Change the ScoopsID Data Type to AutoNumber 3. Close the table to save it. Give it the name Scoops and press Enter 4. When asked whether you want to create a Primary Key, click No 5. Open the Employees table in Design View

6. In the upper section of the table, click EmployeeID and press Tab 7. Click the arrow under the Data Type and click AutoNumber
8. Save the table

Real Numbers
A real number is a number that displays a decimal part. This means that the number can be made of two sections separated by a symbol that is referred to as the Decimal Separator or Decimal Symbol. This symbol is different by language, country, group of languages, or group of countries. In US English, this symbol is the period as can be verified from the Regional (and Language) Settings of the Control Panel:

On both sides of the Decimal Symbol, digits are used to specify the value of the number. The number of digits on the right side of the symbol determines how much precision the number offers. Microsoft Access provides two types of decimal numbers: Single: A single is a decimal number whose value can range from 3.402823e 38 and 1.401298e -45 if the number is negative, or from 1.401298e -45 and 3.402823e 38 if the number is positive. To use

141

this type of numbers on a field, set its Field Size to Single. Double: While the Single data type can allow large numbers, it offers less precision. For an even larger number, Microsoft Access provides the Double data type. This is used for numbers that range from 1.79769313486231e 308 to 4.94065645841247e 324 if the number is negative or from 1.79769313486231E 308 to 4.94065645841247E 324 if the number is positive. Similar to the relationships among natural numbers, a Single can fit a Double. In fact, you may see that, with experience and if you check the databases (and VBA code) of most programmers, they use the Double most of the time. Although the Double type uses more memory (Is computer memory still expensive? I guess not.), it offers higher precision than the Single, which sets its preference.

Currency Numbers
The Currency data type is used for a column made for monetary values. For such a column, set its Data Type to Currency. During data entry, the user can type a decimal number and press Enter, Tab or click somewhere else. The number would then be converted to represent a monetary value. The number would also display the currency symbol on its left. Like the Decimal Symbol, the character used for currency depends on the country or a group of countries. It can also be verified in the Regional (and Language) Settings of Control Panel in the Currency section. The Currency data type does not have a Field Size property on database objects. Instead, it uses the Format property to specify how the number would be displayed:

Practical Learning: Using the Currency Data Type


1. Open the Clarksville Ice Cream database and open the Employees table is Design View 2. In the upper section of the table, click Salary and press Tab. Click the arrow of the combo
box and select Currency 3. Save the table

Boolean Data Types


Introduction
A datum is referred to as Boolean when it can assume only one of two values. It can be either Yes or No, True or False, On or Off, non-zero or 0. Such a field is appropriate when you want the user to indicate the state of a value. To specify that a field is Boolean, set its Data Type to Yes/No.

Boolean-Based Options
To support different ways of expressing a Boolean field, Microsoft Access provides various

142

options. After setting the Data Type of a field to Yes/No, you can control how the field would be presented to the user. The most classic way of representing a Boolean value consists of displaying a check box:

With this layout, the user can either click the check box or give it focus and press the space bar. Alternatively, if you prefer, you can let the user type a value. In this case, after setting the fields data type to Boolean, in the lower section of the table in Design View, click the Lookup property page and, on the Display Control combo box, select one of the available items:

The default option is Check Box. If you select Text Box, then the user will be able to type True, False, Yes, No, On, Off, 0, or any number. Once the user types one of these values and presses Enter, Tab, or clicks somewhere else, you can control how the field would display the value. To do this, in the lower section of the table in Design View, click the General property page and, in the Format property, select one of the available options:

If you set the Format property to Yes/No and if the user types 0, the field would display No; if the user types any other number, the field would display Yes. If you set this property to True/False and if the user types 0, the field would display False; if the user types any other number, positive or negative (but it must be a number) the field would display True:

143

Practical Learning: Using Boolean Field


1. The Clarksville Ice Cream database should still be opened with the Employees table in Design View In the upper section of the table, click MaritalStatus and press Tab 2. Set its Data Type to Yes/No 3. In the lower section of the table, click the Lookup property page. From the Display Control combo box, select Text Box 4. Click the General tab and, in the Format property, make sure that Yes/No is selected 5. Save the table

Document and Object Linking


Introduction
Object Linking and Embedding (OLE) is a technique that consists of adding in your database (not just database, but our discussion will stop to Microsoft Access databases as if OLE had to do only with Microsoft Access) an object that was created using another application. The technique used to include such an object is particularly easy. Its configuration or involvement can be the subject of speculation. Over all, Microsoft Access does not care much what type of object you want to add to, or include in, your database. It is left to you to decide why you want to include the object and what type of object this would be. Some objects (can tremendously) increase the size of your database. To use an OLE object in a field, create the data field in the Design View of a table and set its Data Type to OLE Object.

Objects and Data Fields


After setting the Data Type of a field as OLE Object, since the object is external, there are not too many options or properties provided by the table. The application in which you created or will create the object should control it. To actually include an external object into the field, whether using the table Datasheet View or the form in Form View, the user can right-click the field and click Insert Object. This would open the Insert Object dialog box that presents two options to create or select the object:

If you want to use an application installed in your application to create the document, you can click the Create New radio button. Then, in the Object Type list, click the application and click OK

144

If the object has been created and resides on a portable media (floppy disk, CD, DVD, etc), on your hard drive or on the network your computer is connected to, you can click the Create From File radio button and click Browse. This would bring the Browse dialog box that allows you to locate and select the document

Practical Learning: Using OLE Objects


1. Open the Bethesda Car Rental1 database and open the Cars table in Design View 2. Notice that the Picture field has its Data Type set to OLE Object. Switch the table to Datasheet View 3. Click any cell under the Model column and, on the main menu, click Format -> Freeze Columns 4. Scroll to the right to make sure you can see both the Model and the Picture columns 5. Right-click the first empty cell under Picture and click Insert Object 6. On the Insert Object dialog box, click the Create From File radio button and click the Browse button 7. In the Browse dialog box, using the tree list under the Directories label, locate the folder that contains the resources of this ebook and select it 8. In the File Name list box, click accent.bmp

9. In the Browse dialog box, click Open and, in the Insert Object dialog box, click OK 10. Click the second cell under Picture, the one that is empty. Notice a rectangle box drawn in the cell 11. On the main menu, click Insert -> Object Click the Create From File radio button and click the Browse button. Notice that the Browse dialog box remembers the last folder used. 12. In the File Name list box, click cherokee.bmp and click Open. Then click OK 13. On the main menu, click Format -> Unfreeze All Columns 14. Close the table. When asked whether you want to save it (the question is stated because the structure of the table was modified when we froze the columns, not because we added the pictures), click No 15. On Database window, click the Forms button and double-click the Cars form to open it 16. Click the Next Record button twice to get to the third car

17. Right-click the white empty area on the top-right section and click Insert Object

18. On the Insert Object dialog box, click the Create From File radio button and click Browse 19. Navigate to your Exercises folder. From the list of File Names, click escape and click Open

145

20. On the Insert Object dialog box, click OK

21. In the same way, add a picture for each car included in the database. If the picture of a car does not appear in the list, skip it. This simply means that there is no picture 22. After using the form, close it

Hyperlinks
As mentioned already, an object created with an external application can be added to a database and the object would be included as is. When this is done, Microsoft uses an encryption technique to make the object become part of the database so you do not have to remember to include the object when distributing the database. Because of this, objects such as pictures can highly increase the size of a database. This can be convenient at times. Fortunately, the alternative to this scenario is to provide only a link to the document or file from the database to the external document. The Hyperlink data type allows you to create a field that, when clicked, would open another document on the same computer, on another connected computer, or on the Internet.

Date and Time


Introduction
Dates and times in Microsoft Access are grouped in a category referred to as Date/Time. Over all, dates and times are considered differently but, to specify that a field would use date, time, or both, set its Data Type to Date/Time. Because there are different ways to display date and time values, the Format property is used to specify how this value should appear. The Input Mask is used to assist the user with data entry. After specifying that a field will be set for dates or times, you can use the Input Mask property to create mask sections that can assist the user with entering valid dates or times as valid as possible. To support this, you can type a mask in the Input Mask or you can use the Input Mask Wizard, using the characters we reviewed for strings.

Practical Learning: Setting Date/Time Formats


1. Open the Clarksville Ice Cream database and open the Employees table in Design View 2. In the upper section of the table, click DateHired 3. In the lower section of the table, click Input Mask and click its ellipsis button 4. On the first page of the Input Mask Wizard, click Short Date and click Next 5. In the second page, accept the suggestion in the Input Mask edit box. Click Next and click

146

Finish 6. Save the table and close it 7. To create a new table, on the Database toolbar, click the arrow of the New Object button and click Table

8. In the New Table dialog box, double-click Design View and add the following fields to the table Field Name Data Type OrderID OrderDate Text Description Date the order was placed Same as Order Date but displays the name of the day of the week

AutoNumber Automatic number

DayOfWeek Text

9. Save the table as CustomersOrders and decline to create a Primary Key

Dates Formats
After a valid date value has been entered in a field, you can specify how the date would display, not necessary how the date was entered. The Format combo box provides already created formats you can use. Those are the most popular formats use for dates. If none of those satisfies you, you can use the following characters or symbols to create a desired format: Format d dd ddd dddd w ww m mm mmm mmmm q yy yyyy Used For Used to Display Days Days The day as a number from 1 to 31 The day as a number with a leading 0 if the number is less than 10

Weekdays The name of a weekday with 3 letters as Mon, Tue, etc Weekdays The complete name of a week day as Monday, Tuesday, etc Week Week Months Months Months Months Years Years The numeric day of the week The numeric week of the year, ranging from 1 to 53 The numeric month from 1 to 12 The numeric month with a leading 0 if the number is less than 10 The short name of the month as Jan, Feb, Mar, etc The complete name of the month as January, etc Two digits for the year as 00 for 2000 or 03 for 2003 The numeric year with 4 digits

Quarters The numeric quarter of the year

To use these letters, simply type the desired combination in the Format field. Here is an example:

147

This is configured to display a single digit for a day of the month if the day is less than 10, followed by the complete name of the month, followed by the year in 4 digits. During data entry, the clerk can enter a valid date. Once the field looses focus, it displays the date based on the format. Here is an example:

Based on this, you can use any combination of the formats but you should use a combination most regularly used in your language so the users would not be confused. Besides the indicated characters, you may want to use some other characters to separate them. An example would be January 5, 2004 which uses a comma in the display. To create such sections, include the characters in double-quotes. What you would be doing is to ask Microsoft Access to display such characters as is while considering the non-quotes characters as part of the format. Here is an example:

Practical Learning: Setting Date/Time Formats


1. In the upper section of the table, click OrderDate and press Tab 2. Set its Data Type to Date/Time and press F6

148

3. In the lower section of the table, in the Format field, type d mmm yyyy and press Enter. This means that we want the date to display starting with the day of the month, followed by the 3-letter name of the month, followed by the year in 4 digits 4. In the upper section of the table, set the Data Type of the DayOfWeek field to Date/Time and press F6

5. Set the Format to dddd and press Enter


6. Save the table and switch it to Datasheet View 7. Click the empty field under OrderDate. Type 04/12/1998 and press Enter 8. Under DayOfWeek, type 4/12/98 and press Enter 9. Notice that, although both fields received the same date entry, they display it differently

10. Switch the table to Design View

Times Formats
Like dates, time values follow the Regional (and Language) Settings of Control Panel when they display. To make this display friendlier, Microsoft Windows provides some characters you can use to format a time:

To control how time values should display in a field, after setting its Data Type to Date/Time, use the Format property. The characters used to create a format are:

149

Format : h or H hh or HH n or N nn or NN s or S ss or SS ttttt

Used For Used to Display The character separator for time values Separator This character is set in the Regional (and Language) Settings of Control Panel Hours Hours Minutes Minutes Seconds Seconds An hour number from 0 to 23 If the hour is less than 10, it would display without the leading 0 An hour number from 0 to 23 If the hour is less than 10, it would display with the leading 0 such as 08 A minute number from 0 to 59 If the number is less than 10, it would display without the leading 0 A minute number from 0 to 59 If the number is less than 10, it would display with the leading 0 such as 06 A second value from 0 to 59 If the number is less than 10, it would display without the leading 0 A second value from 0 to 59 If the number is less than 10, it would display with the leading 0 such as 04 Time Time using the formula of the Long Time of the Regional Settings of Control Panel time is configured to display in the standard (non time occurs in the morning, or pm (in lowercase) to display in the standard (non military time) and afternoon

am (in lowercase) if the military time) and if the am/pm AM and PM if the time is configured if the time occurs in the

AM (in uppercase) if the time is configured to display in the standard (non military time) and if the time occurs in the morning, or PM (in uppercase) AM/PM AM and PM if the time is configured to display in the standard (non military time) and if the time occurs in the afternoon a/p a (in lowercase) if the time is configured to display in the standard (non military time) and if the time occurs in the morning, or p (in lowercase) if AM and PM the time is configured to display in the standard (non military time) and if the time occurs in the afternoon A (in uppercase) if the time is configured to display in the standard (non military time) and if the time occurs in the morning, or P (in uppercase) if AM and PM the time is configured to display in the standard (non military time) and if the time occurs in the afternoon AM and PM The AM-PM character. Microsoft Access would refer to the format set in the Regional (and Language) Settings of Control Panel

A/P

AMPM

When combining these characters to create a format, you should abide by the rules of your language. You should refer to the formula set in the Time property page of the Regional (and Language) Settings of Control Panel. Microsoft Access also refers to it for the character separator. If you want to include any other character, type it in double-quotes.

Practical Learning: Using the Time Data Type


1. Click the first empty field under DayOfWeek. Type OrderTime and press the down arrow
key

2. Type MorningAfternoon and press Tab 3. Type d and press the up arrow key 4. Type d and press F6 5. Click the arrow of the Format combo box and select Short Time 6. Set the Format of the MorningAfternoon field to AM/PM 150

7. Save the table and switch it to Datasheet View

8. Under OrderTime, type 11:05 and press Tab 9. Under MorningAfternoon, type 11:05 and press Enter. Notice that the display changes
to AM 10. Switch the table to Design View

Date and Time Masks


As done with Text based fields, you can use the Input Mask property to assist the user with data entry on date and time-based fields. The idea is to create sections and include character separators in the field to help the user know where a number, a month, a year, an hour, a minute, a second, or the AM/PM can be entered. Once again, you have two main alternatives: using a wizard or creating your own mask. The easiest way of creating a mask for a date or time-based field is to use the Input Mask Wizard dialog box and follow the steps while selecting the options. You can also use the characters specified earlier to create a custom mask.

Practical Learning: Creating Date and Time Masks


1. In the upper section of the table, click OrderDate, press F6 and press the down arrow key 2. Click the ellipsis button of the Input Mask field 3. In the first page of the Input Mask Wizard, click Short Date and press Enter 4. In the second page, accept the default and press Enter twice 5. Click Input Mask to select its value and press Ctrl + C 6. In the upper section, click DayOfWeek and click Input Mask. Press Ctrl + V and save the table 7. In the upper section of the table, click OrderTime and, in the lower section, click Input Mask then click its ellipsis button 8. In the first page of the wizard, click Short Time and press Enter three times 9. Select the Input Mask value and copy it. Then click MorningAfternoon and click Input Mask. Paste the 10. Save the table and switch it to Datasheet View 11. Click the empty field under OrderDate. Type 04/12/1998 and press Enter. Under DayOfWeek, type 4/12/98 and press Enter 12. Notice that, although both fields received the same date entry, they display it differently

12. Switch the table to Design View

Exercises
Yugo National Bank
151

1. Open the Yugo National Bank database. Open the Employees table in Design View. Just

under Title, add a new Yes/No column named CanCreateNewAccount. Set its Display Control to Text Box. Save and close the table. as follows:

2. Open the Employees form in Design View and add the new CanCreateNewAccount field

Save the form and set this field as follows for the following employees: Last Name Can Create New Account? Yuen Marconi Young Holland Kast Lourde Kirkland Close the form 3. Open the Customers table in Design View. Change the Data Type of the DateCreated field to Date/Time. Change its Format to Short Date. Use the Input Mask Wizard to set its Input Mask to Short Date. Save and close the table. 4. Open the Customers form in Design View. Delete the DateCreated text and its accompanying label. Using the Field List, add the DateCreated field to where the other was. Save and close the form. 5. Open the Customers form and enter the following values in the Date Created text box Account Number Date Created 28-3782-8 38-4227-5 83-4654-7 82-3763-2 34-5458-4 68-3465-8 56-8468-5 37-5764-8 72-9375-4 20-3454-9 27-3457-4 Close the form 02/04/2002 02/04/2002 02/04/2002 02/05/2002 02/05/2002 02/05/2002 02/05/2002 02/08/2002 02/08/2002 02/08/2002 02/08/2002 Account Number Date Created 92-3782-4 68-6434-5 47-4783-2 72-3474-2 29-4586-4 40-4658-6 94-7785-3 34-9754-7 37-5490-6 76-5475-4 02/04/2002 02/04/2002 02/05/2002 02/05/2002 02/05/2002 02/05/2002 02/08/2002 02/08/2002 02/08/2002 02/08/2002 1 -8 208 6 2500 -34 -1

152

Introduction to Relationships
Overview of Relationships
Introduction
Data entry as we have performed it so far consisted of typing the necessary value in each field. Because a regular database is made of various tables, these objects work as an ensemble to create a product as complete and efficient as possible. As there can be so many objects, one of the rules a database developer should follow is to avoid duplicate entry of data: the same piece of information should not be entered in two different objects. For example, when a person is opening a bank account at a bank, a clerk enters the customers information in an object such as a form or a table:

When the same customer comes back for a transaction such as to deposit money, her information should not be entered again but that information should be selected from the form used to perform transactions:

This is the basis of relational database. Relational database is based on the idea that objects of a database are connected or related so they can exchange information. This exchange of information is made possible by creating relationships among objects of a database.

The Primary Key


If you were asked to create a bank database for the above illustration, the form used when a customer wants to make a deposit probably would need to contain such information as the customers name, her bank account, the date of the transaction, and the amount of the deposit. Per haps you would structure the form as follows: Customer Money Deposit Customer Name Bank Account Transaction Date Amount of Deposit Based on this, the clerk can simply type the name of the customer and perform the transaction. When the same customer comes back for another type of transaction such as money withdrawal or transfer, the clerk would use another form and enter the customers name. The likelihood of typing the name of the customer differently on various forms is really high. For example, when performing a deposit, the clerk may enter the name of the customer as Josiane Tobolowski. On a form used to withdraw money, the clerk may enter the customers name as Jozian Toblowsky. Obviously, these are two completely different names. To avoid this type of mistake, the solution is to create an object (table) that would hold the customers name and make that name available to (all) other objects involved in transactions. The table that holds the customers information may have the following fields:

153

Customer Information Full Name Account Number Address Phone Number Email Address When a customer needs a bank transaction, the clerk can simply select the customers name on a form and continue the transaction. To make this possible, there must be a relationship between the table that holds the customers information and the table on which the transaction is performed: Customer Information Full Name Account Number Address Phone Number Email Address When creating this type of relationship, you would be thinking that, although the customers information is needed by various objects of the database, different objects may need different types of information. For example, when performing money deposit, the clerk would need the customers account number and her name. If the customer signed to receive newsletters from the bank, when another clerk is preparing these newsletters to customers, he would need the customers name and email address but not her account number. For this reason, relational database provides you with the ability to create a special field in the table that holds the customers information. This field would be used to communicate with other objects of the database and provide them with the information they need about the customer. The name of this field usually ends with Number, Nbr, or No. Because this field is referred to as an identifier, it sometimes ends with ID. The table that holds a customers information may become: Customer Information Full Name Account Number Address Phone Number Email Address Customer ID On the objects that need information stored in the customers information table, you must create a field that would hold the relationship. For example, you can create such a field on the table used for money deposit. This field does not directly belong to the money deposit table: it acts as an ambassador. For this reason, it is called a foreign key. Because such a field belongs to the originating table, it should have the same name as the identifier of the original table. On the other hand, the field identifier will be used to manage the relationship between its table and those tables that need information stored in its table. It is called the primary key. After creating these two fields, they are used to link both tables: Customer Money Deposit Customer Name Bank Account Transaction Date Amount of Deposit

154

Customer Information Full Name Account Number Address Phone Number Email Address Customer ID

Customer Money Deposit Customer Name Bank Account Transaction Date Amount of Deposit Customer ID

Although in this example of the customers information table we illustrated only one field as the primary key, you can use more than one field as the primary key. In this scenario, what you need the primary key field to do is to keep track of the exchange of information between its table and the tables related to it. In most circumstances, you will not need to enter information in the primary key field. For this reason, you can ask Microsoft Access to provide an automatic number to the field. Based on this, you can set this fields Data Type to AutoNumber. Of course, you can let the user type the value of the primary key. For example, most companies make sure that two employees don't use the same employee number. In other words, such a number must be unique for each employee. In the same way, in the US, every person must have a unique Social Security Number. Therefore, in some cases, you can let the data entry person provide the value of the primary key. In practicality, you must strongly refrain from letting the user tamper with the primary key. The role of the primary key is to have a unique number that identifies a record in a table. This means that two records should never have the same value of the primary key. For this reason, you should also set it as AutoNumber and let Microsoft Access deal with it. There are three main ways you get a primary key on a table: If you create a table using the wizard, you will be asked whether you want Microsoft Access to assign a primary key for you If you are creating a table in Design View, you can click the Primary Key button on the toolbar while the designated field is selected, you can also click Edit -> Primary Key from the main menu If you try to save a table created in Datasheet View, since you will not have set a primary key, you will be prompted accordingly.

Practical Learning: Introducing Relationships


1. Start Microsoft Access and create a Blank Database If you had already started Microsoft Access, press Ctrl + N. From the New dialog box, click the General property page and click the Database or the Blank Database icon

2. Then click OK

3. Set the name of the database as Video Collection and click Create 155

4. To create your new table, from the Tables section, click the New button 5. From the New Table dialog box, click Design View, and click OK

6. Set the name of the first field to ActorID and set its Data Type to AutoNumber 7. While the field is still selection, on the Table Design toolbar, click the Primary Key button 8. Set its Caption to Actor ID 9. In the upper section of the table, under ActorID, set the name of the second field to Actor
with the Data Type as Text

10. Set the Caption of the Actor field to Actor/Actress 11. Set the last field as Notes with a Memo as Data Type

12. To switch the table to the other view, on the Table Design toolbar, click the View button. 13. When you are asked whether you want to save the table, click Yes. 14. Type Actors and press Enter. 15. Press Enter and enter the following names of actors: ActorID Actor Eddie Murphy Michael Douglas Glenn Close Bruce Willis Isaac de Bankole Jack Nicholson Laura Linney Demi Moore Tom Cruise Djimon Hounsou Anne Archer Bonnie Bedelia Tom Selleck Paulina Porizkova Lane Smith Close the table 16. Create a new table in Design View with the following fields:

Field Name

Data Type

Description

DirectorID AutoNumber Automatic number (Primary Key)

156

Director Notes

Text Memo

Name of a director such as Mark Lynn or directors as a group of such as The Hughes Brothers Observations about the director or group of directors

17. Save the table as Directors and switch to Datasheet View 18. Enter some directors as follows: DirectorID Director Renny Harlin Tony Scott Tim Burton Eddie Murphy Rob Reiner Jonathan Lynn Spike Lee Steven Spielberg 19. Create a new table in Design View with the following fields: Field Name Data Type Caption

VideoCategoryID AutoNumber Video Category ID (Primary Key) VideoCategory Notes Text Memo Video Category

20. Save the table as VideoCategories and switch it to Datasheet View 21. Enter a few categories on the table: Video Category ID Video Category Biography Documentary Fitness Aerobic Comedy General Comedy Police Comedy Politic Comedy War Drama General Drama Police Drama Politic Drama War Sci-Fi General Sci-Fi Comedy Sci-Fi Police Sci-Fi Politic Sci-Fi War Cartoon Close the table 22. Create a new table in Design View with the following fields:

157

Field Name VideoID (Primary Key) Title CopyrightYear Length Notes

Data Type AutoNumber Text Number Text Memo

Caption Video ID

Field Size

120 Year Integer 20

23. (To get the character, you can open Microsoft Word, type (c) then select and copy it. Then paste it in the Caption property of the table field) 24. Save the table as Videos and switch it to Datasheet View 25. Enter a few videos: Title A Few Good Men The Last Boy Scout The Distinguished Gentleman Batman Die Hard 2 Die Harder Beverly Hills Cop II Her Alibi 26. Save the table 1989 1990 1987 1998 Year Length 1993 1991 138 Mins 105 Mins 112 Mins 126 Mins 124 Mins 103 Mins 94 Mins

Introduction to Relationships
Lookup Fields
Unbound Lookup Fields
The fields we have been creating so far were classic text box fields that allow the user to simply type to create a value. Instead of letting the user type the values of a field, if you want, you can establish a list of values that are valid for a certain field. This would allow the user to simply select from that list. Such a field is called lookup field. The simplest type of lookup field consists of creating a list whose items you know at the time you are creating the database. For example, if a clerk must specify the gender of persons whose records she is creating, since there are only two genders, you can create a list that contains only male and female items. Since there would not be suspicion of a new value, you can safely create such a list. The lookup list is provided through a combo box. To set or change a value in the field, the user can expand the combo box and select an item. The item selected in stored in the field and is stored as a string (as text) There are three main ways you can create a simple lookup field: In Datasheet View, create or select a field whose value should be selected from a list. Then, on the main menu, click Insert -> Lookup Column In Datasheet View, create or select a field whose value should be selected from a list. Then right-click the column header and click Lookup Column In Design View, locate the field whose values should be selected from the list and set its Data

158

Type to Lookup Wizard Any of these actions would launch the Lookup Wizard. Since in this case you would be creating a known list, you should select the second radio button and proceed.

Practical Learning: Setting Preset List Of Items


1. The Videos table of the Video Collection database should still be opened Right-click the Length column header and click Lookup Column... 2. On the First Page of the Lookup Wizard, click the second radio button

3. Click Next

4. Click the first empty field under Col1 and type G 5. Press the down-arrow key and type PG 6. Press the down-arrow key and type PG-13
7. Type the other ratings you are aware of, if any:

8. Click Next

9. For the Column Label, type Rating and press Enter


10. Set the ratings of the movies by selecting from the Rating combo box:

159

11. Close the Videos table

12. Open the Music Category1 database 13. Open the Artists table in Design View 14. Click the Structure field 15. For its Data Type, choose Lookup Wizard...
16. When the first page of the Lookup Wizard comes up, choose the second radio button telling the wizard that you will type values for the field, then click Next

17. Click the empty field under Col1 and type Solo 18. Press Tab and type Duo 19. Press Tab and type Band 20. Press the down arrow key and type Soundtrack 21. Press Tab and type Orchestra 22. Press the down arrow key and type Compilation 23. Press the down arrow key and type Other

24. Click Next. Accept the column label as Structure and click Finish 25. Click the Lookup tab in the lower part of the Design View To make sure that the user can only choose a preset value in the list, set the Limit To List field to Yes On the other hand, if you wanted to allow the user to type new entries, you would set the Limit To List field to No (keep in mind that even if you restrict the user to choose only from the list, you can eventually modify that list) 26. Save, and then close the table

Bound Lookup Fields


160

As done with the simple lookup, you can create a field whose data would be selected from a list. As opposed to an unbound lookup fields whose values you can predict at the time you are creating a database, a bound lookup field is one whose values are not known in advance. The values for such a field become available as the database is growing. We mentioned earlier that tables could be linked to exchange information. Based on our illustration, a foreign key field from a table can be used to provide information to its table by retrieving it from the originating table. When creating such a relationship, you should know what table would be providing such information and how the relationship would be managed. To create a bound lookup field, you select a field and proceed as we saw for an unbound lookup field to open the Lookup Wizard. This time, you would select the first radio button and click Next. This would give you the opportunity to select the table that will supply the necessary information. In this case also, you can specify more than one column to be presented in the list.

Practical Learning: Getting Fields Data From External Source


1. Open the Video Collection database and open the Videos table in Datasheet View 2. Click any field under the Notes column. 3. On the main menu, click Insert -> Lookup Column... 4. In the first page of the Lookup Wizard dialog, make sure the first radio button is selected and click Next 5. On the second page, click VideoCategories:

6. Click Next 7. From the Available Fields list box, double-click VideoCategory 8. Click Next and Next 9. For the label, type Category and click Finish 10. Set the appropriate category for each movie

161

11. Close the table

Exercises
Watts A Loan
1. Open the Watts A Loan database. Create a new table in Design View with the following fields: Field Name Data Type Additional Information Primary Key Caption: Type of Loan ID Caption: Type of Loan Memo

TypeOfLoanID AutoNumber TypeOfLoan Description

2. Save it as TypesOfLoan and close it 3. Using AutoForm, generate a form based on the TypesOfLoan table. Save it as
TypesOfLoan and design it as follows before saving and closing it

4. Open the TypesOfLoan form and create the following types of loan: Type of Loan ID Type of Loan 1 Personal 2 Car 3 Boat 4 Furniture We have some partnerships in musical instruments 5 Musical Instrument stores. This is the type of loan we will make available to the customers they find for us Description This is loan given as a cashier check to a customer who wants a cash loan This loan will be processed by our partners as car dealers

5. Open the Transactions table. In the Datasheet View, create a new column using the
Lookup (Column) Wizard. Include the AccountNumber and the LastName fields of the

162

Customers table. Set its label to Account # then save and close the table

6. Open the Transactions table in Design View. Insert a new field just under TransactionID.
Name it Processed By and start the Lookup Wizard. Include the LastName, the FirstName, and the Title fields from the Employees table. Save and close the table 7. Using AutoForm, generate a form based on the Transactions table. Save it as Transactions and design it as follows:

Close the form

Tenley Associates
1. Open the Tenley Associates database and open the Employees table in Design View. Using the Lookup Wizard, configure the DepartmentName field so its value would origin from the DepartmentName Column of the Departments table. Set its label to Department. Save and close the table

2. Open the Employees form in Design View and delete the DeparmentName text box. Using
the Field List, add the DepartmentID field to where the other was. Adjust the design of the form as follows:

Save and close it

Yugo National Bank


1. Open the Yugo National Bank and, in Design View, create a new table with the following fields:

Field Name

Data Type

Additional Information Primary Key Caption: Charge Reason ID

ChargeReasonID AutoNumber

163

ChargeReason Description Memo

Caption: Charge Reason

Save it as ChargeReasons and close it

2. Using AutoForm, generate a form based on the ChargeReasons table and save it as
ChargeReasons before closing it

3. Open the ChargeReasons form and create the following records Charge Reason ID Charge Reason Description 1 Monthly Charge Applied every month to all accounts 2 Overdraft Close the form Applied if a customer's account remains negative for 72 hours

Managing Relationships
Numeric Fields Referencing
Most of your data entry will be performed on forms. This is done to protect your tables from (even unintentional) corruption. This means that, during table design, you should be aware of what table is doing what and why. The combo boxes we have created so far provide a good mechanism for data entry but as long as you know what data a field is holding, you don't necessarily have to create these combo boxes on tables. The only piece of information a foreign key field really needs is a number: the number is what connects it to the Primary Key field of the originating table. Therefore, once you understand the use of relationships and lookup fields, you can simply create a numeric field that acts as a liaison between two tables.

Practical Learning: Creating a Numeric Lookup Field


1. Open the Video Collection database you started in the previous lesson 2. From the Tables section of the Database window, open the Videos table in Design View 3. Right-click CopyrightYear and click Insert Rows 4. In the new empty field, type DirectorID and set its Data Type to Number 5. In the lower section of the view, make sure the Field Size is set to Long Integer. In the
Caption field, type Director 6. Save the table and switch to Datasheet View

7. Without closing the Videos table, from the Tables section of the Database window, doubleclick the Directors table to open it 8. Display both tables so the Directors table is on top and in the background while the

164

Videos table is at the bottom

9. Then enter the number of the DirectorID from the Directors table to the corresponding
Director in the Videos table

10. Close both tables

Relationship Diagrams
The concept of relational database insures data reliability on the concept of data moving from one source to another. There are many goals behind this theory. Data in your resources needs to be as much accurate as possible. Provided your database is made of various objects, mainly tables, you should avoid any redundancy possible. In other words, data from one source should be unique. To accomplish these goals, you interrelate the various components of your database, namely tables (remember, data in your database depends on, or is originating from, tables). In our earlier illustration, we saw that a foreign key field created in a table acts as an ambassador. To make this effective, a formal relationship must be created between that field and the primary key field of the table it represents. There should be some type of link between both fields. When you are creating a Lookup field, you are indicating that the value entered in this particular field will come from another table, and you specify the originating table. The originating table is the parent table. The target table is the child table. The reason you established Primary Keys in your tables is because these are the fields used to build relationships between tables. They are used to verify the uniqueness of data. Also, they avoid that data in relationships be mixed. You can build a reliable relationship only between data of the same kind. We also saw that, to make it easy to recognize the primary key of a parent table and the foreign key of a child table, both fields should have the same name, although this has little to do with the database itself: as long as both fields have the same data type, the relationship can be created. Tables and fields relationships are created and managed in a special window called the Relationship window. To display it, on the Database toolbar, you can click the Relationships button. Alternatively, on the main menu, you can click Tools -> Relationships. After clicking one of those, if no relationship exists among the tables in the current database, the Show Table dialog box would come up, asking you to select the tables whose relationship(s) you want to create. If at least one relationship has been created between two tables, the Relationship window would come up and display that relationship or the already existing relationships. In this case also, if a table of the current database is not represented in the window, to add it, display the Show Table dialog box, select the table, click Add and click Close. You can create a relationship only between two tables that are present on the

165

Relationships window. This means that even if a table is part of your database and you want to link it to another table (of your database), if the table has not been added to the Relationships window, you cannot create or manage its relationship to another table. Of course, there are other ways you can create relationships without using the Relationships window but the Relationships window gives you advanced and detailed means of creating and managing relationships. When the Relationships window is displaying, a new menu group is added to the main menu: it is the Relationships. To establish a relationship that does not yet exist between two tables, you can drag the primary key from the parent table to the foreign key of the desired table. If drag it accurately, the relationship would be acknowledged and you can just click Create to make it formal. If you dropped the primary key on the wrong field, you would have time to select the appropriate fields in the Edit Relationship dialog box. After working with the Relationships window, you can close it. You would be asked to save it in order to keep the relationship(s) created.

Practical Learning: Establishing Tables Relationships

1. Open the Music Collection1 database 2. On the Database toolbar, click the Relationships button The Show Table property sheet comes up. From here, you will specify what tables (or queries) will be used when building your relationship (s):

3. Click MusicCategories once and click the Add button 4. Double-click the MusicAlbums 5. On the Show Table dialog box, click the Close button 6. To add another table as if we forgot it, right-click an empty area in the Relationships window and click Show Table 7. In the Show Table dialog box, click AlbumTracks. Then click Add and click the Close button 8. Arrange the layout of your Relationships window so that the MusicAlbums table is in the middle of the MusicCategories table on its left and the AlbumTracks table on its right. The originating table uses its Primary Key and associates it to the field you choose in the target table. The target field is referred to as the Foreign Key 9. Drag the MusicCategoryID field from the MusicCategories table and drop it on top of the MusicCategoryID field in the MusicAlbums table:

166

10. The Edit Relationship dialog box comes up. This allows you to confirm creating a relationship Click the Create button to create the relationship Now you have a line relating these two tables 11. Drag any field from the MusicAlbums table and drop it on top of any field in the AlbumTracks as if you missed the target

12. Once again, the Edit Relationship dialog box comes up On the dialog, under the left Table/Query, click the field that is selected to display its combo box. In that left combo box, select AlbumID and press Tab 13. Under Related Table/Query, click the field that is selected and click the arrow of its combo box 14. Select AlbumID

167

15. Click Create 16. To add another table that we failed to include to the diagram, on the main menu, click Relationships -> Show Table 17. In the Show Table dialog box, double-click Artists and click Close 18. Position the new table to the top left section of the Relationships window and move the MusicCategories table under it 19. To create a new relationship, on the main menu, click Relationships -> Edit Relationship 20. On the Edit Relationship dialog box, click Create New 21. In the Create New dialog box, click the arrow of the Left Table Name combo box and select Artists. In the Right Table Name combo box, select MusicAlbums. In the Left Column Name combo box, select ArtistID. In the Right Column Name combo box, select RecordingArtistID

22. Click OK 23. In the Edit Relationship dialog box, click Create

24. On the Relationship toolbar, click the Save button and close the Relationships window 25. Now we will include a table without using the Relationships window.

168

Open the MusicAlbums table in Design View 26. Click the Format field to give it focus 27. Press Tab, type L and press F6 28. When the first page of the Lookup Wizard comes up, accept the first radio button and click Next 29. Click Formats and click Next

30. In the list, double-click AlbumFormat and click Next:

31. Agree to let Microsoft Access Hide The Primary Key and click Next 32. Accept the label as Format and click Finish 33. Accept to save the table 34. Save the table and switch to the Datasheet View to verify that the Format field has a combo box and does not allow any value that is not coming from the Formats table 35. Specify the appropriate formats

36. When you have finished, close the MusicAlbums table 37. To open the Relationships window, on the main menu, click Tools -> Relationships Notice that, this time, the Relationships window opens because some relationships had already been created among tables 38. On the main menu, click Relationships -> Show Table 39. On the Show Table dialog box, double-click Formats and click Close 40. Notice that a joining line is created between the MusicAlbums table and the Formats table

169

41. Save and close the Relationships window

Exercises
Watts A Loan
1. Open the Watts A Loan database. Start a new table in Design View and create it with the following fields: Field Name LoanProcessingID EmployeeID DateProcessed CustomerID TypeOfLoanID LoanAmount InterestRate PeriodicPayment FirstPaymentDueDate RegularPaymentsDueOn NumberOfPayments Notes Number Memo Data Type AutoNumber Number Date/Time Number Number Currency Number Currency Date/Time Additional Information Primary Key Caption: Loan Processing ID Caption: Processed By Format: Short Date Input Mask: 99/99/00 Caption: Date Processed Caption: Account Number Caption: Type of Loan Loan Amount Field Size: Double Format: Percent Caption: Interest Rate Caption: Periodic Payment Format: Short Date Input Mask: 99/99/00 Caption: 1st Payment Due Date Caption: Regular Payments Due On Field Size: Integer Caption: Number of Payments

2. Save it as LoanProcessing and close it

3. Open the Relationships window and create the relationships as follows:

170

If you are using Microsoft Access >= 2000, print the Relationships diagram and save it as Watts A Loan Map

Yugo National Bank


a) Open the Yugo National Bank and create a new table in Design View with the following fields: Field Name TransactionID Processed By Account Number Transaction Type b) Save the table as Transactions c) Use the Field Builder to add the TransactionDate field of the Transactions sample table under the other fields d) Use the Field Builder to add the TransactionNumber field of the Transactions sample table under the other fields e) Use the Field Builder to add the DepositAmount field of the Transactions sample table under the other fields f) Use the Field Builder to add the WithdrawalAmount field of the Transactions sample table under the other fields g) Use the Field Builder to add the ServiceCharge field of the Transactions sample table under the other fields g) Use the Lookup Wizard for the Processed By field. Select the LastName, the Title, and the CanCreateNewAccount fields of the Employees table. Keep the label as Processed By h) Use the Lookup Wizard for the Account Number field. Select the AccountNumber and the AccountName fields of the Customers table. Keep the label as Account Number i) Use the Lookup Wizard for the Transaction Type field. Select the TransactionType field of the TransactionTypes table. Keep the label as Transaction Type j) Add a new field at the end of the table and name it Charge Reason. Use the Lookup Wizard for the Charge Reason field. Select the ChargeReason field of the ChargeReasons table. Keep the label as Charge Reason k) Add a new field under the others. Name it Notes and set its Data Type to Memo Save the table and close it Data Type AutoNumber Additional Information Primary Key Caption: Transaction ID

171

Referential Integrity
Cascades
Introduction
At this time, we know that there is useful functionality to creating relations between tables as they allow the user to select existing information instead of typing it. This flow of information brings up issues about what happens if data that exists in a parent table gets deleted while such information has been made available to another table. When manipulating data that is in a relationship, it is very important to make sure that data keeps its accuracy from one table or source to the other. To accomplish that goal, some rules must be established to watch or monitor the flow of information between two tables. Data or referential integrity is used to check that two tables are related through one field on each table used as the primary key and the foreign key, data entered in the foreign key of a child table must exist in the parent table or it would be rejected, only two fields of the same data type are used to establish a relationship between two tables, the tables involved in the relationship belong to the same database.

Cascades on Related Records


After creating a relationship between two tables, you must then make sure that when data changes in the parent table, this change is reflected in the child table. For example, if a bank customer changes her last name after getting married or after a divorce, you should be able to change her name in one object (table) and the related objects, such as the one used to process her transactions would receive the changes without your having to make the change on each object (table). In the same way, when data is deleted, the objects that are related to it must also have that data deleted. To enforce the rules of data integrity, Microsoft Access provides three check boxes in the Edit Relationship dialog box. First, if you want Microsoft Access to monitor data flow, you can click the Enforce Referential Integrity. This would make available two other check boxes.

The Direction of a Relationship


172

The One-To-Many Relationship


As mentioned already, a relationship between two tables allows one table, the parent, to make its information available to another table (the child). Because in this case the user is asked to select information, it is likely that the same record of a parent table can be tied to various records in the child table. For example, one customer at a bank can deposit an amount of money today. The same customer can make another deposit tomorrow and even another deposit next month. In such a case, the relationship between the tables would show various entries of the same customers account number in the object (table) used to deposit money but with different transactions. This type of relationship is known as one-to-many because one entry in the parent table can result in many entries in the child table. To create a one-to-many relationship, check all three referential integrity check boxes and click OK or Create. The parent table would have a one on its side of the joining line. The child table would have the infinity symbol on its side of the joining line.

Practical Learning: Editing Relationships


1. Open the Music Collection1 database you were working on in the previous lesson 2. To display the Relationships window, on the main menu, click Tools -> Relationships 3. To control the relationships, on the Relationships window, click the joining line between MusicCategories and MusicAlbums. Notice that it becomes thicker than the others 4. On the main menu, click Relationships -> Edit Relationship 5. Click the Enforce Referential Integrity check box. Now, the database would like to know how you would handle data updating and deletion 6. Check the other two check boxes:

7. Click OK 8. In the Relationships window, right-click the joining line between the Artists and MusicAlbums tables:

9. Click Edit Relationship... from the popup menu 10. Click all the three check boxes and click OK 11. In the Relationships window, double-click the joining line between MusicAlbums and

173

AlbumTracks 12. In the Edit Relationship dialog box, click all three check boxes and click OK 13. Using one of the above three techniques, configure the joining line between the MusicAlbums and the Formats tables for a one-to-many relationship that performs both cascade update and cascade deletes

14. Save the relationships window and close it

The Many-to-Many Relationship


Although one-to-many is the most common type of relationship applied on tables, in some databases, you may need to create a relationship in which many records from one table A can have many related records in another table B and vice versa. This type of relationship is known as many-to-many. For example, in our Video Collection database: It is possible to have one video that has many actors. In this case, if we had created a field to receive actors in the Videos table, we would enter many names of actors in that one field but this type of database would not be professional At the same time, one actor can have participated in many videos. In this case, if we had created a field to enter the titles of videos in the Actors table, the field would have too many entries, making the table unprofessional

To implement this type of relationship, you can create what is called a junction table. A junction table is a table whose main purpose is to bring together fields from other tables, creating a type of cross relationship for the necessary fields. A junction table can be very helpful for data analysis and sub-forms/sub-reports:

A junction table is usually made of three or four fields (usually not less than three and usually not more than four; a classic junction table has only three fields). The first field, almost less engaged, is used as the primary key, the same type of field almost every table has. The other fields hold data that would emanate from other tables. You can create a junction table either in Datasheet View or in Design View: To create a junction table in Datasheet View, you use the Lookup Column menu that would call the Lookup Wizard. From the Lookup Wizard, select the table that holds the desired field, then select the field itself, and click Finish. After adding the first column, repeat the same steps for each needed field To create a junction table in Design View, set the field's data type to Lookup Wizard and proceed the same way you would for the Lookup Column

174

You can also switch to either view to create a junction table. In other words, you can create one field in one view and create the other field in the other view.

Practical Learning: Creating Junction Tables


1. Open the Video Collection database you started in Lesson 12
2. To create a new table, on the main menu, click Insert -> Table 3. From the New Table dialog box, double-click Design View

4. Type VideoActorID as the name of the first field 5. Set its Data Type to AutoNumber 6. Right-click the VideoActorID name and click Primary Key 7. Save the table as VideosAndActors 8. Click the empty field under VideoActorID, type ActorID then press Tab, type L and press
F6 9. In the first page of the Lookup Wizard, make sure the first radio button is selected and click Next. 10. On the second page of the wizard, make sure Actors is selected and click Next 11. In the Available Fields list, double-click Actor and click Next twice 12. Change the field's label to Actor/Actress and press Enter 13. When asked to save the table, click Yes 14. Switch the table to Datasheet View 15. In Datasheet View, right-click Actor/Actress and click Lookup Column 16. In the first page of the Lookup Wizard, make sure the first radio button is selected and click Next 17. From the list of tables, click Videos and click Next 18. From the Available Fields, double-click Title to select it and click Next 19. Make sure the Hide Key Column check box is marked and click Next

20. Change the label to Video Title and click Finish


21. Switch the table to Design View

22. Set the Description of VideoID to The title of a video 23. Set the Description of ActorID to An actor or actress who participated in this video

24. Save the table and switch it to Datasheet View 25. To perform data entry, on the Video Title column, click the arrow of the combo box and select A Few Good Men

175

26. Then, on the Actor/Actress column, click the arrow of the combo box and select Jack Nicholson

27. In the same way, complete the table as follows:

28. Close (and if necessary save) the table. 29. To open the Relationships window, on the main menu, click Tools -> Relationship... 30. Observe the names of tables on the window Right-click an empty area of the Relationships window and click Show Table... 31. On the Show Table dialog box, double-click Directors table. Also, if there is a table on the Show Table property sheet that is not displaying in the Relationships window, add it 32. To close the Show Table property sheet, click the Close button 33. Position the VideosAndActors table between the Actors and the Videos tables 34. Drag DirectorID from Directors and drop it on top of DirectorID in Videos 35. Check the Enforce Referential Integrity check followed by the Cascade Update Related Fields and Cascade Delete Related Fields check boxes

36. Click Create 37. As done previously, double-click each joining line and enforce its reference integrity to both update and delete records in the Edit Relationship dialog box

176

38. If you are using Microsoft Access 2000 and later, on the main menu, click File -> Print
Relationships...

39. Click the close button. When asked to save the report, click Yes. Change the name of the report to Video Collection Layout and click OK 40. Close the Relationships window (in Microsoft Access 97, if you are asked to save the window, click Yes).

The One-to-One Relationship


A one-to-one relationship is the type of junction between two tables A and B so that one record in a table can have only one corresponding entry in table B and vice versa. Because this is similar to one table of records, this type of relationship is hardly used since you can as well simply create one table.

Subdatasheets
A sub datasheet provides a technique of creating or displaying relationships in a table in a Datasheet View. It can help you or the user see information that is stored in another table. For example, when using a music collection database, it can should the music tracks that are part of an album by displaying an album in a table as long as a relationship has been created and configured. To use a sub datasheet, open a table or query in Datasheet View and click the + button on the first column of the desired record. Here is an example:

Practical Learning: Using a Sub Datasheet


1. Open the Music Collection database 2. On the Database Window, from the Tables section, double-click the MusicAlbums table

3. Click the + button on the left of Tribute 177

4. Notice that the tracks of the music album display 5. To perform data entry, click the + button of the One Bright Day record 6. Click the empty field under # then type 1 and press Enter 7. Complete the list of tracks as follows: # 2 One Bright Day 3 Who Will Be There 4 When The Lights Gone Out 5 All Love 6 Look Whos Dancing 7 Justice 8 Love Is The Only Law 9 Pains Of Life 10 Urban Music 11 Problems 12 All You Got 13 When The Lights Gone Out (Jamaican Stylee) 8. After viewing the table, close it Track Title Length 04:16 04:12 04:10 04:09 04:39 05:00 04:12 04:07 03:46 02:54 04:02 04:19 04:52

1 Black My Story (Not History)

Exercises
Watts A Loan
Open the Watts A Loan database and configure the cascading of relationships as follows:

178

Save and close the Relationships window

Yugo National Bank


Open the Yugo National Bank database and open its Relationships window. Enforce the cascades on relationships as follows and save it:

If you are using Microsoft Access >= 2000, print the Relationships dialog box and save its report as YNB Main Diagram

Introduction to Data Analysis


Techniques of Sorting Records
Introduction
Data analysis provides the user with the ability to examine a database's records and the overall behavior of its objects. Data analysis is performed on tables, queries, and/or forms. There are two main aspects involved with data analysis: what you provide to the users and what the users may decide to do with data at their disposal. An intermediate to advanced user of Microsoft Access will know how to perform some, most, or all of the operations we will review. In some other cases, you may want to create objects such as forms and/or reports that isolate records instead of showing all records. These types of forms and reports can be based on a query or a SQL statement. In some other cases, you can create queries that your users would run to get a fixed list of records based on a rule of your choice. For these and many other reasons, you should be aware of what your users can do and what they should not do.

Record Sorting on Tables


By default, if you have a first field on a table to register incremental numbers (AutoNumber) as the user enters records, the records are organized in the order they were entered. They

179

typically follow the ordinal numbers defined in the first field, as numbers are counted from the lowest to the highest. One way you can change this order is to rearrange the list of records based on a field of your choice. Rearranging the order of records is referred to as sorting. To sort records, you must first select the field that would be used as the reference. To do this, you can click a field under the column of your choice. You have two options. To arrange the list in alphabetical order, you can ask the table to display its records in ascending order. To arrange records in alphabetical order following the field of your choice, you would use the Sort Ascending option, which is available from the main menu (Records -> Sort -> Sort Ascending). Besides the regular arrangement of records, you can also sort records in reverse alphabetical order. This is done using a column as basis using Sort Descending. Both techniques of sorting are also available when you right-click the desired field on the table. When you have finished viewing, it is sometimes important to reset the table before continuing unless you want to keep the table sorted. If you sort records on a column whose fields are not all filled, which means some records are empty, the empty records would display first before the other records start in alphabetical order. This would allow you to find out which fields have not been filled; that is, what records are incomplete or missing. For example, in our students registration form, imagine you want to find out what students do not have the emergency name (which means if something happens, the user wouldn't know who to call) (of course, an alternative would be to make such a field Required), you can sort the emergency name. Here is an example:

For this reason, you can sort records on a field, not because you want to get the alphabetical order, but because you would like to find out what record(s) need(s) to be completed. This could be used to find out what student doesn't have an e-mail address yet. Besides the sorting of text fields, you can also arrange a list of records by seniority. This is usually done by sorting a date field. In the case of a student list, you can sort records based on the date of birth. When sorting a list of records based on a date, the year is first considered. This means that, if two records have different years, the record with the oldest date would display first (of course, to get the youngest date first, you can sort in descending order). If two dates have the same year value, the month would be considered. The date with the earliest month would display first. If two dates have the same year and the same month, then their day values would be considered. By right clicking, you can sort any field in the table or form. When a field has a combo box with two values, such as the M/F field for the Gender column, you can sort a Boolean column whose fields are equipped with a check mark. If you sort such a field in ascending order, the True, On, Yes or 1 records would display first, followed by the opposite records.

Practical Learning: Sorting Records on Tables


180

1. Open the ROSH database and open the Students1 table in Datasheet View 2. To view the list of students in alphabetical order based on their last name, click any field under the Last Name column

3. On the main menu, click Records -> Sort -> Sort Ascending

4. Notice that some students have the same last name 5. To see a list of students by date of birth starting with the youngest, click any field under the Date of Birth column 6. On the Table Datasheet toolbar, click the Sort Descending button 7. To restore the table to its original arrangement, right-click any field under Student ID and click Sort Ascending 8. Close the table. When asked whether you want to save the table, click No

Record Sorting on Forms


When reviewing forms, we saw that a form can display in Datasheet View, like a table or a query. With that type of form, you can apply the same techniques we used to sort records on a table. If you display a form in its regular and most usual format, where it displays one record at a time, you can still perform the same sorting operations as done on a table. This allows you to view one record at a time.

Practical Learning: Sorting Records on Forms


1. In the Database window, click the Forms button and double-click the Students form to open it in Form View

2. Observe the last name of the first record. To navigate through the records, click the Next
Record button a few times

3. To get to the first record, click the First Record button 4. To jump to a specific record, select the number in the Record Number
type 42: text box and

5. Press Enter. Notice that the table has jumped to record 42

6. To navigate backward, click the Previous record button


7. To return to the first record, press Ctrl + Home 8. To organize the student's Last Names alphabetically, click the Last Name field on the form 9. On the main menu, click Records -> Sort -> Sort Ascending:

181

10. Notice that the records are arranged alphabetically based on the students last names 11. To arrange the list of students by age starting with the youngest, click the Date of Birth field

12. On the Form View toolbar, click the Sort Descending button
13. To sort records using the context-sensitive menu, right-click the Gender field and click Sort Ascending 14. To dismiss the sorting of records, on the main menu, click Records -> Remove Filter/Sort 15. To sort records based on a Boolean field, we will find out who (students) lives in a single parent home. 16. Right-click the Single Parent? label or its check box and click Sort Ascending 17. Navigate through the records. Notice that the records of students who live in a single-parent home display first 18. When you have finished viewing, to remove the sorting, right-click anywhere on the form and click Remove Filter/Sort 19. Close the form

Record Filtering on Datasheet and Form Views


Introduction
So far, we have built fairly simple queries that consisted of displaying all records that are part of a table. The only thing we were doing was to select the necessary fields. In some circumstances, you may want to set a limit on the number of records to display or make available to the user. To do this, you must create a rule and ask Microsoft Access to apply it to a set of records (also called a Recordset). The rule works like a funnel that decides what to let through and what to retain. The rule is also called a criterion. For example, you can set a criterion that asks a query to consider the list of all students in a school but to restrict the list only to female students. A filter is a criterion or a set of criteria that must be applied to a Recordset to create a list of records that abide by a common rule. Filters can be used to isolate records on a table, a query, a form, or a report. There are differences on the way each type of value handles it.

Records Filtering Using Selections


While sorting is used to rearrange data in alphabetical, incremental, or decremental orders, filtering allows you to isolate data. For example, when you order the Gender column alphabetically, you get a list of girls first (F for Female), then the boys (M for Male). Using a filter, you can create a list that would include only one of these categories. Fields on a table are organized in categories. For example, in the Last Name, all records are meant

182

to represent a string as people's last name. The content of such a field can be used as a basis for selecting records. It is another way of asking a table to isolate records that share the exact same content. This technique of isolation is referred to as Filter By Selection. To filter records that display on a data sheet, based on a selection, you can first click a field that would be used as the basis. Then on the main menu, you can click Records -> Filter -> Filter By Selection. Imagine you have a list of videos in a Video Collection database and stored in a table named tblVideos:

Imagine you want to have a list of only movies that are rated R. To do that, you can click an R field and filter by selection:

Unlike the sorting techniques, filtering hides data. In order to execute another filter on all records, you must remove the previous filter, unless, as we will see shortly, you want to combine filters. The context menu provides the same options available on the toolbar. You can also filter records using a Boolean field that is equipped with check boxes. For example, on the Single Parent? column of the Students table, you can ask the table to show only the list of students who live in a single parent house. To do this, you can filter by selecting a record that is checked.

Practical Learning: Filtering Data By Selection


1. Open the ROSH database and, from the Tables section of the Database window, open the Students1 table 2. To filter records by selection, under the Gdr column, click any field that has M 3. On the main menu, click the Records -> Filter -> Filter By Selection 4. Scroll down in the list and notice that the table displays only male students 5. Also notice that the bottom section of the table displays Filtered 6. To remove the filter, on the main menu, click Record -> Remove Filter/Sort 7. To view only the records whose ZIP Codes are known, click any field under ZIP Code

8. On the Table Datasheet toolbar, click the Filter By Selection button 183

9. Notice that the list displays only records that have an entry in the ZIP Code

10. To remove the filter, on the Datasheet toolbar, click the Remove Filter button
11. Close the Students1 table. When asked whether you want to save the changes, click No 12. On the Database window, click the Forms button and double-click the Students form 13. To get only the list of girls, click the Next Record button a few times until a record displays F in the Gender field

14. Right-click F and click Filter By Selection


15. Navigate through the records and notice that the form now displays a list of only female students. To indicate this filter, the number of records displays (Filtered):

16. To refresh the form, on the main menu, click the Records -> Remove Filter/Sort 17. Navigate to a field whose Single Parent? check box is checked 18. For an example of filtering a Boolean field, right-click a Single Parent? field (one that is checked) and click Filter by Selection 19. Notice that the form is now displaying a list of only the students who live in a single parent home 20. To remove the filter, right-click anywhere on the form and click Remove Filter/Sort

Filter By Exclusion
Instead of using a field's content as a basis for inclusion, you can ask the table to deny or hide the records that respond to a certain field. This is referred to as filtering by exclusion. In Microsoft Access, this is done using Filter Excluding Selection. Imagine that, on your Videos table, you want to get a list of movies that are not rated R, you can right-click an R field in the Rating column and click Filter Excluding Selection.

Practical Learning: Filtering Records By Exclusion


1. Navigate to a record whose State field displays MD 2. To get a list of the students who live outside of Maryland, right-click MD in the State field and choose Filter Excluding Selection 3. Notice that the form displays a list that excludes MD

4. When you have finished viewing, on the Form View toolbar, click the Remove Filter
button 5. Close the Students form

Filter By Form
184

The techniques we have used so far to analyze our data consisted of looking for a particular field content as a basis for our filtering. Microsoft Access provides another technique that allows you to select a criterion from an empty field. Using this technique, the whole table is emptied and all records get hidden. You can then select your criterion from the column of your choice. Although the fields appear empty, each column equips its first and only field with a combo box that displays a list of all records of that column, thereby allowing you to select, which one of the fields responds to your choice. This technique is referred to as Filter By Form.

Practical Learning: Filtering By Form


1. From the Tables section of the Database window, open the Students1 table 2. On the main menu, click Records -> Filter -> Filter By Form 3. Click the empty box under Gdr. To get a list of female students, click the arrow of the Gender combo box and click F 4. To apply the filter, on the main menu, click Filter -> Apply Filter/Sort 5. Scroll down in the list and notice that the table displays only girls

6. To remove the filter, on the main menu, click Records -> Remove Filter/Sort 7. Close the table. When asked to save it, click No 8. From the Forms section of the Database window, double-click Employees

9. On the Form View toolbar, click the Filter By Form button


10. Delete the value in the Empl # field 11. To get a list of only the staff members who live in Maryland, click the State label or field and notice the button that appears 12. Click the button on the State field and click MD

13. On the Form View toolbar, click the Apply Filter button 14. After viewing the records, to restore the records, on the Form View toolbar, click the
Remove Filter button 15. Close the form

Data Analysis With Operators


185

Introduction
Queries are meant to provide advanced techniques of performing data analysis. Because they use the SQL, they use a syntax that is not directly available to tables and reports. In fact, queries provide a good alternative to creating the record sources that can be used to populate forms and reports. To make this effective, it is a good idea to know what the SQL has to offer. To perform data analysis, besides the techniques of selection, exclusion, and form we have used so far, you can use operators. We have already reviewed some of the operators used throughout Microsoft Access. Such operators can also be used when filtering records. Besides those, the SQL provides additional operators to further filter data. To provide a more refined criterion to filter data, the table and form can present a special text available from right-clicking the object. This is presented as Filter For. When the text box displays, you can use operators to write an expression and apply it as the criterion.

Advanced Filter By Selection


All of the techniques we used to filter data by selection, exclusion, and form on tables are also available on queries. As done on tables and forms, such criteria do not get saved. This is used to preserve data even if a filter was previously applied to an object. If you want to create a list that permanently reduces the number of records available, you can use a query. Based on its structure, a query uses operators to filter data and saves the criteria. To create a query to filter records by selection, you should open it in Design View and use Criteria field to write the expression that will be applied. To write an expression that would be used as the criterion of data filtering on a Datasheet View of a table or a query or the Form View of a form, right-click the object. Then, in the Filter For text box, type the expression and press Enter. There are a few rules you should observe: Each operator must be written as is. All operators we reviewed can be used To include a letter, a character, or a string, type it between double-quotes. An example is M. Another example would be El Salvador. Fortunately, if you forget to use the double-quotes, Microsoft Access would add them. In some circumstances, if you forget to use the doublequotes, Microsoft Access would not add them and the expression might fail. Therefore, to be on the safe side, always add the quotes. If a date or time value is part of an expression, include it between two # symbols. An example would be #12/8/94#. Another example is #05/02/04#. If you forget the # symbol, most of the time, Microsoft Access would not correct it. This leaves the responsibility on you. All built-in constants, True, False, NULL, etc, do not use quotes.

Of course, there are situations in which these rules can or must be applied differently. When in case, you will be appropriately directly.

Practical Learning: Filtering For


1. From the Tables section of the Database window, open the Students1 table in Datasheet View

2. To apply a filter by typing, we will get a list of the students who live in Maryland. Rightclick any field in the State column, click in the Filter For: text box

3. Type =MD

186

4. Press Enter 5. To remove the filter, right-click anywhere on the table and click Remove Filter/Sort

6. To get a list of students who live outside of Virginia, right-click the State field, click Filter
For, type = NOT "VA" and press Enter 7. Close the table. When asked to save, click No

Data Analysis and Filtering by Comparison


Databases and other programming environments provide operators you can use to perform data analysis. We have already reviewed the logical operators used because they apply to other scenarios. These operators can also be very valuable for data analysis and/or filtering. Comparisons are performed on Boolean, numbers, date, time, or string fields or values. To perform a comparison on a Boolean field, you can right-click it, click Filter For and type the desired value as True or as False. After pressing Enter, the database would perform the comparison and display the result. When comparing date-based or time-based values, include the date or time value between two # signs. For example, to get a list of records that occur before 1/1/1950, you would type an expression such as <=#1/1/1950#

Practical Learning: Performing Comparisons


1. The ROSH database should still be opened. Open the Students1 table in Datasheet View

2. To get a list of students who were born before January 1, 1988, right-click the Date of
Birth field, click Filter For:

3. Type <#01/01/1988# and press Enter


4. After viewing the list, remove the filter 5. On the main menu, click Records -> Filter -> Filter By Form

6. To get a list of students who were born on or after June 30, 1988, click the empty field
under Date of Birth column and type >=#6/30/1988# 7. To apply the filter, on the main menu, click Records -> Apply Filter/Sort 8. Close the table. When asked whether to save the changes, click No 9. On the Database window, click Queries and double-click the Staff Members query to open it 10. Switch it to Design View

11. To see only the people who were hired before 1995, in the Criteria row for the DateHired
field, type <#1/1/96# This means "show me the people whose DateHired field is less than January 1st, 1996", which means anybody hired before 1996

187

12. Then run the query 13. To sort this list by seniority, right-click a field under the Date Hired column and click Sort Ascending:

14. To save this particular query, on the main menu, click File -> Save As...

15. In the Save As dialog box, set the name of the query to
Staff Members Hired Before 1996 16. Click OK 17. Close the query 18. From the Database Window, click the Queries button if necessary. Right-click the Staff Members query and click Design View

19. To get the list of employees who live in Maryland, in the Criteria field for State, type
="MD" 20. Run the query and then switch back to Design View

21. To find out which ones of the employees do not reside in MD, change ="MD" to <>"MD"
22. Run the query and close it without saving it

Exercises
Yugo National Bank
1. Open the Customers table and sort records by State then remove the criteria View a list of customers who live in MD View a list of customers who live outside of MD Based on the ZIP Code, view a list of customers who live in DC (ZIP Code between 20000 and 20599). Notice some discrepancies of bad data entry Close the table without saving it 2. Open the Employees form View a list of only employees who have the capacity to create a new bank account View a list of cashiers View a list of employees who live outside of Baltimore View a list of employees who earn less than $16.00/hr Close without saving the form

The Structured Query Language


Introduction to SQL
Overview
188

So far, to create a query we have learned to use either the Query Wizard or the Design View of a query. In both cases, we were selecting fields and adding them to the query. This concept of building a query is based on the Structured Query Language abbreviated SQL. In fact, all queries are based on SQL and this language is used by most database development environments, including Microsoft Access. SQL can be pronounced Sequel or S. Q. L. On this site, we will consider the Sequel pronunciation. For this reason, the abbreviation will always be considered as a word, which would result in A SQL statement instead of "An SQL statement". Also, on this site, we will regularly write, The SQL instead of The SQL language, as the L already represents Language. Because Microsoft Access provides very flexible and advanced means of creating queries, you can create almost any type of query without knowing anything about the SQL but it is important to understand this language because you should have an idea of what Microsoft Access does when you ask it to create a query. This would allow you to troubleshoot a query when necessary. Furthermore, you may have to interact with applications created from other environments. Queries are built from the SQL. Like every computer language, the SQL comes with its syntax, vocabulary, and rules. The SQL is equipped with keywords that tell it what to do and how to do it. We have established that a query resembles a question you ask the database and the database responds. This works by asking the database to isolate or select some fields and create a new object made of those fields. In order to ask the database to create a query, that is, to isolate fields, you must write a statement made of keywords, operators, and database objects.

The SELECT Keyword


When creating a query, we saw that you must specify what object holds the field(s) you want to include in the query. The object can be a table or another query. If you are using the Simple Query Wizard, you select the object in the Tables/Queries combo box:

If you are starting a query in Design View, you select the object in the Show Table dialog box:

189

The most fundamental keyword used by SQL is SELECT. In order to process your request, you must specify what to select. This is done using the FROM keyword. Therefore, the SELECT keyword uses the following syntax: SELECT What FROM WhatObject; Over all, the SQL is not case-sensitive. This means that SELECT, Select, and select represent the same word. To differentiate SQL keywords from "normal" language or from the database object, it is a good idea to write SQL keywords in uppercase. A SQL statement must end with a semi-colon. In the SQL, the object is specified after the FROM keyword and by the WhatObject parameter of our syntax. For example, if you want to create a query based on a table named Persons, you would write the statement as: SELECT What FROM Persons; We also saw that, after specifying the object that holds the fields, you can then select each desired field and add it to the query. If you are using the Simple Query Wizard, you can double-click the field in the Available Fields list:

If you are using the Select Query window, you can drag the field from the list and drop it in the lower section of the view:

190

In the SQL, to select a field, enter its name after the SELECT keyword. For example, to select the LastName field of the Persons table, you would type SELECT LastName FROM Persons; If you want to include more than one field from the same table, separate them with a comma. For example, to select the first and last names of the Persons table and include them in your query, you can use the following statement: SELECT FirstName, LastName FROM Persons; We also saw that, to select all fields from an object and include them in your query, you could drag the asterisk field and drop it in the lower section of the query in Design View. In the same way, to include everything from the originating table or query, use the asterisk * as the field. Here is a statement that results in including all fields from the Persons table: SELECT * FROM Persons;

Practical Learning: Using the SELECT Keyword


1. Start Microsoft Access and open the Bethesda Car Rental1 database 2. Open the Cars table and switch it to Design View to review its list of fields 3. Close the Cars table 4. On the Database Window, click the Forms button 5. On the main menu, click Insert -> Query 6. On the New Query dialog box, click Design View and click OK 7. Click the Close button on the Show Table dialog box 8. On the main menu, click View -> SQL View. Notice that a Notepad-like window appears.

9. Change the content of the window to SELECT Make FROM Cars;

10. To run the query, on the Query Design toolbar, click the Run button 11. After viewing the query, to get back to the SQL View window, on the main menu, click View -> SQL View. 12. To list the makes, models, and years of the cars, change the statement as follows: SELECT Make, Model, Year FROM Cars; 13. Run the query to see the result:

191

14. After viewing the query, right-click its title bar and click SQL View 15. To create a query that includes all fields from the table, change the statement as follows: SELECT * FROM Cars; 16. Run the query 17. After viewing the query, right-click its title bar and click SQL View

Record Sorting on Queries


All of the techniques used to sort records on a table can also be applied to a query that displays in Datasheet View. To create more advanced queries, the SQL allows you to sort a field on a query and use this arrangement as part of the query. To create a query that has a field sorted as part of its statement, open the query in Design View. Once in Design View, click the Ascending field of the desired column and select Ascending from its combo box. In the same way, you can sort the field in reverse order by selecting the Descending option. In SQL, to sort a field in ascending order, you can include the ORDER BY clause in your statement. The syntax used would be: SELECT What FROM WhatObject ORDER BY WhatField; The field used as the basis must be recognized as part of the selected columns. Imagine you have created a list of staff members made of their first and last names in a table named StaffMembers. If you want to order the list in alphabetical order based on the LastName column, you would use a statement such as: SELECT FirstName, LastName FROM StaffMembers ORDER BY LastName; If you use the * operator to include all fields, you can order the list based on any of the table's fields, as we learned during data analysis. Imagine that you have created a query that includes all fields. The following statement would list the records of the StaffMembers table based on the alphabetical order of the LastName column: SELECT * FROM StaffMembers ORDER BY LastName; By default, records are ordered in ascending order. Nevertheless, the ascending order is controlled using the ASC keyword specified after the based field. For example, to sort the last names in ascending order of a query that includes the first and last names, the above statement can also be written as follows: SELECT FirstName, LastName FROM StaffMembers ORDER BY LastName ASC; The second statement can be written as: SELECT * FROM StaffMembers ORDER BY LastName ASC; If you want to sort records in descending order, use the DESC keyword instead. It produces the opposite result to the ASC effect. To sort records in reverse alphabetical order, the above two

192

statements can be written as: SELECT FirstName, LastName FROM StaffMembers ORDER BY LastName DESC; The second statement can be written as: SELECT * FROM StaffMembers ORDER BY LastName DESC;

Practical Learning: Sorting Records in Queries


1. Open the ROSH database 2. In the Tables section of the Database window, click Students1 to select it 3. To create a new query, on the main menu, click Insert -> Query and, in the New Query dialog box, double-click Design View 4. In the Students list, double-click FirstName, LastName, Gender, DOB

5. Click the box that is at the intersection of LastName and Sort to reveal its combo box 6. Click its arrow and select Ascending

7. To view the result, on the Query Design toolbar, click the Run button
8. Close the query. When asked to save the query, click Yes

9. Type List of Students as the name of the query and press Enter
10. In the Database window, click the Queries button. To create a new query, on the Database window, click New and double-click Design View 11. In the Show Table dialog box, click Close. Right-click an empty area of the Select Query window and click SQL View 12. Change the statement as follows: SELECT LastName, FirstName, DateHired, Salary, MaritalStatus FROM Staff ORDER BY DateHired; 13. Run the query

193

14. Close the query. When asked whether you want to save the query, click Yes

15. Type Staff Members By Seniority as the name of the query and press Enter

SQL and Filter By Selection


Filter By Selection in SQL is performed using the WHERE clause in a SQL statement. Its basic syntax is: SELECT What FROM WhatObject WHERE Expression; We learned that, to perform data analysis, a criterion is specified using an expression. The expression could be that records should only be about students who live in a single parent home. The same types of expressions are used in SQL, following some rules. We saw that, to get a list of employees who live in Maryland, in Filter By Form, we could type an expression such as =MD or ="MD" (remember that if you type =MD and press Enter, Microsoft Access would change it to ="MD"). In SQL, to create a list of staff members who live in Maryland, we can write the following statement: SELECT FirstName, LastName, State FROM Staff WHERE State="MD"; To build your expressions, you can use any of the Boolean, logical, and comparison operators we have studied.

Practical Learning: Querying by Selection


1. Open the Bethesda Car Rental1 database 2. To create a new query, on the main menu, click Insert -> Query and double-click Design View 3. On the Show Table dialog box, click Close 4. To write a SQL statement, right-click an empty area in the window and click SQL View 5. To list only Ford cars, change the statement as follows: SELECT Make, Model, Year FROM Cars WHERE Make="Ford"; 6. Run the query 7. After viewing the result, right-click its title bar and click SQL View 8. To query the list of available cars, change the statement to the following: SELECT Make, Model, Year, Available FROM Cars WHERE Available=True; 9. Run the query 10. Close the query. When asked whether to save, click No

194

11. Open the ROSH database


12. To create a new query, on the main menu, click Insert -> Query and double-click Design View

13. In the Students1 list, double-click LastName, FirstName, Gender, SingleParentHome,


EmergencyName, EmergencyPhone

14. To create a list of only students who live in a single parent home, click the box that is at
the intersection of SingleParentHome and Criteria. Type =True

15. To view the SQL statement, right-click the title bar of the window and click SQL View

16. Run the query 17. Switch the query back to Design View 18. Since we already know what the list includes, we do not need to show the SingleParentHome column. Under SingleParentHome, remove the check box of Show 19. To view the SQL statement, right-click an empty area of the window and click SQL View 20. Run the query 21. Close the query. When asked whether you want to save the query, click Yes

22. Type Students Who Live In A Single Parent Home as the name of the query and press
Enter

Microsoft Access and SQL Statements


Qualifying Fields in Statements
While Microsoft Access is faithful to the SQL, it adds its own little details when creating or interpreting the statements it is confronted with. Instead of using field names as we have done so far, Microsoft Access likes recognizing the object that holds a field just by looking at the referred field. When studying operators, we saw that the name of a field should be delimited by square brackets to reduce confusion in case the name is made of more than one word. We also mentioned that the

195

square brackets provide a safeguard even if the name is in one word. Based on this, to create a statement for a query that includes the first and last names of a Persons table, you can write it as follows: SELECT [FirstName], [LastName] FROM [Persons]; To identify a field as belonging to a specific table or query, Microsoft Access usually associates its name to the parent object. This association is referred to as qualification. To qualify a field, you consider the object that is holding the field, then add a period followed by the name of the field. The basic syntax of a SELECT statement would be: SELECT WhatObject.WhatField FROM WhatObject; Imagine you want to get a list of Persons by their last names from data stored in the Persons table. Using this syntax, you can use a statement as follows: SELECT Persons.LastName FROM Persons; Or SELECT [Persons].[LastName] FROM [Persons]; In the same way, if you want to include many fields from the same table, qualify each and separate them with a comma. To list the first and last names of the records from the Persons table, you can use the following statement: SELECT Persons.FirstName, Persons.LastName FROM Persons; Or SELECT [Persons].[FirstName], [Persons].[LastName] FROM [Persons]; If you want to include everything from a table or another query, you can qualify the * field and qualify it as you would any other field. Here is an example: SELECT Persons.* FROM Persons; Or SELECT [Persons].* FROM [Persons];

Statement Lining
Some of the SQL keywords are used to control blocks of sub-statements. Such words as we have seen so far are SELECT and FROM. A good technique of making a SQL statement easy to read consists of isolating each major keyword and its sub-statement on its own line. Using this approach, a basic SELECT statement would follow this syntax: SELECT WhatObject.WhatField FROM WhatObject; Here is an example: SELECT Persons.FirstName, Persons.LastName FROM Persons;

196

Queries and Relationships


Introduction
When creating relationships among tables, we were selecting the primary key of one table and the foreign key of a dependent table to join them. Once such a relationship is created, you can create a query that combines both tables to create a set of records, also called a record set, or a Recordset, that would include either all records or isolate only the records that have entries. For example, imagine you have created a Persons table as follows where the Gender of a record is selected from a lookup field: 1. Open the Music Collection1 database that you started in the previous lesson

2. On the Database toolbar, click the Relationships button


3. On the Relationships window, click the joining line between the Artists table and the MusicAlbums table to select it 4. On the main menu, click Relationships -> Edit Relationship 5. After making sure that ArtistID and RecordingArtistID are selected in the combo boxes, click the Join Type button In the Join Properties dialog box, click the first radio button (it should be selected already)

6. Click OK twice 7. Open the Rockville Techno database 8. Open the CompanyAssets table in Design View 9. Right-click Notes and click Insert Rows

10. In the new empty field, type AssignedTo


We are setting the name of this field to AssignedTo. This field will be linked to the EmployeeID field of the Employees table. In reality, you should set the name of such a field similar to the primary key it is linked to. We are using a different name here just to demonstrate how to create a relationship in the query Design View. In the future, always give the same name as the field it is related to, in the parent table. In this case, it should have been named EmployeeID.

11. Set its Data Type to Number 12. In the lower section of the view, make sure the Field Size is set to Long Integer. In the
Caption field, type Assigned To 13. Save the table and switch it to Datasheet View 14. In the Assigned To column, type the numbers as follows: Asset ID Asset Type 1 Printer 2 Computer 2 Assigned To

197

3 Laptop 4 Printer 5 Digital Camera 6 Computer 7 Computer 8 Computer 15. Close the CompanyAssets table 16. In the Database window, click the Forms button

1 4

17. To create a new query, on the main menu, click Insert -> Query and, in the New Query dialog box, double-click Design View 18. In the Show Table dialog box, double-click Employees and CompanyAssets then click Close 19. From the Employees list, drag EmployeeID and drop it on top of AssignedTo in the CompanyAssets list:

20. Notice that a line has been drawn between the tables and it joins both fields. Right-click the line that joins the tables and click Join Properties 21. Notice that the first radio button that represents an inner join is selected Click OK 22. To select the fields, in the CompanyAssets list, double-click AssetType, Make, Model, and PurchasePrice 23. From the Employees list, double-click LastName and First Name

24. To view the SQL statement, right-click the title bar of the window and click SQL View: 198

25. To view the result of the query, on the Query Design toolbar, click Run

26. Notice that, with this inner join, only the asset(s) assigned to an employee are displayed.
Any asset not assigned to an employee does not display. After viewing the query, close it. When asked whether you want to save it, click No 27. Open the CompanyAssets table in Design View 28. Change the Field Name of AssignedTo to EmployeeID and make sure it keeps its Caption as Assigned To 29. Save the table and close it 30. As the CompanyAssets table is still selected in the Tables section of the Database window, to create a new query, on the Database toolbar, click the arrow of the New Object button and click Query. In the New Query dialog box, while Design View is selected, click OK 31. Notice that the CompanyAssets table is already selected. To create a relationship between the CompanyAssets table and the Employees table, rightclick an empty area in the upper section of the window and click Relationships 32. Right-click an empty area in the Relationships window and click Show Table 33. In the list of tables, double-click CompanyAssets (the Employees table should already be in the window; if not, add it also) and close the Show Table dialog box 34. Drag EmployeeID from the Employees list and drop it on top of EmployeeID in the CompanyAssets list 35. After making sure that EmployeeID is selected in both combo boxes, click Join Type. In the Join Properties dialog box, make sure the first radio button is selected and click OK 36. In the Relationships dialog box, click the Enforce Referential Integrity check box and click the check boxes under it 37. Click Create 38. Notice the 1 and infinity symbol between the CompanyAssets and the Employees tables Save and close the Relationships window 39. To add a table, right-click an empty area on the Select Query window and click Show Table 40. In the list of tables, double-click Employees and click Close 41. To select the fields, in the CompanyAssets list, double-click AssetType, Make Model, and PurchasePrice 42. From the Employees list, double-click LastName and First Name

199

43. To view the SQL statement, right-click the title bar of the window and click SQL View

44. To view the result of the query, on the Query Design toolbar, click Run
same as the above result

. The result is the

45. After viewing the query, close it. When ask whether you want to save it, click Yes

46. Type Assets Assigned To Employees and press Enter

Outer Joins
The queries we have used so far and that were based on related tables allowed us to get only the columns that had entries based on the established relationships. Columns that didn't follow the rules were excluded. Instead of excluding columns, the SQL allows you to create a query that includes all fields, not just those that follow rules, as long as the records are part of either table. Such a query is referred to as outer join. To manage the result of this type of query, the SQL considers the direction of a relationship. When creating relationships, we learned to drag a primary key from one table, the parent, to a dependent table, the child. In this type of relationship, the table (or query) that holds the origin of the relationship is referred to as the Left table (or query). The other table is referred to as the Right table (or query). Based on this, there are two types of outer joins: the left join is represented in SQL as LEFT JOIN and the right join is represented by RIGHT JOIN. As done with the inner join relationship, the left and right joins can be prepared in the Relationships window on tables. If the query has already been created and you want to change its direction, you can change it in the Design View of the query.

Practical Learning: Creating Outer Join Relationships


1. Open the Video Collection1 database and, on the Database toolbar, click the Relationships
button 2. In the Relationships button, double-click the joining line between Directors and Videos 3. In the Edit Relationship dialog box, click Join Type 4. In the Join Properties dialog box, read all options then click the second radio button

200

5. Click OK 6. In the same way, double-click each line and configure it with the second radio button of the Join Properties dialog box 7. Open the Music Collection1 database and open the Relationships window 8. Configure each relationship as follows:

9. If you are using Microsoft Access 2000 and above, to create a report for the relationships, on the main menu, click File -> Print Relationships 10. To save the report, press Ctrl + S 11. Type Music Collection Diagram as the name of the report and press Enter 12. Close the Relationships window 13. Open the Video Collection database and its Relationships window. Then, configure all relationships as done for the Music Collection1 database:

14. Save and close the Relationships window 15. Open the Rockville Techno database and, on the Database toolbar, click the Relationships button 16. Right-click the line between Employees and CompanyAssets then click Edit Relationship 17. In the Relationships dialog box, click Join Type and click the second radio button

201

18. Click OK twice 19. Save and close the Relationships window 20. On the Database window, click the Tables button and click CompanyAssets 21. On the main menu, click Insert -> Query. Since Design View is selected, click OK 22. As done previously, add the Employees table to the query 23. From the CompanyAssets list, double-click AssetType, Make Model, and PurchasePrice 24. From the Employees list, double-click First Name and LastName

25. To view the SQL statement, right-click the title bar of the window and click SQL View. Notice
the LEFT JOIN clause in the statement

26. To run the query, on the main menu, click View -> Datasheet View

27. After viewing the query, close it. When asked whether you want to save it, click Yes

28. Type Assets Already Assigned and press Enter


29. To follow the same steps to create a query with the same fields, once again, on the main menu, click Insert -> Query. Since Design View is selected, click OK 30. As done previously, besides the CompanyAssets table, add the Employees table to the query

31. From the CompanyAssets list, double-click AssetType, Make, Model, and PurchasePrice
32. From the Employees list, double-click First Name and LastName 33. Right-click the line between CompanyAssets and Employees then click Join Properties 34. In the Join Properties dialog box, read the text of all radio buttons. Click the third radio button

202

35. Click OK

36. To view the SQL statement, right-click the title bar of the window and click SQL View. Notice
the RIGHT JOIN clause in the statement

37. To run the query, on the main menu, click View -> Datasheet View

38. After viewing the query, close it. When asked whether you want to save the query, click Yes

39. Type Assets Not Yet Assigned and click OK


40. Close Microsoft Access

Exercises
Watts A Loan
Open the Watts A Loan database and configure the relationships among its tables as follows:

Save and close the Relationships window

Yugo National Bank


Open the Yugo National Bank and open its Relationships window. Configure the directions

203

of the relations as follows then save the diagram:

Exploring Data Analysis


Combinations of Operations
Overview
To further enhance your filtering capabilities, you can use Boolean algebra combined with the operators we have used so far. Besides the logical operators we know already, Boolean algebra adds extra operators used to concatenate expressions. Boolean Algebra works on logical statements. A statement is a sentence that acknowledges a fact or a possibility. That fact is eventually evaluated as being true or false. There are three main types of logical statements: Some statements can clearly be evaluated as being true or as being false (or at least they would hardly change). Examples include: "An hour contains 80 minutes", "You are a girl", "Gabon was colonized by Portugal", or "Argentina won the 1998 World Cup". Some statements are true at one time but can change to false at another time. Examples include: "Melbourne is the capital of Australia", "It is now 12:00 PM", "My monitor is 17 inches", or "It is raining". Some statements cannot be easily evaluated. Such statements could be vague. Examples include: "This girl is attractive", "It is going to be a sunny day tomorrow". Some other statements, although they can logically be evaluated, because of the way they are stated, they appear as vague. Examples include: "Santiago is a large country" (first of all, Santiago is not a country; even if Santiago were a country, what is the criterion for evaluating that a country is large?).

After a statement is formulated, it is evaluated as being true or false. We have already applied this concept during data analysis. Imagine that, in your database of students, you want to see a list of students whose records indicate a home telephone number. The statement to be evaluated is: This student's record indicates a home phone number

A statement such as "This student's record indicates a home phone number" is evaluated as being true or false. If the record of the student referred to holds a home phone number, the statement is true. If the record referred to does not display a home telephone number, the statement is false. We have already seen that such a record can be filtered with an expression such as =Not Null. We know that, in our database, besides the home telephone number, a students record also can provide an emergency telephone number (a number to dial if something happens to the student). If the record of a student does not have a home telephone number that we want to use to contact

204

a student, we can just find out whether an emergency number was provided. Therefore, we can also filter records using a statement such as: This student's record provides an emergency phone number

Now, in case we want to contact somebody for the student, if a student's record does not display a home telephone, alternatively, we can use the emergency telephone. This means that we need to find out if the student's record displays either one of those numbers.

Logical Conjunction: The And Operator


Imagine that you are reviewing the students records of a school and you want to make sure that you know whom to contact in case of emergency for each student. For example, imagine that you are trying to make sure the record of each student provides an emergency telephone number. The statement to evaluate would be: This student's record provides an emergency phone number

If the record of the student referred to contains an emergency phone number, the statement is true. If the record does not provide this information, our goal is not met and the statement is false. Imagine that, on the other hand, we want to find out if the record of each student displays the name to contact in case of emergency. The statement considered would be: This student's record provides an emergency name

If the record considered displays an emergency name, the statement is true. Imagine that a student's record indicates an emergency telephone number but does not provide an emergency name. What if a student's record indicates an emergency name but no emergency telephone number? It appears that in the absence of one of these pieces of information, it would be hard to perform an effective contact. To make a record complete or to accomplish our goal, we want each record to have both an emergency name and an emergency telephone number. We can combine both of the above statements as follows: "This student's record provides an emergency phone number" AND "This student's record provides an emergency name"

Evaluating the combined statement would produce the following results: If the record of the student referred to does not provide an emergency phone number, the record of the student is not complete and our goal is not met, regardless of the second statement. Therefore, the combined statement is false. If the record of the student referred to provides an emergency phone number, then we would consider the second statement. If the record does not provide a name in case of emergency, the record is not complete and our goal is not met. Therefore, the combined statement is false. If the record of the student being considered provides neither an emergency phone number nor an emergency name, the record is still not complete and our goal is not met. Therefore, the combined statement is false. If the record of the student being considered provides both an emergency telephone number and an emergency name, we consider that the record is complete and our goal is met. Therefore, the combined statement is true.

To resume, our goal is met only if BOTH the first and the second statement are TRUE. On a table or query that displays in Datasheet View, or a form, to combine two statements, you can use Filter by Form and select a criterion for each field that is being considered. Another alternative is to concatenate (join) statements. This is done using the AND operator.

Practical Learning: Filtering Using Logical Conjunction


1. Open the Bethesda Car Rental1 database and open the Cars form in Form View

205

2. On the main menu, click Records -> Filter -> Filter by Form 3. To see a list of SUV cars, click the arrow of the Category combo box and select SUV

4. On the main menu, click Records -> Filter -> Apply Filter/Sort

5. After viewing the records, on the main menu, click Records -> Remove Filter/Sort 6. On the Form View toolbar, click the Filter by Form button 7. Delete the content of the Category combo box

8. Imagine that a customer wants a car that has A/C and a CD player.

To combine two criteria for a logical conjunction, click the check box of Air Condition. Then click the check box of CD Player

9. On the Form View toolbar, click the Apply Filter button:

10. Navigate through the records and verify that each of the filtered cars has BOTH air condition and a CD Player. 11. After viewing the records, to refresh, on the Form View toolbar, click the Remove Filter button. 12. Right-click an empty area on the form and click Filter by Form 13. Remove the check marks on the form 14. Imagine that another customer wants to lease a small car. To proceed, you need to find out what Economic category cars are Available

206

Click the check box of Available 15. Then, in the Category combo box, select Economy 16. Right-click an empty area on the form and click Apply Filter/Sort 17. After checking what small (Economy) cars are Available, right-click on the form and click Remove Filter/Sort 18. Open the ROSH database and, from the Queries section of the Database window, open the Staff Members query 19. Switch it to Design View 20. To get the list of employees whose salaries range from $10 to $15, in the Criteria for Salary

21. Type >=10 And <=15


22. Run the query

23. To get a list of employees whose salary is greater than $10 AND live in MD, in the Criteria for
Salary, type >=10

24. Then, in the Criteria for State, type =MD


25. Run the query 26. Switch it back to Design View and delete both criteria

27. To get a list of the employees who earn more than $11 AND are married AND (but) do not live
in Maryland, in the Criteria, for the Salary field, type >=11 28. For the Criteria field of the MaritalStatus column, type True

29. For State, type <>"MD"

30. Run the query 31. Switch it to Design View and delete the Criteria values of the Salary, the MaritalStatus, and the State columns 32. Run the query

Logical Disjunction: The OR Operator


Imagine that our main goal is to make sure that we have a number we can use to contact somebody for the student. In this case, either the home phone number or the emergency number would be fine. We already have the following two statements: 1. This student's record indicates a home phone number 2. This student's record provides an emergency phone number To get either number, we can concatenate these two statements and evaluate the truthfulness of either one of them. We create a new statement as follows: "This student's record indicates a home phone number" OR "This student's record provides an emergency phone number"

207

The comparative evaluation produces the following results: If the student's record indicates a home phone number, our goal is met and we do not need to evaluate the second statement. Therefore, the combined statement is true. If the student's record does not indicate a home phone number, we can then consider the second statement. If the student's record provides an emergency phone number, we have a number we can use. This means that the result of the first statement is not important. Therefore, the combined statement is true. If the student's record indicates a home phone number and the student's record provides an emergency phone number, our goal is still met; we can use either number. Therefore, the combined statement is true. If the student's record does not indicate a home phone number, then we consider the second statement. If the student's record does not provide an emergency phone number, our goal is not met: we do not have any number to contact somebody for the student in case of emergency. Therefore, the combined statement is false.

The logical disjunction shows us that a combined statement is true if EITHER of its two statements IS TRUE. The logical disjunction produces a false result if BOTH of its two statements are FALSE. To perform a logical disjunction, you can use the OR operator.

Practical Learning: Filtering Using Logical Disjunction


1. The ROSH database should still be opened with the Staff Members query. Switch the query to Design View

2. To get a list of employees who live in Maryland OR in Virginia, for the State field, in the
Criteria row, type =MD Or VA 3. Run the query and notice that staff members who live in DC are not in the list 4. Switch to Design View

5. To run the same query, in the Criteria under State, type MD 6. Press the down arrow key (that should take you to the OR field of the Criteria for State), then
type VA 7. Run the query 8. Close the query without saving it 9. Open the Bethesda Car Rental1 database and click the Forms button 10. Double-click the Cars form to open it in form View 11. On the main menu, click Records -> Filter -> Filter By Form If the Air Condition and the CD Player check boxes are white (instead of being NULL), click each to make it appear NULL like the other check boxes. Also, if any combo box or text box displays any value, delete it

12. Imagine that a customer wants to rent a small to medium size car. These fit in the Economy
and Compact categories. To use the OR operator, click in the Category combo box and type: ="Economy"OR"Compact"

208

13. On the Form View toolbar, click the Apply Filter button 14. Navigate through the list to see the small cars of Economy and Compact 15. After viewing the list, on the Form View toolbar, click the Remove Filter button 16. Right-click an empty area on the form and click Filter by Form 17. Delete the content of the Category combo box 18. To get a list of cars that have either a Cassette player or a CD Player (or both), click the check box of Cassette

19. On the bottom left section of the form, click the Or tab

20. Click the check box of CD Player. 21. Right-click an empty area on the form and click the Apply Filter/Sort

22. Notice that the first car has a Cassette player but not a CD Player. The second car has not
Cassette player but has a CD Player. The 12th car has both a Cassette player and a CD Player

23. After viewing the records, right-click an empty on the form and click Remove Filter/Sort 24. Click the Cassette check box twice to make appear NULL like the others 25. Click the left Or tab on the lower-left section of the form and click the CD Player check box twice to make it NULL 26. Right-click anywhere on the form and click Apply Filter/Sort

Combination of Logical Operators

209

You can apply more restrictive filters by combining logical operators, as long as you follow some rules. Imagine that in your database of students, you want to get a list of girls whose records indicate either a home telephone number or an emergency telephone number. On the other hand, imagine that, at your car rental company, a customer wants to rent a small car that has a cassette player. To find these records, you should proceed by logic thinking and combine filters that can produce the right result. Because databases are varied and scenarios are different, there is no strict recipe to follow, just some suggestions. Imagine that, in your database of students, you want to see a list of girls who live in a Single Parent home. Using the Filter by Form on a table, in the Gender column, you can just select F and, in the Single Parent? column, you would select the check box. Imagine now that you want a list of male students whose records display either a home telephone number or an emergency telephone number. The expression to evaluate would look like this: "Home Phone Contains Something For Each M Gender" AND "Emergency Number Contains Something For Each M Gender". To create the criteria using Filter by Form on a form, for the first criterion, you would select M in the Gender combo box and, in the Home Phone field, you can type IS NOT NULL (which means that this field must not be empty for the criterion to apply):

Then click the OR tab and proceed the same for both the Gender combo box and the emergency telephone number field:

After applying the filter, you would notice that the list displays only boys whose records have either of both telephone numbers. Suppose you want a list of girls whose records have incomplete information on who to contact in case of emergency. To satisfy this goal, we want each girl to have either a home telephone number OR both an emergency name AND an emergency telephone number. We believe that, if the record has a home number, we can call her home and ask for Mr. or Mrs. Last Name. If the record does not have that number, we want to have an emergency number. Because we saw earlier (or as our records of some students indicate) that an emergency number is not

210

necessarily the (direct) parent, we want to make sure that we have a corresponding emergency name. Such an expression can be created as follows: "<'Gender=F' AND 'Home Phone IS NULL'> OR <'Gender=F' AND 'Emergency Name IS NULL AND Emergency Phone IS NULL'>". Using the Filter By Form on a form, for the Look For section, we would select the F Gender and, in the Home Phone field, we can type IS NULL. Then, we click the OR tab and, in the Gender combo box we select F; in the Emergency Name, we would type IS NULL and, in the Emergency Phone, we type IS NULL:

Practical Learning: Combining Logical operators


1. The Cars form of the Bethesda Car Rental1 database should still be opened in Form View. On the main menu, click Records -> Filter -> Filter By Form 2. Imagine that a customer who cannot drive stick shift wants to rent a small car. This means that you must check Available Economy cars that have Automatic Transmission Click the Available check box 3. In the Category combo box, select Economy

4. In the Transmission combo box, select Automatic:

5. On the main menu, click Filter -> Apply Filter/Sort

211

6. Notice that there are only two cars available 7. After viewing the records, imagine that the customer would like to know what else you have in the smaller cars. Besides the Economy cars, you want to see the available compact cars also. Right-click an empty area on the form and click Filter by Form. 8. Click the OR tab 9. Click the Available check box. In the Transmission combo box, select Automatic 10. In the Category combo box, select Compact 11. Right-click an empty area on the form and click Apply Filter/Sort 12. After viewing the records, right-click on the form and click Remove Filter/Sort 13. Close the form 14. Open the ROSH database 15. From the Queries section of the Database window, double-click the Staff Members query to open it 16. Switch it to Design View

17. To see an alphabetical list of employees who live either in Maryland or in DC, set the Sort
order of LastName to Ascending

18. In the Criteria field for State, type =MD 19. In the OR field for City, type =DC

20. Run the query 21. Switch back to Design View 22. To get an alphabetical list of Maryland-resident employees who are married, delete ="DC" in the OR field for the State field 23. In the Criteria field under the MaritalStatus column, type =Yes

212

24. Run the query 25. To save the current query, on the menu bar, click File -> Save As...

26. Type Married Maryland Staff Members and press Enter


27. Close the Married Maryland Staff Members query

Logical Operators: Between


The Filter By Form feature allows you to filter records by assigning appropriate criteria. The Filter By Form is like a dialog box in the form of a datasheet where you decide how to set the criteria. A technique used to filter records between ranges of values involves the use of the BETWEEN keyword. The Between comparison is usually combined with the AND operator to get a list of records between two values.

Practical Learning: Filter With Wildcards


1. The ROSH database should still be opened. From the Forms section of the Database window, double-click the Students form to open it in Form View

2. Right-click the Date of Birth field and click the Filter For: text box, type
Between #1/1/1985# And #12/31/1985# 3. Press Enter 4. After viewing the records, right-click on the form and click Remove Filter/Sort 5. Close the Students form and, on the Database window, click Queries 6. Double-click the Staff Members query and switch it to Design View

7. Click the Criteria for Salary and type Between 10 And 15


8. Run the query then close it without saving it

Like Wildcards
A wildcard is a character or a group of characters that specify a criterion the database should follow to find records. When performing filtering, wildcards are usually used with the LIKE operator.

Practical Learning: Filter With Wildcards


1. To get a list of students who live in single parent homes, on the Form View toolbar, click the Filter By Form button 2. On the form, check the box for the Single Parent? field and delete any criteria in the other boxes 3. Then click the Apply Filter button on the main toolbar

4. When you have finished viewing, click the Remove Filter


box for Parents Names, type Like Dr*

button on the toolbar

5. To get a list of students whose parents are doctors, click the Filter by Form button . In the
6. When you have finished viewing, click the Remove Filter button on the Form View toolbar. 7. Close the form.

213

Data Analysis With Charts


Overview of Charts
Introduction
A chart is a technique of displaying data using pictures and graphical representations instead of numbers or simple words. It works by drawing figures that would represent numbers, giving a dramatic effect to the information presented. Good created and formatted charts can help people and businesses make decisions based on the impact that their images provide to the users. While data analysis as we have seen it so far was performed on a record displayed on sheets or forms, data analysis on charts is done using graphics that present pictures. In addition to the pictures, you can add words, also called labels to indicate what the pictures represent. Because a chart is used to present data in a graphical format, before creating a chart, you should plan it. That is, you should prepare it. There are two pieces of information you should have before starting: The numbers that you want to represent and the type of chart you want to use. If you have used Microsoft Excel to create charts, you are probably familiar with them and the effects available. While both Microsoft Excel and Microsoft Access base their charts on the same engine, Microsoft Access presents some limitations, especially with formatting or drawing. Therefore, while you should be able to analyze any data in Microsoft Access using charts, because of the way it is setup, you may not have all of the same options available as for Microsoft Excel.

Creating a Chart
The information used to create a chart is the one you would have stored in a table. In some other cases, you can use a query as queries do a good job at isolating records or counting them. Therefore, before creating a chart, you should prepare it so it can be easily recognizable. Data used on a chart can be made of natural numbers. In some other cases, you may want to use percentages. You can also present a series of repeating words and let the chart engine count the occurrences of such words before using them as numbers. Once the data is ready, to create a chart, display the New Form dialog box and in it, select the Chart Wizard. This would give you is selecting the information needed for analysis followed by the type of chart you want to use. There are different types of charts, ranging from columns to pies, from lines to surfaces, etc, as we will review them. To present its information more efficiently, a chart is made of different sections. The main area allows users to view the graphical display of data. A legend explains the meaning of various colors on the chart. A title indicates what the chart is used for.

Types of Charts
Column Charts
A column chart can render a very effective result when analyzing data of the same category on a defined scale. The column chart emphasizes high and low values. It helps to compare items. The classic column chart is made of flat bars that simply illustrate maximal, minimal, and in-between values. One of the options allows you to create a 3-dimensional look of the chart and further accentuate the colors and/or other graphic effects. To enhance an effective analysis, you can create a real 3-D chart that shows data and graphics in perspective. We are going to create a chart to shows us how often a particular container gets ordered. During data analysis, this type of chart can show management what type of container should

214

be supplied more often.

Practical Learning: Creating a Column Chart


1. From the resources that accompany this ebook, copy the Clarksville Ice Cream1 database and paste it in your Exercises folder 2. Start Microsoft Access and open the Clarksville Ice Cream1 database. If necessary, click Queries in the Database window 3. To create a new query, double-click Create Query In Design View. If you are using MS Access 97, in the Queries property page of the Database window, click the New button and, in the New Query dialog box, double-click Design View 4. In the Show Table dialog box, double-click CustomersOrders followed by Containers and click the Close button 5. In the Containers list, double-click Container

6. To view the result, switch the query to Datasheet View 7. Save the query as ContainerOrderFrequency and close it 8. On the main menu, click Insert -> Form 9. In the New Form dialog box, click Chart Wizard and, in the bottom combo box, select ContainerOrderFrequency

10. Click OK 11. In the first page of the Chart Wizard, in the Available Fields list, double-click Container to include it in the Fields For Chart list:

215

12. Click Next 13. In the second page of the Chart Wizard, click the chart in the 2nd column - 1st row 3-D Columnar Chart

14. Click Next 15. To take a glimpse at the chart, click the Preview Chart button

16. Click Close and click Next 17. Set the Title to Number of Containers Ordered and press Enter 18. Save the form as chtContainersOrdered

216

19. After viewing the chart, close the form

20. Print the chtContainersOrdered form

Bar Charts
Like the Column, the Bar chart is used to compare values of the same category on a common scale. This time, the chart is drawn horizontally. You create a Bar chart using the same process as the Column, except that you should select the Bar in the second page of the wizard. In the following chart, we will see the frequent number of scoops that customers order. In the following exercise, we are referring to an issue that has not been introduced previously. The reason is that we are going to ask you to use a function that cannot be explained at this time. The function we want you to use is called Choose(). We will explain it when we get to the functions and expressions. The problem is that, the chart we want to create is completely based on numbers from the Scoops column. If we just use the number, Microsoft Access "thinks" that we want to use a sum of the scoops and create a chart from it. Instead, we want to get a sum of scoops by categories. That is, we want to know the number of 1 scoop, or the number of 2 scoops, or the number of 3 scoops. Therefore, in our own defense, here is what we propose to you. Since the following exercise is for demonstration purposes, you can skip it and you will not loose anything. Otherwise, simply do the exercise and trust us as you have done so far.

Practical Learning: Creating a Bar Chart


1. To create a new query, on the main menu, click Insert -> Query and, in the New Query dialog box, double-click Design View 2. In the Show Table dialog box, double-click CustomersOrders and click Close 3. In the CustomersOrders list, double-click Scoops and press Tab. That will put the caret in the second column 4. In the second column, type NumberOfScoops: Choose([Scoops], "One", "Two", "Three") and press Enter 5. Save the query as TypesOfScoops

217

6. Switch the query to Datasheet View to preview it. Then close it 7. To create a new chart, on the main menu, click Insert -> Form 8. In the New Form dialog box, click Chart Wizard and, in the bottom combo box, select TypesOfScoops and click OK 9. In the first page of the Chart Wizard, in the Available Fields list, double-click NumberOfScoops to include it in the Fields For Chart list:

10. Click Next 11. In the second page of the Chart Wizard, click the chart in the 1st column - 2nd row Bar Chart

12. Click Next twice 13. Set the Title to Number of Scoops/Order and click Finish 14. Save the form as chtNumberOfScoopsPerOrder

218

15. After viewing the chart, print then close the form

Line Charts
A Line chart is used to analyze ups and downs of a tendency in a range of values. You can define it with one series of values where you will judge the evolution of an item over a period. When used with more than one series, this chart can be very helpful in comparing values of the same category over the same period. The Line chart can also be used to analyze values that don't share the same periodic variable. For example, you can use it to compare library attendance with regard to the real population number (which could be in hundreds of thousands or millions) with the number of people attending the library. In the latter situation, if the same axes are used to analyze, one category will almost disappear from the chart. The alternative is to separate their axis on the same chart. In the following chart, we are picking a sample week of the year. We then isolate the names of weekdays to evaluate the tendency of customers orders. What we want to know is what days produce more orders and what days are slow. This type of information can help the management decide what days they need more cashiers because there are more customers. On the slow days of the week, the business doesn't need many employees, at least not too many cashiers serving customers. To prepare data to be used, we will create a query that uses the dates orders are placed. Fortunately, we also have a column that evaluates weekdays. This second column will be the actual source of data for the chart. The first column allows us to specify the criteria, which consists of considering only one week as our sample.

Practical Learning: Creating a Line Chart


1. To create a new query, on the main menu, click Insert -> Query and, in the New Query dialog box, double-click Design View 2. In the Show Table dialog box, double-click CustomersOrders and click Close 3. In the CustomersOrders list, double-click OrderDate 4. In the Criteria field for the new column, type >=#01/06/2002# And <=#01/12/2002# and press Enter 5. In the CustomersOrders list, double-click DayOfWeek to put it in the second column 6. Save the query as SecondWeekOfJanuary2002

7. Switch the query to Datasheet View to preview it. Then close it 8. To create a new chart, on the main menu, click Insert -> Form

219

9. In the New Form dialog box, click Chart Wizard and, in the bottom combo box, select

SecondWeekOfJanuary2002 and click OK 10. In the first page of the Chart Wizard, in the Available Fields list, double-click DayOfWeek to include it in the Fields For Chart list and click Next 11. In the second page of the Chart Wizard, click the chart in the 3rd column - 3rd row Line Chart

12. Click Next twice 13. Set the Title to Daily Orders in a Sample Week and click Finish 14. Save the form as chtSampleDailyOrders

15. After viewing the chart, close the form

16. Print the chtSampleDailyOrders form

Pie Charts
A Pie chart is used to show percentage and/or fraction values. You should choose it whenever your analysis involves values that altogether evaluate to a 100%, a 1, a 10, a 100, or a 1000 scale. To prepare data for a Pie chart, you can select values as you would any other chart. When asked to create the chart, the chart engine would perform the necessary evaluation. It would calculate the sum of all values, then find out what proportion or fraction each category claims in the total.

Practical Learning: Creating a Pie Chart


1. In the Database window, click Queries if necessary. To create a new query, double-click Create Query In Design View. If you are using MS Access 97, in the Queries property page of the Database window, click the New button and, in the New Query dialog box, double-click Design View 2. In the Show Table dialog box, double-click CustomersOrders followed by Flavors and click the Close button 3. In the Flavors list, double-click Flavor

220

4. To view the result, switch the query to Datasheet View 5. Save the query as FlavorOrderFrequencies and close it 6. On the main menu, click Insert -> Form 7. In the New Form dialog box, click Chart Wizard and, in the bottom combo box, select FlavorOrderFrequencies, and click OK 8. In the first page of the Chart Wizard, as the Flavor item is already selected in the Available Fields list, click the select one button to add Flavor to the Fields For Chart list and click Next 9. In the second page of the Chart Wizard, click the chart in the 1st column - 4th row Pie Chart

10. Click Next 11. To take a glimpse at the chart, click the Preview Chart button

12. Click Close and click Next 13. Set the Title to Frequency At Which A Flavor Is Ordered and press Enter 14. After viewing the chart, save the form as chtFlavorFrequency and close it

Doughnut Charts
A Doughnut chart is an alternative to the Pie chart as both use the same types of values. The main difference between both types of charts is that a Doughnut chart can include more than one series of data.

Practical Learning: Create a Column Chart


1. To create a new query, on the main menu, click Insert -> Query and, in the New Query dialog box, double-click Design View 2. In the Show Table dialog box, double-click Ingredients followed by CustomersOrders and click Close 3. In the Ingredients list, double-click Ingredient 4. Run the query to preview it 5. Save the query as ChoiceOfIngredient then close it 6. To create a new chart, on the main menu, click Insert -> Form

221

7. In the New Form dialog box, click Chart Wizard and, in the bottom combo box, select
ChoiceOfIngredient and click OK

8. In the first page of the Chart Wizard, click the select one button

to add the Ingredient item to the Fields For Chart list and click Next 9. In the second page of the Chart Wizard, click the chart in the last column - last row Doughnut Chart 10. Click Next twice 11. Set the Title to Customers Choice of Ingredient and click Finish 12. Save the form as chtChoiceOfIngredient

13. Print the chtChoiceOfIngredient form


14. After viewing the chart, close the form

The Cylinder, Cone, and Pyramid Charts


The Cone, Cylinder, and Pyramid charts can be used in the same scenario as the column and bar charts. Their 3-D visual effect can enhance the overall analysis of data. The Cylinder chart creates long circular boxes of the same base on both ends. It can be enhanced with good formatted Fill Effects. This chart is suitable for industry, manufacturing analysis, and predictions. The cone is made of a circular base topped by a higher point. When used with various data, the higher values will have the complete cone while the lower values will share portion of the geometric figure. The cone chart should be used with values that can take advantage of its graphing dimensions. The Pyramid chart resembles the cone chart with a difference on their respective base. Both are constructed the same and can be used in similar scenarios. When analyzing data for geographical purposes, the Pyramid chart can render very dramatic effects.

Practical Learning: Creating a Pyramid Chart


1. To create a new query, on the main menu, click Insert -> Query and, in the New Query dialog box, double-click Design View 2. In the Show Table dialog box, double-click CustomersOrders and click Close 3. In the CustomersOrders list, double-click DayOfWeek 4. Run the query to preview it 5. Save the query as DailyCustomerAffluence and close it 6. To create a new chart, on the main menu, click Insert -> Form 7. In the New Form dialog box, click Chart Wizard and, in the bottom combo box, select DailyCustomerAffluence and click OK

222

8. In the first page of the Chart Wizard, click the select one button

to add the DayOfWeek item to the Fields For Chart list and click Next 9. In the second page of the Chart Wizard, click the chart in the last column - 1st row Pyramid Column Chart 10. Click Next twice 11. Set the Title to Daily Customer Affluence and click Finish 12. Save the form as chtDailyAffluence and print it 13. After viewing the chart, close its form

Multi-Series Charts
In some cases you may want to analyze two or more series of data, either concurrently or as they relate to each other. For example, in our ice cream application, you may want to know how often customers who order the Butter Pecan flavor are likely to add an ingredient to their order (since butter pecan already has some nuts in it). Also, if another analysis reveals that Vanilla is most often ordered, is it related to a particular time of the day? To analyze data from two series, when preparing it, make sure you create a way for the chart engine to figure out how to reconcile the numbers. Also, not all charts are made for multiple series.

Practical Learning: Creating a Multi-Series Chart


1. To create a new query, on the main menu, click Insert -> Query and, in the New Query dialog box, double-click Design View 2. In the Show Table dialog box, double-click CustomersOrders followed by Containers and click the Close button 3. In the CustomersOrders list, double-click PeriodOfDay 4. In the Containers list, double-click Container 5. To view the result, switch the query to Datasheet View 6. Save the query as ContainerByPeriodOfDay and close it 7. On the main menu, click Insert -> Form 8. In the New Form dialog box, click Chart Wizard and, in the bottom combo box, select ContainerByPeriodOfDay, and click OK

9. In the first page of the Chart Wizard, click the select all button

to add both fields to the Fields For Chart list and click Next 10. In the second page of the Chart Wizard, click the chart in the 2nd column - 1st row Pie Chart

11. Click Next twice 12. Set the Title to Container by Period of Day and press Enter 13. After viewing the chart, save the form as chtContainerByPeriodOfDay 14. Print the form and close it

Formatting Charts
Introduction to Chart Formatting
A Chart as Part of a Form
223

A chart created using the New Form dialog box is positioned on a form. As such, the form acts as its parent. The chart can only fit inside of the form. Based on this, you can enlarge a form to make available more space for the chart. After enlarging and/or heightening a form, you can increase the side of the chart to have a bigger picture and better appreciate a chart.

Practical Learning: Resizing a Chart


1. Open the Clarksville Ice Cream you were working on the previous lesson
2. In the Database window, click Forms and double-click the chtFlavorFrequency form to open it 3. After viewing the chart, switch the form to Design View 4. Right-click the chart, position the mouse on Chart Object and click Edit. This opens the Microsoft Graph window 5. Using the lower-right corner of the the Microsoft Graph window, resize it as much as you can afford 6. Using the lower-right corner of the form, increase the size of the chtFlavorFrequency window as much as possible

7. After enlarging the chtFlavorFrequency window, click somewhere close to the circle until a surrounding square appears

8. Click that square and drag left to move the chart to the left

224

9. In the same way, click the box that displays the title above the chart and drag it left to place it above the chart 10. Also, click the box that displays East West North and drag it left to place it close to the chart 11. After resizing, close the Microsoft Graph window

12. Back in Microsoft Access, resize the box that surrounds the chart until the chart and the
words around it are visible. You may need to continue various trial-and-error attempts until you come to the following

13. Save and close the form

Change of Chart Type

225

A chart created with all defaults settings usually accomplishes its purpose of helping you analyze data and figures, but the default features are set only as starting points. All the formatting and emphasis needs are left to you. Besides the values and numbers on it, a chart is a graphic object whose characteristics can be enhanced to accentuate special important points of the whole process. Most aspects of a chart can be changed. For example, if you selected a certain type of chart but think that another is more suitable, you can change it. The Chart Wizard is equipped with various kinds of charts. In each category, different sub-types are used to accomplish a unique purpose. Although they share a lot of characteristics, some charts in the sub-type can tremendously change or alter the intended goal. You should know what options are available, and then act accordingly. Many charts can be changed from one kind to another, sometimes completely different. For example, you can change a chart from a flat column to 3-D. You can also change a chart from a bar to a cylinder, etc. To actually change a chart, after displaying its parent form in Design View, you can double-click it. This would open the Microsoft Graph application. From there, you can right-click any part of the chart to make the necessary changes. Any area you right-click presents a particular menu. This is because a chart is made of various sections. To change the type of chart, you can right-click a white area on the Form - Chart window and click Chart Type. This would bring up the Chart Type dialog box. It presents the various available types of charts and you can click one of them. If none of the available types suits you, you can click the Custom Type tab for more options.

Practical Learning: Changing a Chart Type


1. Open the chtDailyAffluence form in Form View and switch it to Design View 2. Right-click on a white area on the chart and click Chart Type 3. In the Chart Type dialog box, make sure the Standard Types property page is displaying In the Chart Type list box, click Cylinder In the Chart Sub-Type section, make sure the Chart With A Cylindrical Shape is selected

4. Click OK

226

5. As done for the the chtFlavorFrequency chart, resize the chart window

6. Close the Microsoft Graph window to return to Microsoft Access 7. Once again, resize the form and the chart to occupy as much space as possible

8. Save and close the form

The Sections of a Chart


Introduction
As mentioned already, to present its information and explain it, a chart is made or various sections.

Most or everyone of these aspects can be hidden, displayed or changed. To perform any action on these parts, after displaying the form or report that holds the chart in Design View, you can doubleclick the chart. Then, in Microsoft Graph, click or right-click the desired part.

The Title of a Chart


227

To indicate what it is used for, a chart can be equipped with a title. The title is a string that typically displays in the top section of a chart. In some rare cases, a title can also be positioned under the chart. To move the title, click and drag it in the desired direction. To format the title, you can either double-click it or right-click it and click Format Chart Title. By default, the chart displays without a border, in bold Arial. You change reformat it using the Format Chart Title dialog box.

Practical Learning: Formatting a Chart's Title


1. From the Forms section of the Database window, double-click the
chtContainerByPeriodOfDay form and switch it to Design View 2. Double-click the chart to open the Microsoft Graph window and enlarge the window that contains the chart 3. Right-click the Container by Period of Day title and click Format Chart Title... 4. In the Format Chart Title dialog box, click the Font property page 5. In the Font combo box, select Times New Roman 6. In the Size combo box, select 18 7. Click arrow of the Color combo box and select Blue

8. Click OK 9. Close the Microsoft Graph window 10. Adjust the chart to fit the form

11. Save and close the form 12. Right-click the chtFlavorFrequency form and click Design View 13. Double-click the chart to open Microsoft Graph 14. Click the title on top twice (that is, click it and click it again; not double-click) to put it into edit mode 15. Edit it to display PercentageOrdered 16. Click between Percentage and Ordered then press Enter to create a new line

228

17. Click somewhere else to deselect

18. Move the title to the top left section and double-click it. Change its font to Haettenschweiler,
Bold, 14, Red and click OK

Chart Figures
To represent its numbers to the user, a chart draws some geometric figures, depending on the type of chart. These figures can be rectangles, pie slices, triangles, cones, etc. By default, the chart engine uses some randomly selected colors from its own list. You can either change these colors or apply some preset drawings available. You can also design and use any custom picture to paint the chart's shapes. To format the geometric figures of a chart, you can right-click one of them and click Format Data Series.

Practical Learning: Formatting a Chart's Shapes


1. Open the chtDailyAffluence form and switch it to Design View 2. Double-click the chart to open the Microsoft Graph window 3. Right-click the most left cylinder and click Format Data Series 4. In the Format Series dialog box, make sure the Patterns property page is selected. In the Border section, make sure the Custom radio button is selected. click the arrow of the Color combo box and click Blue (5th column - 1st row) 5. Click the arrow of the Weight combo box and click the 2nd option 6. In the Area section, click the Pale Blue color (1st section - 6th column - 5th row)

7. Click OK 8. Close Microsoft Graph 9. Preview the chart 10. Save and close the form 11. Open the chtContainerByPeriodOfDay form and switch it to Design View 12. Double-click the chart to Open Microsoft Graph 13. Right-click the most left rectangular box and click Format Data Series 14. In the Format Data Series dialog box, make sure the Patterns property page is selected. In the Area section, click Fill Effects... 15. In the Gradient property page of the Fill Effects dialog box, in the Colors section, click the One Color radio button 16. In the Color 1 section, drag to thumb of the slider to the right 17. In the Shading section, click the Vertical radio button 18. In the Variants section, click the box on 1st column - 2nd row

229

19. Click OK 20. Save the form and preview the chart 21. Print the form 22. Close the form

A Chart's Legend
When a chart draws its graphics, if the data is made of different types of values, the chart engine uses a different column for each type of value to differentiate them. Because this can become confusing, a small box is created as a guide. This box, by default displayed to the right of the chart, is called a legend. In the legend, a small painted square displays a color and a label on its right. The color is one of the colors used on the graphics of the chart. The label indicates what that part represents

Practical Learning: Using a Chart's Legend


1. Right-click the chtDailyAffluence form and click Design View 2. Double-click the chart to open Microsoft Graph 3. Click the box that has 1st Qtr and press Delete

4. Close Microsoft Graph and preview the chart

5. Print then close the form 6. Right-click the chtFlavorFrequency form and click Design View 7. Double-click the chart to open Microsoft Graph

230

8. Click the box that displays East West North and press Delete 9. Right-click the chart and click Format Data Series 10. In the Format Data Series dialog box, click the Data Labels property page 11. In the Data Labels section, click the Show Label And Percent radio button 12. Click OK and position the chart to the center of the window 13. Close Microsoft Graph 14. Adjust the chart to your liking and preview it

15. Save and print the form 16. Close the form

Chart's Labels
By default, when a chart is drawn, it is equipped with shapes and a separate legend. If you want, you can display the value of each part and possibly its name close to it. This is done through a label. On a large chart, a label can also be used in the absence of a legend. In fact, you can delete a legend and simply make use of a label. Labels are created using the same approach as we have done with the legends and titles.

Practical Learning: Adding Labels to a Chart


1. Right-click the chtFlavorFrequency form and click Design View 2. Double-click the chart to open Microsoft Graph 3. Click the box that displays East West North and press Delete 4. Right-click the chart and click Format Data Series 5. In the Format Data Series dialog box, click the Data Labels property page 6. In the Data Labels section, click the Show Label And Percent radio button 7. Click OK and position the chart to the center of the window 8. Close Microsoft Graph 9. Adjust the chart to your liking and preview it

231

10. Save and print the form then close it

Chart's Walls
The wall is in fact the background of a chart. By default, it is painted either white or gray, depending on the chart. You can use a different color to paint it, a design pattern or a picture to cover it.

Practical Learning: Formatting a Chart's Walls


1. Right-click the chtContainerByPeriodOfDay form and click Design View 2. Double-click the chart to open Microsoft Graph 3. In the chart, right-click the gray area and click Format Walls... 4. In the Format Walls dialog box, in the Area section, click Fill Effects 5. In the Fill Effects dialog box, click the Pattern property page 6. In the Pattern section, click the box in 6th column - 4th row 7. Set the Foreground to Gray-25% (8th column - 4th row) 8. Set the Background to Dark Red (1st column - 2nd row)

9. Click OK twice

232

10. Save and print then close the form 11. Right-click the chtDailyAffluence form and click Design View 12. Double-click the chart to open Microsoft Graph 13. Right-click the gray area and click Format Walls... 14. Click Fill Effects and click the Texture property page 15. In the Texture section, click the box in the 4th column - 1st row and click OK twice 16. Right-click the bottom gray area and click Format Floor... 17. Click Fill Effects... and click Texture 18. Click the box in 2nd column - 2nd row and click OK twice

19. Close Microsoft Graph and preview the chart

20. Save the form 21. Print and close the form

Action Queries

233

Introduction to Action Queries


We have used the concept of a query so far only to create a list of fields that would be considered for a set of records. We also mentioned that a query in Microsoft Access is simply a means of visually representing data. Indeed, a query is based on a SQL statement. As SQL is its own, fully functional language, we can use it to perform far more operations than to only select columns for a query. The SQL can be used to create tables, modify tables, perform data entry, modify records, etc. Some of these operations can be performed visually in the query Design View. They can also be performed using SQL statements. To know what is going on behind the scenes, you can write your own code (SQL statement). You can also use the Design View to start a query, and then open the code to customize the statement. You will hardly perform some of the operations we will review here, but you should know that they are available. It is very important to know that, when using an action query to perform a specific action such as creating a table, you are not creating a regular query in the strict sense. Most of these queries are usually useful only once. For this reason, you will hardly need to save them, as the action may be needed only once. If you perform the action of the query, you do not need to save it but once you apply its intended action, the related action is executed and stays with the database even if either you do not save the query or save it but later on delete the query. In practicality, this is also how queries are used in many other environments. For example, in Microsoft SQL Server, the statement that makes up a query is created as its own file, also called a view, then it can be called any time.

Practical Learning: Introducing Action Queries


1. To create a new database, on the Taskbar, click Start -> (All) Programs -> New Office Program

2. In the New Office Document dialog box, click the General property page and click
Blank Database

3. Click OK 4. Locate your Exercises folder and display it in the Save In combo box

5. Change the File Name to Clarksville Ice Cream2 and click Create

Queries and Table Creation


Creating a database is usually the first action you perform in order to have one. Of course, you can also open an existing database. Creating a Microsoft Access database is done visually as you must create its file without using SQL code, contrary to many other database environments. The second action to take is probably to create a table. Using queries, there are two main techniques you can use to create a new table for your database. Microsoft Access provides a technique called Make-Table Query. This type of query is used to retrieve all or some fields of an existing table and, instead of creating a new query that depends on an existing table, you would get a brand new table, independent of any existing table. This type of action can let you create a new table based on a rule applied on an existing

234

table. For example, suppose the Cars table of your car rental database contains cars that should not be rented to customers anymore, perhaps because of their age. You can create a query that would make a list of cars that follow a rule, apply it, and then create a new table made of only such cars. To create a table using a Microsoft Access query, start a new query in Design View. Then, on the main menu, you can click Query -> Make Table Query, this would present you with a Make Table dialog box that allows you to specify a new name for the query or to select an existing table that would receive the new data.

Practical Learning: Using Make-Table Queries


1. Open the Bethesda Car Rental1 database 2. On the Database window, click the Tables button and click the Cars table to select it 3. On the main menu, click Insert -> Query and, in the New Query dialog box, double-click Design View

4. On the Query Design toolbar, click the arrow of the Query Type button and click MakeTable Query

5. In the Table Name combo box, type CarsToConsiderRetiring as the name of the table

6. Make sure the Current Database radio button is selected and click OK

7. In the Cars list, double-click TagNumber, Make, Model, CarYear, and Picture 8. To set the criterion for an old car, click the Criteria field of the Year column
Type < 2000 This means that the list applies to any car made before 2000

235

9. To preview the list of cars that will be considered, on the main menu, click View Datasheet View 10. Switch back to Design View

11. To execute the action, on the Query Design toolbar, click the Run button
You will receive an acknowledgement message box

12. Read it and click Yes 13. Close the query window. When asked whether you want to save it, click Yes

14. Type Create A List Of Retiring Cars as the name of the query and press Enter

SQL and Table Creation


As a computer language, the SQL is equipped to perform all basic and necessary operations of a database. As such, it can be used to create a table. Although you will usually use the visual means of Microsoft Access, you can still use a SQL statement to create a table. To create a table, you start your statement with the CREATE TABLE expression followed by the desired name of the table as follows: CREATE TABLE TableName As you have probably realized by now, every table must have at least one column. The list of columns of a table starts with an opening parenthesis ( and ends with a closing parenthesis with an optional semi-colon );. If the table will be made of more than one column, you can separate them with a comma. The syntax used would be:

CREATE TABLE TableName (Column1, Column2, Column_n); To make the statement easier to read, and because some columns can be long, you can create each on its own line. The syntax would become: CREATE TABLE TableName ( Column1,

236

Column2, Column_n ) To create a column, you specify its name, followed by its data type, and some possible options. Therefore, the syntax of creating a (one) column is: ColumnName DataType Options Notice that there is only space that separates the sections of the syntax. For this reason, the name of a column should be in one word because, if you put space after the first word, the SQL engine would treat the next word as a data type. For example, the following statement would produce an error: CREATE TABLE Test ( Marital Status ) If you want to use space in a column name, include the name between an opening square bracket [ and a closing square bracket ]. The above statement would be changed to: CREATE TABLE Test ( [Marital Status] ) After (or on the right side of) the column name, you must specify the type of information, also called the data type, that will be stored in the cells under that column. Here are the SQL data types supported in Microsoft Access: Data Type Description

The char or the text data types can be used for columns whose fields would receive (or present) text. The field must not contain more than Char or Text 255 characters This is the same as Microsoft Access Text data type Varchar Memo This is one of the most regularly used data types of a SQL column. It can used for strings (text) of any kind The same as Microsoft Access Memo, its field can hold up to 65656 characters (many SQL environments don't support the Memo data type) This is used for a Boolean or logical field that accept only a True or False, a Yes or No, an On or Off, or a 0 or 1 as a value This is equivalent to Microsoft Access' Yes/No The smallint data type can be used for a field that would hold numbers that can range from 32,768 to 32767 This is used for fields that would hold small to very large natural numbers Real is a relatively small data type in the world of double-precision representation but can be used on a column whose fields would hold decimal numbers that can range from 3.402823E 38 to 1.401298E -45 for negative values or from 1.401298E -45 to 3.402823E 38 for positive values. This data type is close to Microsoft Access Single The float data type can be used on a column whose fields would hold numbers with a decimal portion, like Microsoft Access Single. Like the Single data type, the float is mainly used on a column where number precision is not a significant issue. For example, you should not use it on a column that hold monetary values The numeric data type can be used on a column whose fields would

Bit Smallint

Int or Integer Each of these data types can be used to represent a natural number Long

Real

Float

Numeric

237

hold numbers with a decimal portion. It is close to the Microsoft Access Double data type and can be used when numeric precision is needed Double Money and Currency Datetime This is the same as Microsoft Access Double data type This data type is appropriate for fields that would hold numbers that represent monetary values Equivalent to Microsoft Access Date/Time data type, the DATETIME data type can be applied to a column whose fields would display either date, time or both date and time values The binary data type can let a field accept any type of data but it is equipped to interpret the value. For example, it can be used to receive hexadecimal numbers This can be used for fields that would hold OLE Object equivalents

Binary Image

Here is an example that creates a table named Persons CREATE TABLE Persons ( FirstName VARCHAR, [Last Name] Text, Gender int, [Date Of Birth] DateTime, MaritalStatus Integer, IsMarried Bit, PersonalIncome Money, HouseholdIncome Currency );

When studying techniques of creating fields in a tables Design View, we saw that a property called Field Size can be used to specify the size of value used on a field. In the SQL also, this property is fixed for most fields expect those that are text-based. Therefore, when creating a field whose data type is char, text or varchar, you can specify the desired number of characters that the field should allow. If you are creating a char or a varchar column, you should (strongly) specify the number of characters instead of letting Microsoft Access assign the default. The text usually doesn't use a number of characters. To specify the maximum number of characters of a text-based field, include it in parentheses to the left of the data type. There are many other properties that can be applied to a column, as we have learned in the past. For example, you may want a column of a table to be used as the primary key. To provide this piece of information, on the right side of the column, before its comma, type primary key. By default, except for a column set as primary key, the user is not required to provide a value for each field when performing data entry. This is because, by default, each field is set to NULL. This is equivalent to setting the Required property of a field to No (which is the default) in a tables Design View. As this property is to No in the Design View, you can also

238

specify it by typing null on the right side of any column you want. Here are examples: CREATE TABLE Persons ( PeronID long Primary Key, FirstName VARCHAR NULL, [Last Name] Text, Gender int NULL, [Date Of Birth] DateTime, MaritalStatus Integer, IsMarried Bit NULL, PersonalIncome Money, HouseholdIncome Currency ); If you don't specify the NULL attribute, the nullity is implied. On the other hand, if you want to require the values of a field so the user cannot move to the next record unless the field is filled, type not null to its right. This would indicate to Microsoft Access that the field does not allow a null value. During data entry, the user is allowed to type the same value in the same fields of two different records. For example, it is not unusual for two people to have the same last name. In some other cases, you may want each record to have a different value for a particular field. For example, a company may not allow two employees to have the same employee number or the same social security (US) numbers, just like two cars should not have the same tag number in the same state. To communicate this, on the right side, type the unique key word. If you are creating a table that will participate in a relationship, when creating the field used as its primary key, on the right side of that field, type the constraint keyword followed by a name for primary key. This clause should be entered before primary key. Here is an example: CREATE TABLE Genders ( GenderID int CONSTRAINT PKGender Primary Key, Gender char(20) ); To establish a relationship from this table when creating another table, in that other table, create a field. By tradition, this would have the same name as we have mentioned already but this is not a requirement. The requirement is that both fields (the new field and the field it refers to in the parent table) must have the same data type. When creating the relationship, after specifying the name of the field and its data type, type the references keyword followed by the name of the table it is linked to and its primary key as argument. For example, to create a Persons table that is related to the above Genders table, you would type: CREATE TABLE Persons ( PeronID long Primary Key, FirstName VARCHAR NULL, LastName Text Not Null, GenderID int REFERENCES Genders(GenderID), Notes char );

Practical Learning: Creating Tables With SQL


1. Open the Clarksville Ice Cream2 database that you started earlier 2. On the Database window, click Queries and click the New button 3. In the New Query dialog box, double-click Design View and, on the Show Table dialog box, click Close

4. On the Query Design toolbar, click the View button


5. Change the statement in the Query1 window as follows:

239

CREATE TABLE Ingredients ( IngredientID LONG CONSTRAINT IngredientID PRIMARY KEY, Ingredient TEXT(50) );

6. To save the query, on the Query Design toolbar, click the Save button 7. Type Create Table as the name of the query and press Enter

8. To execute the query, on the Query Design toolbar, click the Run button 9. To create another table, in the Create Table window, change the statement as follows: CREATE TABLE Flavors ( FlavorID Long Constraint FlavorID Primary Key, Flavor VarChar(50) ); 10. To execute the query, on the main menu, click the Query -> Run 11. To create another table, in the Create Table window, change the statement as follows: CREATE TABLE Containers ( ContainerID int constraint ContainerID primary key, Container char(50), Description text ) 12. To formally create the table, execute the query 13. To create another table, in the Create Table window, change the statement as follows: CREATE TABLE Scoops ( ScoopID Integer Constraint ScoopID primary key, Scoop Text(10) ) 14. To formally create the table, execute the query 15. To create another table, change the SQL statement as follows: CREATE TABLE Employees ( EmployeeID Long Constraint EmployeeID Primary Key, DateHired DateTime, FirstName char(20) Null, LastName text(20) Not Null, Title VarChar(100) Null, ContactPhone text(16), HourlySalary Money, Notes char )

240

16. Create the table by executing the query 17. To create another table, change the SQL statement as follows: CREATE TABLE OrderProcessing ( OrderID Long Primary Key, EmployeeID Long REFERENCES Employees(EmployeeID), OrderDate DateTime, OrderTime DateTime, ContainerID Long references Containers(ContainerID), FlavorID Long references Flavors(FlavorID) Not Null, IngredientID Long References Ingredients(IngredientID) Null, ScoopID long References Scoops(ScoopID) Not Null, Notes Text ) 18. Execute the statement to actually create the table 19. Close the window. When asked whether you want to save it, click Yes 20. On the Database window, click the Tables button to see the list of tables

21. On the main menu, click Tools -> Relationships to see the already created diagram

22. If you are using Microsoft Access 2000 and later, on the main menu, click File -> Print Relationships 23. Save the relationship as Ice Cream Structure 24. Close the Relationships window

SQL and Data Entry


When using the Make-Table Query of Microsoft Access, you actually perform two actions at once. First you create a table, which is the primary requirement of the Make-Table Query, then, when you execute the query, you fill the new tables fields with the existing values of the originating table. The SQL allows you to actually perform data entry on a table. In the languages standard, you can create a table and fill it with values. Alternatively, you can add various new records to the fields of an existing table. This is also referred to as inserting records. In the SQL, data entry is performed using the INSERT INTO expression, followed by the table name, followed by the VALUES keyword, and followed by the values in parentheses. If the table is made of only one column, you can include the desired value in the parentheses. If the table is made of more than one column, you must separate the values with commas. The syntax to use is: INSERT INTO TableName VALUES(Column1, Column2, Column_n) The TableName attribute must be the name of an existing table of the current database. If the name is wrong, that is, if the name is not found in the database, the SQL engine would consider that the table you are referring to does not exist. Consequently, you would receive an

241

error. The VALUES keyword indicates that you are ready to list the values of each field of the record. The values of the columns must be included in parentheses. In the above syntax, the value of each field of the column must be entered in the exact order of the columns as they were created in the table. Fortunately, the SQL allows you to perform data entry in the order of your choice. To do this, when creating the statement, after specifying the name of the table, open the parentheses and type the order of the columns in the order of your choice but make sure you type valid names of existing columns. Then, in the parentheses of the VALUES attribute, type the values in the order specified in the parentheses of the table name. This random order of fields presents another advantage: it allows you to select only the fields whose values you want to enter. If the column is a BIT data type, you must specify one of its values as 0, 1 (or 1), True, False, On, Off, Yes, or No. If the column is a numeric type, you should pay attention to the number you type. If the column was configured to receive an integer (Int, Smallint, Integer, or Long), you should provide a valid natural number without the decimal separator. If the column is for a decimal number (real, float, single, double, or numeric), you can type the value with its character separator (the period for US English). If the column was created for a date data type, make sure you provide a valid date or a valid time value. If the data type of a column is a string type, you can include its value between either single or double quotes. For example, a shelf number can be specified as 'HHR-604' and a middle initial can be given as 'D'.

Practical Learning: Performing Data Entry


1. Continuing with the Clarksville Ice Cream2 database, on the Database window, click Queries 2. On the main menu, click Insert -> Query and, in the New Query dialog box, double-click Design View 3. On the Show Table dialog box, click Close. Then, on the Query Design toolbar, click the View button 4. Change the SQL statement as follows: INSERT INTO Ingredients VALUES(1, "None") 5. To save the query, on the Query Design toolbar, click the Save button

6. Type Data Entry as the name of the query and press Enter

7. To execute the query, on the Query Design toolbar, click the Run button
You will receive a message box

242

8. Read it and click Yes 9. To add another record, change the statement as follows: INSERT INTO Ingredients VALUES(2, 'Cookies') 10. Execute the statement and click Yes 11. To use the same query and add a record to another table, change the statement as follows: INSERT INTO Flavors VALUES(1, 'Vanilla') 12. Execute the statement 13. Add another record by changing the statement as follows: INSERT INTO Flavors VALUES(2, "Cream of Cocoa") 14. Execute the statement 15. To add a record to the Scoops table, change the statement as follows: INSERT INTO Scoops VALUES(1, "One") 16. Execute the statement 17. Change the statement as follows to add one more record to the Scoops table: INSERT INTO Scoops VALUES(2, "Two") 18. Execute the statement 19. To a record to the Containers table, change the statement as follows: INSERT INTO Containers VALUES(1, 'Cone', 'We present various types of cones, including chocolate-based') 20. To another record to the Containers table, change the statement as follows: INSERT INTO Containers VALUES(2, "Cup", "A cup is a plastic utensil, similar to a glass used in homes. Unlike a cone, it can be reused.") 21. To add a record to the Employees table, change the statement as follows: INSERT INTO Employees VALUES(1,6/8/2000, "Allison", "Deans", "Crew Manager", "(301) 821-4990", 8.35, "") 22. To enter a customer record in the OrderProcessing table, change the statement as follows: INSERT INTO OrderProcessing VALUES(1, 1, 8/12/2000, "10:06", 2, 1, 1, 2, "")

243

23. To add another in the OrderProcessing table, change the statement as follows: INSERT INTO OrderProcessing VALUES(2, 1, 8/12/2000, "10:22", 1, 2, 2,1, "") 24. To enter a record in the Containers table with the order of our choice, change the statement as follows: INSERT INTO Containers(Description, ContainerID, Container) VALUES("A bowl is larger. Unlike the other two containers, a bowl can contain more than 2 scoops. We offer bowls or collectible items.", 3, "Bowl") 25. To perform random data entry in the Employees table, change the statement as follows: INSERT INTO Employees( ContactPhone, LastName, EmployeeID, HourlySalary) VALUES( "(202) 622-8674", "Nguyen", 2, 6.25) 26. Close the query. When asked whether you want to save it, click OK

Queries and Record Appending


When working in a sensitive database, if you were the one in charge of data entry, you may prefer to use a temporary table to create records to make sure they are validated before actually adding them to the system. If you had created a significant number of these records and need to add them to the main table, the work can become overwhelming. Fortunately, Microsoft Access allows you to create a special query that can be used to add many records to a table in one step. An Append Query allows you to add records to an existing table but you do not create the records. They must be retrieved from one table and transferred to another table. In our Bethesda Car Rental1 database, imagine the company had acquired many cars at once but they were created in their own temporary table waiting to receive final approval after inspection. Now that this has been done, you can add them to the list of cars that is made available to the clerks who process order entry.

Practical Learning: Appending Records


1. The Bethesda Car Rental1 database should still opened. In the Database window, click Tables and double-click the Cars table to open it 2. Notice the number of cars in the current table. After viewing the table, close it 3. In the Database window, double-click the NewCars table to open it 4. After viewing the table, close it 5. In the Database window, make sure the NewCars table is selected. On the main menu, click Insert -> Query and double-click Design View in the New Query dialog box

6. Right-click the title bar of the Query1 window. Position the mouse on Query Type and click
Append Query

244

7. In the Append dialog box, click the arrow of the Table Name combo box, and select Cars

8. Click OK 9. In the NewCars list, double-click the asterisk field because we will involve all fields 10. To save the query, on the Query Design toolbar, click the Save button

11. Type Add New Cars To The System as the name of the query and press Enter 12. To see the SQL statement, right-click the title bar of the Query1 window and click SQL
View

13. To execute the query, on the Query Design toolbar, click Run
You will receive a message box:

14. Read it and click Yes 15. Close the query window

245

16. From the Database window, open the Cars table to verify that the number of cars has increased

Queries and Records Updating


If you have a large database and all of a sudden, there are many records that need to receive a common change, you may face an arduous task. For example, you may have to check every record and make the change where needed. Fortunately, to apply this type of impact to a set of records, you can create a special query. The Update Query allows you to change the existing values of one or more columns of a table. In other words, you can retrieve the values that are already in the fields of a table, change these values and have the table saved with them.

Practical Learning: Updating Records


1. The Bethesda Car Rental1 database should still be opened. In the Database window, double-click the Cars table to open it 2. Scroll down and notice that the new recently added cars have their Available field set to No, False, or Off 3. Close the table. Since we have recently added new cars, we will set their Available attribute to True so the clerks would know that these cars can be rented now to the customers 4. Make sure the Cars table is selected in the Tables section of the Database window On the main menu, click Insert -> Query and double-click Design View in the New Query dialog box 5. Right-click an empty area of the Query1 window. Position the mouse on Query Type and click Update Query

6. In the Cars list, double-click Available 7. In the Update To box of the Available column, type [Available]=0 and press the down
arrow key

8. In the Criteria box of the Available column, type [CarYear]>=2004

This query is saying that, If you find any car whose year is 2004 or up, set its Available property to true

9. To save the query, on the Query Design toolbar, click the Save button 10. Type Control The Availability Of Cars as the name of the query and click OK

11. To view the SQL statement, on the main menu, click View -> SQL View

246

12. To execute the query, on the main menu, click Query -> Run 13. You will receive a message box. Read it and click Yes 14. Close the query window 15. Open the Cars table and notice that the new cars have their Available field set to True, Yes, or On 16. Close the table

Queries and Table Deletion


Microsoft Access provides various techniques to delete tables. In the next lesson, we will see how this can be done in the Database window. Meanwhile, the SQL provides its own mechanism to delete a table. This is easily done using the DROP command. The syntax is: DROP TABLE TableName; The DROP TABLE command is used only to delete tables (and indexes), not forms or reports. The TableName parameter must be a valid name of a table of the current database. There are two big issues with the DROP TABLE command: it does not warn you and it is not reversible.

Practical Learning: Deleting Database Tables


1. Open the Bethesda Car Rental1 database 2. On the Database window, click Tables and open the ForTheCustomers table to view. After viewing the table, close it 3. On the Database window, click Forms 4. On the main menu, click Insert -> Query 5. In the New Table dialog box, double-click Design View and click Close 6. On the main menu, click View -> SQL View 7. To delete a table, change the statement as follows: DROP TABLE ForTheCustomers 8. Close the query window. When asked whether you want to save it, click Yes

9. Type Delete Useless Table as the name of the query and press Enter
10. On the Database window, click Tables and notice that the ForTheCustomers table is gone

Queries and Record Deletion


Besides deleting tables, you can also delete individual records of a table. Microsoft Access provides an easy mechanism of performing such an operation. To delete a group of records in one action, you can create a special query called a Delete Query. Like all other Microsoft Access queries, a Delete Query allows you to select the necessary fields of a table. The first difference between this and the Select Query is that the Delete Query, like all other action queries, selects or considers all fields, even those you do not include in your statement. The other columns are those that would be used to specify the rules under which a record must be deleted. The rule that governs whether a record must be deleted or not is also called a criterion. You can use many criteria to set the rule to follow in order to get rid of a record. Like most other

247

action queries, the action of a Delete Query is irreversible.

Practical Learning: Deleting Database Records


1. The Bethesda Car Rental1 database should still be opened. On the Database window, click Tables and double-click the Cars table to open it 2. Review the records and, in the Year column, notice some cars from 1998, 1996, or 1999. Now that the company has new cars, Management has decided it is time to retire any car that was made before 2000. We will use a query to delete all cars. Close the table but, in the Database window, make sure it is still selected 3. On the main menu, click Insert -> Query and, in the New Query dialog box, double-click Design View 4. On the main menu, click Query -> Delete Query 5. In the Cars list, double-click TagNumber, Make, Model, and CarYear

6. Click the Criteria box of the CarYear column. Type <2000 and press Enter

7. To preview the list of cars that would be deleted, on the main menu, click View -> Datasheet View. Notice that 18 cars will be deleted 8. Leave the query window opened and, on the Database window, double-click the Cars table to open and check the Available field of some cars. Notice that some cars (like the 2) are not available. Either they have been rented or we do not know for sure where they are. Because of this, we cannot delete a car from the system if we cannot certify where it is. Instead of starting to call everybody and sending emails all over the place, we will simply ignore non-Available cars for now: we will delete only cars that are available because we are more likely to know where they are. 9. Close the Cars table and get back to the query 10. Switch the query to Design View 11. From the Cars list, double-click Available

12. Click the Criteria box of the Available column. Type =True and press Enter

248

13. Save the query as Retire Old Cars 14. View the SQL statement

15. Execute the query. When the message box appears, read it and click Yes 16. Close the query window 17. Open the Cars table and notice that cars older than 2000 have been deleted 18. Close Microsoft Access

Database Maintenance, Import, and Export


Data Maintenance
Default Value
Data entry consists of typing values in data fields or selecting values from bound controls. Some records happen to have the same value for a particular field, or most records hold a common value for a certain field. When designing a form, you can assign the most commonly used value to such a field so the user would not have to type it. The user would change the value only if it is different from the usual. For example, when creating a database for a small company, all employees may have the same telephone number but with individual extensions. When a new record is being entered, the value would be set already for the field. To specify a regularly used value for a field, open a table or a form in Design View, select the field, and type the desired value in the Default Value field. The default value should be appropriately typed: If the field is text-based, you can type the default text included in double-quotes. Examples are M, Virginia, (301) 122-4738 If the field is numeric, you can type the default number If the field is date-based, you have two options and you want to specify a fixed date as the default value, type it between two # signs. An example would be #2/5/1998# If the field is date-based, you can also type a function that would find the correct date to display. For example, to provide the current date as default value, you would use the Date() function.

Practical Learning: Setting Default Values


1. Open the Rockville Techno database 2. In the database window, click Tables and double-click the Employees table to open it in Datasheet View 3. Switch it to Design View

4. In the upper section of the table, click Country 5. In the lower section, click Default Value, type USA and press Enter 6. In the upper section of the table, click WorkPhone 249

7. In the lower section, click Default Value, type (301) 668-0808 and press Enter 8. In the upper section of the table, click DateHired 9. In the lower section, click Default Value, type =Date() and press Enter
10. Save the table

Validation Rule
A validate rule is a condition that the value entered in a field must meet in order to be valid. This rule is usually created as an expression and entered in the Validation Rule property of a field when the table or the form is opened in Design View.

Practical Learning: Setting Validation Rules


1. The Employees table of the Rockville Techno database should still be opened with the
Employees table in Design View. In the upper section of the table, click BillingRate

2. In the lower section, click Validation Rule, type 15.00 and press Enter
3. Save the table

Validation Text
When the condition in the Validation Rule field is not respected, you can display a message box to let the user know. The message for that text box can be created as a string in the Validation Text field.

Practical Learning: Creating a Validation Text


1. In the upper section of the table, click BillingRate 2. In the lower section, type:
3. Save and close the table The minimum billing rate or salary of this company is $15.00

Value Required for a Field


If you think that there must be an entry for a particular field for each record, you can let Microsoft Access know. The Required property is Boolean value. If you set it to Yes, the user would not be able to move to the next record until he has entered a valid data in the field. Its default value is No.

Practical Learning: Specifying Required Fields


1. Open the Clients table in Datasheet View and, after viewing it, switch it to Design View

2. In the upper section of the table, click ContactLastName


3. In the lower section, double-click Required to change its value to Yes

4. In the upper section of the table, click PhoneNumber 5. In the lower section, double-click Required to change its value to Yes
6. Save and close the table

Indexed Fields
When data is entered in fields, it is possible to have the same value for a field in different records, such as two people who live in the same state. This is considered as a duplicate value. In some other cases, this may not be acceptable. For example, you may not want two employees to have the same employee number. This characteristic can be set using the Indexed property that provides 3 values:

250

If set to No (its default), no duplicate value checking will be done If you want the database engine to check for duplicate but not necessary take any action, set this property to Yes (Duplicates OK) If you do not want a duplicate value of the same field in different records, set the fields Indexed property to Yes (No Duplicates)

Practical Learning: Controlling Indexed Fields


1. Right-click the Employees table and click Design View

2. In the upper section, click EmployeeNumber 3. In the lower section, click Indexed to display its combo box. Click the arrow of the
Indexed combo box and select Yes (No Duplicates)

4. In the upper section, click EmailAddress 5. In the lower section, double-click Indexed a few times until it display Yes (No
Duplicates)

Data Import/Export
Introduction
Importing data allows you to get information from an external source and insert it in your database. Microsoft Access can accept data from various applications, and with a little trick, you can import even from unfriendly applications. Before importing data, you must make sure that it is in a format Microsoft Access can read; even if that data is coming from another application of the Microsoft Office suite.

Practical Learning: Introducing Data Import


1. From the resources that accompany this ebook, locate a text file named Customers, a Microsoft Excel spreadsheet named Employees, and a Microsoft Access database named Georgetown 2. Copy and paste them in your Exercises folder 3. In Microsoft Access, create a new blank database named GCS

Import/Export With Text Files


As you are already familiar with Microsoft Access functionality, you know that a cell is delimited with gridlines. If you intend to import a text document, format it so that Microsoft Access can recognize where a field starts and where it ends. Such a file can be created with Notepad. This delimiter is usually done by pressing Tab when creating the fields' content and pressing Enter at the end of each record. Instead of the Tab key, you can also use a comma or a semi-colon to separate two fields. Since a field is usually made of more than one word (such as an address), enclose the content of each field in double quotes, as in "1600 Pennsylvania Avenue". When importing data, you use a wizard that will assist you in identifying the document, the fields delimiter, and the target table where you would like to store the new data. You can create a new stable or use one already created in your database

Practical Learning: Importing a Text Document


1. Start a text application, such as Notepad (Start -> (All) Programs -> Accessories -> Notepad) 2. Open the Customers.txt file to see what it looks like. Then close Notepad 3. On the main menu, click: File -> Get External Data -> Import...

4. Locate your Exercises folder and display it in the Look In combo box 251

5. Click the arrow of the Files Of Type combo box and select Text Files 6. On the list of files, click Customers (it should be selected already) and click Import 7. On the first page of the Import Text Wizard, accept that the text be Delimited and click Next 8. On the second page, set the delimiter as Comma and check the box stating: First Row Contains Field Names

9. Click Next 10. Accept to store the data In A New Table and click Next 11. Click the Notes column to select it then, in the Data Type combo box, select Memo

12. Click Next 13. Accept to Let Access Add Primary Key and click Next

14. Finally, you are asked to give a name to the table.


Accept the name of the table as Customers

252

15. Click Finish. You should receive a confirmation message when the table has been imported

16. Click OK 17. In the Database window, click Tables and double-click the Customers table to see what it looks like 18. Close the Customers table

Import/Export With Microsoft Access Objects


Microsoft Access objects are probably the easiest objects to import because, created with of the same application, these objects are already formatted and recognizable. To import objects from another Microsoft Access database, you can use the main menu or the New Table dialog box.

Practical Learning: Importing a Microsoft Access Object


1. The GCS database should still be opened. On the main menu, click File -> Get External Data -> Import 2. Locate your Exercises folder and display it in the Look In combo box. Change the Files Of Type combo box to Microsoft Access 3. Then, click Georgetown and click Import 4. In the Import Objects property sheet, click the Forms property page 5. In the Forms property page, click OrderProcessing

253

6. Click OK

Database Objects Linking


Linking data allows you to connect your database to an external document. Such a table can have its data accessed directly or modified in Microsoft Access. When linking data, since you are making it available to the database, make sure that Microsoft Access can "read" it; otherwise it would not recognize its content. The main reason you link data is to treat your database as one file despite its belonging to another document. Linking to a spreadsheet is usually a straightforward process. Linking to a word processing document usually involves performing a mail merge.

Practical Learning: Linking to a Microsoft Access Object


1. The GCS database should still be opened. On the main menu, click Insert -> Table 2. In the New Table dialog box, click Link Table

3. Click OK 4. Locate your Exercises folder and display it in the Look In combo box. Click Georgetown and click Link 5. In the Link Tables property sheet and in the Tables property page, click OrderProcessing

254

6. Click OK 7. In the Database window, click Tables

Import/Export/Linking With Spreadsheet Files


When creating a spreadsheet in Microsoft Excel for data import, you have two alternatives. You can create the column headers at the very top of the worksheet and type a data field in each corresponding column. Alternatively, you can create data as on a table, and then create a name range that holds the information you need in the database. To import a Microsoft Excel spreadsheet, on the main menu, you can click File -> Get External Data -> Import. Locate the file that holds the spreadsheet and click Import. You would be asked to specify what to import, a whole spreadsheet or a named range. There are various circumstances when you will need to link to a spreadsheet rather than importing it. The main idea is to accommodate your users. To link to a spreadsheet, you use the same approach.

Practical Learning: Linking to a Spreadsheet


1. Start Microsoft Excel if you have it. From your Exercises folder, open the Employees spreadsheet to see what it looks like. Then close Microsoft Excel and return to Microsoft Access. The GCS database should still be opened. On the main menu, click File -> Get External Data -> Link Tables 2. Locate your Exercises folder and display it in the Look In combo box 3. Change the Files of Type to Microsoft Excel and click Employees (it should be selected already 4. Click Link 5. In the first page of the Link Spreadsheet Wizard, accept the Show Worksheets radio button and, in the list, click Employees

6. Click Next

7. On the 2nd page, make sure the First Row Contains Column Headings check box is 255

selected and click Next

8. Accept the name of the table as Employees and click Finish


9. A message box lets you know that the table has been linked. Click OK

10. To view the table in Microsoft Access, double-click the Employees linked table 11. After viewing the table, close it

Import/Export With Microsoft Outlook


Importing a Microsoft Outlook document is mainly done on the address book level and is as smooth as what we have seen so far. All you have to do is have the address book already created and you are ready to go. The following exercise is not supposed to be performed here; it is provided as a guide 1. On the Database toolbar, click the arrow of the New Object button and choose Table 2. In the New Table dialog, double-click Import Table 3. In the Import dialog, change the Files of Type to Outlook 4. A particular wizard starts. In the first page of the wizard, click the + on Personal Folders to expand it

5. Click Contacts and click Next 6. Accept to store data In A New Table and click Next 7. Click Next, Next, Finish, and OK

Saving a Database Object As a Web Page

256

Microsoft Access allows you to create a web page based of your database. The process of doing this is different from one version of Microsoft Access to another. We will cover only Microsoft Access 2000.

Practical Learning: Exporting a Database Object as HTML


1. Open the Rockville Techno database 2. In the Database window, click Queries. Right-click AssetsInventory and click Exports 3. In the Export Query dialog box, locate and display your Exercises folder in the Save In combo box

4. In the Save As Type combo box, select HTML Documents

5. Click Save 6. Still in the Queries section of the Database window, click AssetsAssignedToEmployees to select it 7. On the main menu, click File -> Export 8. Make sure the Save As Type displays HTML Documents. Click the Save Formatted check box and click Save 9. On the HTML Output Options dialog box, click the Browse button 10. Locate the folder in which you installed Microsoft Access or Microsoft Office. Open the Templates folder. Open the 1033 folder. Open the Pages folder. Open the Normal folder

11. Click Normal and click OK 12. On the HTML Output Options dialog box, click OK

Mail Merge
Mail merging allows you to use data on your database to create letters, labels, envelopes, and

257

other documents that require external data originating from another document. When performing a mail merge, you usually do not need all the fields that are part of a table. Although you can use all fields on a table, it is recommended that you create a query made only of fields you need for your document. This would include the name and address of the recipient. Perform the following exercise only if you have Microsoft Word

Practical Learning: Merging Data With Microsoft Word


1. Open the Bethesda Car Rental1 database 2. On the main menu of Microsoft Access, click Insert -> Query 3. On the New Query dialog box, double-click Simple Query Wizard. 4. In the 1st page of the Simple Query Wizard, click the arrow of the Tables/Queries combo box and select Table: Customers 5. On the Available Fields list box, double-click FirstName, LastName, Address, City, State, ZIPCode, and Country 6. Click Next 7. Change the name of the query to CustumersContact and click Finish 8. Close the query and close Microsoft Access 9. Start Microsoft Word 10. On the main menu, click Tools -> Mail Merge

11. On the Mail Merge Helper dialog box, click Create -> Form Letters

12. On the Microsoft Word dialog box, click New Main Document

13. On the Microsoft Word dialog box, click Get Data -> Open Data Source

258

14. From the Open Data Source dialog, click the arrow of the Files Of Types combo box and select MS Access Databases 15. Using the Look In combo box, locate your Exercises folder and display it in the Look In combo box 16. Click Bethesda Car Rental1 and click Open 17. From the Microsoft Access dialog, click the Queries property page 18. Click CustumersContact and click OK 19. Now Microsoft Word would like you to create the letter Click Edit Main Document 20. To save the letter, press Ctrl + S and save the document as Promotion102 21. Now we will create the main letter Since in the beginning we decided to create a New Main Document, if you are using Microsoft Word 2000, you should have two instances of Microsoft Word running (on the Taskbar) If you are using Microsoft Word 2000, from the Taskbar, click the other instance of Microsoft Word, it might display Document1 - Microsoft Word If you are using Microsoft Word 97, on the menu bar, click Window -> Document1 22. On the main menu, click File -> Open... 23. From the exercises that accompany this ebook, select the BCR Promotion document, and then click Open. That opens the document we will use 24. On the main menu, click Edit -> Select All 25. On the main menu again, click Edit -> Copy 26. From the Taskbar, click the instance of Microsoft Word that is holding our mail merge process 27. On the main menu, click Edit -> Paste. After the letter has been pasted, all we have to do now is to edit the document for our mail merge 28. Press Ctrl + Home to get to the beginning of the letter 29. Double-click Date to highlight it 30. On the main menu, click Insert -> Date and Time... 31. From the Date And Time dialog, click the 3rd date

259

32. And click OK 33. Click on the right side of Dear 34. On the Mail Merge toolbar, click Insert Merge Field -> FirstName 35. Press the Space bar 36. On the Mail Merge toolbar, click Insert Merge Field -> LastName

37. To read and preview the document, on the Mail Merge Helper toolbar, click the View
Merged Field button

38. To review the letters, use the navigation buttons: Button Name Description

View Merged Data Toggles the code of the merging process First Record Previous Record Go To Record Next Record Last Record Displays the very first record on the list Displays the previous record on the list To jump to a particular record, click in the Go To Record text box, type a number and press Enter. The corresponding record will be displayed Displays the next record on the list Displays the very last record on the list

39. To print the letters, on the Mail Merge toolbar, click the Merge to Printer button
40. On the Print dialog box, click OK 41. Now we will create the envelopes 42. On the main menu, click Tools -> Mail Merge 43. On the Mail Merge Helper dialog box, click Create -> Envelopes... 44. When you receive the dialog, click New Main Document 45. In the Data Source section, click Get Data -> Open Data Source... 46. Change the Files of Type combo box to MS Access Database then locate and display your Exercises folder in the Look In combo box 47. From the list of files, select Bethesda Car Rental1 and click Open. 48. On the Microsoft Access dialog box, click the Queries property page. Click

260

CustumersContact and click OK

49. Click Set Up Main Document 50. In the Envelope Options dialog box, accept the envelope size 10 and click OK 51. In the Envelope Address dialog, click Insert Merge Field -> FirstName 52. Press the Space bar 53. Click Insert Merge Field -> LastName 54. Press Enter. Click Insert Merge Field -> Address 55. Press Enter 56. Click Insert Merge Field -> City 57. Type the comma and press the Space bar 58. Click Insert Merge Field -> State and press the Space bar 59. Click Insert Merge Field -> ZIPCode 60. Press Ctrl + Home to position the cursor to the left of FirstName 61. Click Insert Postal Bar Code... 62. Click Merge Field With ZIP Code combo box and select ZIPCode 63. Click the Merge Field With Street Address combo box and select Address

64. Click OK 65. Click OK and click Close

261

66. To view the merged envelopes, on the Mail Merge toolbar, click the View Merged Data
button 67. Once more, to review the envelopes, use the navigation buttons on the Mail Merge toolbar.

68. To print the envelopes, on the Mail Merge toolbar, click the Merge to Printer button
69. Close Microsoft Word. You will be prompted to save your document. It is up to you

Considerations on Data Entry


The Computer Regional Settings
The information in a database is stored in tables, although you will usually not allow users to get access to such objects. The table is therefore the most principal means of data entry. The computer controls how it is supposed to display some pieces of information such as date and time values. These also affect internal settings of databases and other programs used on a computer. To view, control or set these properties, the computer bases its decisions on the Regional Settings dialog box from the Control Panel window. To review the Regional Settings of your computer, you can click Start -> Settings -> Control Panel. If you are using MS WinXP, you can click Start -> Control Panel. From the Control Panel window, you can double-click Regional Settings. If you are using WinXP, click Regional and Language Options. Click each of the property pages: Number, Currency, Date, and Time

Practical Learning: Using the Computer's Regional Settings


1. Open Control Panel and double Regional Settings. If you are using MS Windows XP, after opening Control Panel, click Switch to Classic View, then double-click Regional and Language Options and click Customize...

262

2. Click the Date property page

3. In the Short Date Style combo box, select M/d/yy

4. Click OK twice 5. Return to Microsoft Access and open the CompanyAssets table

The Office Clipboard


If you are using Microsoft Access 97, skip this section The computer clipboard is a non-spatial object used to temporarily hold a piece of data. In fact, it is one form of memory in which you can store information to be retrieved. The word temporary implies two things. First, the clipboard can hold its data only as long as the computer is On. If you turn the computer Off, the clipboard gets emptied and looses its data. Second, the clipboard can hold only one type of data. The good news is that the clipboard is not strictly confined to one type of information. This means that it can hold a picture (any type) OR text (any length), anything. This was the behavior of the classic clipboard. Microsoft Access 2000 brought tremendous improvement to the clipboard. The new Microsoft Office clipboard can hold up to 12 items. Each item is independent of the others and can individually be anything. In fact, information held by one of these memories can origin from any application. To use Microsoft Office Clipboard, you should first display it. To do this, you can first open an object such as a table or a form. Then, on the main menu, you can click View -> Toolbars -> Clipboard. To copy an object to the clipboard, you can just press Ctrl + C or Edit -> Copy from the main menu. You can also select something and then click Copy on the Clipboard toolbar.

The Size of a Database


A database is primarily a computer file, just like those created with other applications. As such, it occupies an amount of space in the computer memory. In some circumstances, you should know how much space your product is using. This can be important when you need to back it up or when it is time to distribute it. Also, when adding and deleting objects from your database, its file can grow or shrink without your direct intervention. Like any other computer file, to know the size of a database, you can right-click it in Windows Explorer or My Computer and click Properties. If you are already using the database, to check its size, you can access the properties from the main menu under the File category.

Practical Learning: Checking the Size of a Database File


263

1. Open the Bethesda Car Rental1 database 2. To check its size, on the main menu, click File -> Database Properties 3. In the Properties dialog box, click the General tab and notice the value on the right side of the Size label 4. Click Cancel to close the Properties dialog box

Deleting Database Objects


As we have seen so far, there are various reasons you create objects in your database. Some will be made part of the final product. Some others are used to test conditions, values, data entry, etc. When such temporary objects are not needed anymore, you can delete them. To delete a table, we learned that you could use the DROP TABLE expression in a SQL statement and specify the name of the table. To delete any database object (table, query, form, etc), you can click to select it, and then press Delete. Unlike some other database environments (like Corel Paradox), a Microsoft Access table is not a stand-alone object, which means you cannot access it as its own entity outside of its database. For this reason, when you delete a database object such as a table or a form, it does not go into the Recycle Bin. Therefore, the deleting action is irreversible. Whenever in doubt, do not delete a database object, especially a table.

Practical Learning: Deleting a Database


1. The Bethesda Car Rental1 database should still be opened In the Database window, click Forms 2. Click Custumers2 to select it 3. On your keyboard, press Delete 4. When a warning message comes up, read it and click Yes 5. In the Database window, click Tables 6. Right-click the CarsToConsiderRetiring table and click Delete 7. To check the current size of the database, on the main menu, click File -> Database Properties 8. Check the size in the General property page and click Cancel to close the Properties dialog box

Compact and Repair of a Database


As mentioned already, once you have created a database file, it occupies a certain amount of memory space that can grow or shrink without your direct intervention:

When you add an object to the database, the database's file grows as needed. When you remove an object, the memory space it was occupying is left empty. This also applies when you keep removing objects:

264

The computer is supposed to recuperate the space those previous objects were using. Unfortunately, that is not the case. Most of the time, that space is left empty but cannot be accessed by the computer. This means that the memory space cannot be made available to other applications. To recover this memory space, you can compact the database. When this is done, the file is shrunk to occupy only the necessary amount of space and free the unused sections:

To compact a database, on the main menu, you can click Tools -> Database Utilities -> Compact and Repair (in Microsoft Access 97, the Compact Database and the Repair Database are separate menu items).

Practical Learning: Compacting a Database


1. The Bethesda Car Rental1 database should still be opened. If you want, check the database size again. On the main menu, click Tools -> Database Utilities -> Compact (and Repair) Database 2. When the operation has been completed, on the main menu, click File -> Database Properties 3. Notice that the database size has been reduced. Click Cancel to close the Properties dialog box.

Maintenance of Imported Objects


Like most other computer applications, a database is a product that can benefit from regular revisions and improvements. There are various operations related to database maintenance, including renaming objects, changing the sequence of fields, applying customers feed back. We have already performed some of these actions such as renaming fields of a table in Datasheet View and in Design View. Whenever you import a database object from an external source, to be understood by Microsoft Access, its data field would receive some configuration that you may not like. For this reason, after importing a table from a text file or from a Microsoft Excel spreadsheet, you should review it in Design View and customize the fields if necessary. Most of the time, each text field imported would be assigned a field size of 255 characters. If a field in numeric, you should review it and specify the appropriate numeric data type. If you import a spreadsheet a field hold monetary values, its field would be translated with the Currency data type. Microsoft Excel and text files do not have the concept of AutoNumber. When importing data from an external source, if you want to use an AutoNumber field on the new object, you should let Microsoft Access create a new field as the Primary Key. In this case, Microsoft Access would also create it as AutoNumber. If you decide to create your own primary key and if the object

265

already contains data, you cannot change it to an AutoNumber. If you link your database to an external object, you should not modify its structure because your database is not supposed to control this. Your database in this type of scenario is mainly used for data entry. This is why you should make a decision between importing and linking.

Practical Learning: Customizing Imported Objects


1. Open the GCS database that you created above 2. From the Tables section of the Database window, double-click the Customers table to open it in Datasheet View 3. After viewing the table, switch it to Design View 4. Double-click ID to select it. Type CustomerID and press F6 5. Change its Caption to Customer ID 6. In the upper section of the table, double-click HomePhone. Type CustomerPhone and complete the table as follows: Field Name FirstName LastName CustomerPhone Notes 7. Save the table and close it Field Size 20 20 20 Input Mask Caption First Name Last Name !\(999") "000\-0000;0;_ Phone Number Required No Yes

Data Objects Backups


If you are working on a complex database and need to perform some tests on it, you should avoid use the original objects as a test might mess them. The alternative is to create a copy of either the object or the database itself. It is important to remember that data resides on tables. For this reason, if you copy a form or query and change the data, for example if you delete a record, the record would be deleted from the database. If you copy a table and make record changes on the new table, you would be safe because such a table would have a new and independent set of records. To make a backup copy of any object that is part of your database, you can right-click it and click Copy. Then right click the same window and click Paste. Since two objects (of the same category) cannot have the same name, a dialog box would display to request a new and different name for the object you are copying.

Practical Learning: Backing Up Database Objects


1. Open the Bethesda Car Rental1 database and, in the Database window, click Tables 2. To make a backup of a table, right-click the VariousOrders table and click Save As. If you are using Microsoft Access 97, click the second radio button (Within The Current Database As) 3. Set the name of the table to OrderProcessing and click OK

Database Backup
When working regularly with a database, you should always make a backup of your database, in case something bad happens like a computer complete crash where you may not be able to recover. In most cases too, especially if you have a customer whose product you have developed, you should make a copy of the database to give away while keeping the original. To make a backup copy of a database, you can open either Windows Explorer or My Computer, locate the folder in which the database is located, then right-click it and click Copy. If you

266

right-click the same window and click Paste, a copy of the same database would be created with a name that starts with Copy of If you right-click another folder and click Paste, a new copy of the database with the same name would be created in the new folder. You can also make a backup copy of a database to distribute either to colleagues, employees, students, or customers, etc. In this case, you can copy it from Windows Explorer or My Computer and paste it in the floppy drive. If the database is too large, such as the current Bethesda Car Rental (because it has grown a lot after adding the pictures), it would not fit in one floppy disk. In such case, you can zip it using zip software and possibly spread it on various floppy disks. The best alternative is probably to put on a CD-ROM. Since most computers nowadays ship with a CD Writer, this should not be difficult to do. If you have a more advanced backup system for your computer, you can also use it regular to backup your database. As backup systems are different, if you have one, it would give you the information you need to proceed. The following exercises are completely optional.

Practical Learning: Backing Up a Database


1. Open the Clarksville Ice Cream2 database 2. To compact it, on the main menu, click Tools -> Database Utilities -> Compact (And Repair) Database 3. Close Microsoft Access 4. Open Windows Explorer and put a floppy disk in the floppy drive (A:). Right-click the A: drive and click Format 5. After formatting the disk, click Close on the 6. Still in Windows Explorer, on the left frame, select your Exercises folder 7. On the right frame, click Clarksville Ice Cream2 and drag it to the floppy drive to back it up 8. To backup a database to a CD-R, put a blank CD in your CD writer drive 9. If a window comes up asking you to create a CD, you can use it. If nothing comes up, in the right frame of Windows Explorer, right-click Bethesda Car Rental1, position the mouse on Send To and click the name of the drive that is the CD-R

MDE Files
If you have created a database and decide to distribute it or to give it to a customer, colleagues or employees, they may be tempted to open the forms in Design View and possibly modify their structures. There are two disadvantages to such an action. They may compromise or corrupt your hard, possibly rendering obsolete. Some bad eye may decide to cheat on your hard work VBA code. Microsoft Access allows you to make some or most of these actions difficult or impossible. An MDE file is a database compiled by Microsoft Access so the users of the database cannot change the design of forms or reports, create new forms or reports, view its VBA code, or import forms, reports or VBA code. To create an MDE file of your database, after opening it, on the main menu, you can click Tools -> Database Utilities -> Make MDE File

Practical Learning: Creating an MDE File


1. Open the Rockville Techno database

267

2. On the main menu, click Tools -> Database Utilities -> Make MDE File

Exercises
Yugo National Bank
1. Open the Yugo National Bank. Open the Customers table in Design View and set the following properties Field Name AccountNumber CustomerName Address City State ZIPCode Country HomePhone Save and close the table 2. Open the Employees table in Design View and change the following properties Field Name EmployeeNumber LastName WorkPhone Country Save and close the table 3. Open the Transactions table in Design View and change the following properties Field Name EmployeeID CustomerID TransactionTypeID TransactionDate TransactionNumber ServiceCharge ChargeReasonID Save and close the table 4. Save the Employees form as HTML and access all defaults 5. Save the Customers table as an MS Excel spreadsheet (Tools -> Office Links -> Analyze It With MS Excel) 6. Check the size of the database. Then compact it 0 Delete the 0 Default Value Delete the 0 Delete the 0 Delete the 0 Required Yes Yes Yes Yes Yes Yes (No Duplicates) Indexed "(410) 653-1309" "USA" Yes Default Value Required Indexed Yes (No Duplicates) "USA" Yes Yes Yes Yes Yes Yes Default Value Required Indexed Yes (No Duplicates)

Watts A Loan
268

1. Open the Watts A Loan database. Open the Customers table in Design View and set the following properties Field Name AccountNumber LastName Address City State ZIPCode Country HomePhone Save and close the table 2. Open the Employees table in Design View and change the following properties Field Name LastName WorkPhone State Country Save and close the table 3. Open the Transactions table in Design View and delete the number 0 in the Default Value property of the EmployeeID field. Delete the number 0 as the Default Value of the CustomerID field. Set 0 as the Default Value of the TransactionAmount field 4. Open the LoanProcessing table in Design View and change the following properties "(410) 781-6238" "MD" "USA" Default Value Required Indexed Yes "USA" Yes "MD" Yes Yes Yes Yes Yes Default Value Required Indexed Yes (No Duplicates)

Field Name EmployeeID DateProcessed CustomerID TypeOfLoan LoanAmount InterestRate RegularPaymentsDueOn Save and close the table

Default Value

Required Yes Yes Yes

1 0 0.0875 "The 25th of the month"

Yes

5. Open the Customers table. Select all records (Ctrl + A -> Ctrl + C) and paste the
selection in Notepad. Save the text file as WAL Employees in your My Documents folder 6. Save the Employees table as text

Tables and Queries Aesthetics


269

Columns and Fields Visibility


Hidden Columns on Tables
When examining records on a database, some tables are so wide the user would need to scroll left and right to see fields one screen at a time. Sometimes, the user does not need to see all fields all the time. Microsoft Access allows you to temporarily hide unneeded columns. This feature does not delete records or columns; it only hides them and can display the columns as needed. To hide columns, you have two options: You can narrow a column by dragging its right border completely to the right until the whole column disappears. Here is an example where the Last Name column has been hidden:

The other approach to hiding columns is to know which columns are hidden or not. To do that, on the menu bar, you would click Format -> Unhide Columns...

The Unhide Columns dialog box allows you to visually see what columns are currently displaying and which ones are hidden. To hide a column, uncheck its check box. To display a hidden column, check its unchecked box. You can also access the Unhide Column dialog by right-clicking the table's title bar. The Unhide Columns dialog box works live with the table. This means that columns are hidden and unhidden as you check or uncheck them on the dialog box. After hiding some columns on the table, you can save it if you want the table to remember what columns were hidden previously. This is valuable for data analysis and does not have any impact on a form whose records emanate from this table. Microsoft .

Practical Learning: Hiding and Un-hiding Columns


1. Open the ROSH database

270

2. From the Tables section of the Database window, double-click Students1 to open it 3. Position your mouse on the right border of the Date of Birth column header until the mouse cursor turns into a vertical bar crossed by a double arrow:

4. Click and drag in the left direction until you cannot go any further to the left. Then release the mouse Notice that the Date of Birth column is not displaying anymore 5. To view a list of columns, on the main menu, click Format -> Unhide Columns... 6. Notice that the check box of the Date of Birth is not marked 7. Move the Unhide Columns dialog box down and make sure you can see the Student # and the Gdr column headers (of course your screen resolution will control the number of columns you can see at a time) 8. To display the Date of Birth column, click the check box of Date of Birth 9. Notice that the Date of Birth is now displaying on the table 10. Click Close on the dialog box 11. To hide columns, right-click the title bar of the table and click Unhide Columns... 12. On the Unhide Columns dialog box, uncheck Student #, MI, Address, City, State, ZIP Code, Home Phone, Email Address, Parents Names, Single Parent?, and Notes:

13. On the Unhide Columns dialog box, click Close 14. To display all columns again, on the main menu, click Format -> Unhide Column... 15. Check all of the check boxes and click Close 16. Close the table. When asked whether you want to save the table, click No

Hidden Columns on Queries


271

To display or hide a column in a query, you can open the query in Design View and use the Show check box of the column:

If you leave the Show check box of a column, which is the default value, when you run the query, the column would display:

If you clear the check box of a column, the column would still be part of the query but it would not display when the query is run. In the SQL, if you do not want to display a column, you can simply omit or delete it from the statement. For example, the following statement can be used to display the LastName column from the Persons table and the Gender column from the Genders table while both tables are joined by the GenderID primary key of the Persons table and the GenderID foreign key of the Persons table representing the Genders table: SELECT Persons.LastName, Gender.Gender FROM Gender LEFT JOIN Persons ON Gender.GenderId = Persons.GenderID;

Practical Learning: Hiding Column on a Query


1. On the main menu, click Insert -> Query 2. In the New Query dialog box, double-click Simple Query Wizard 3. In the Tables/Queries combo box, select Table: Students 4. In the Available Fields, double-click FirstName, LastName, DOB, SingleParentHome, EmergencyPhone, and Gender

272

5. Click Next 6. Accept the default on the second page of the wizard and click Next 7. Change the Title of the query to List Of Female Students and click Finish

8. Notice that the list contains both male and female students. Also, on the bottom bar of the Datasheet View, notice the total number of students 9. Switch the query to Design View 10. To isolate only the list of girls, click the Criteria box of the Gender column and type =Female

11. Run the query 12. Notice that the query now shows only records whose Gender value is Female. Also notice the total number of students 13. Switch the query to Design View 14. Since we know that the list will include only girls, we do not need to display the Gender

273

column. Click the Show check box of the Gender column to remove the check mark 15. Run the query 16. Save and close the query-

Hidden Fields on Forms and Reports


To hide a field from a form or a report, as done for a query, you can simply avoid adding it to your form or report when designing the form or report. There will be many other cases where you must add the field to the form or report but would not need to show it to the user. In such a case, after adding the field to the form or report, access its Properties window and change the value of its Visible Boolean property:

If you set the value to Yes, the field would display at run time. If you want to hide the field, set its Visible property to No.

Columns Freezing on Tables and Queries


During table or query data entry or analysis, you have to scroll left and right to navigate from various fields if the table is very large or too wide for your screen resolution. Sometimes, this would be annoying if you do not need access to all fields of all columns. Microsoft access allows you to work in series of records so that you can fix some columns on the left side of the screen and scroll only to its right columns. To freeze a column, you should first click it to select it. Then on the main menu, click Format -> Freeze columns. The column would be moved to the left side of the table and would become the first column. The columns that were on its left would be moved to the right. The frozen column would become static with a thick right border. When scrolling to the right, only the other columns would move. To freeze a group of columns, first select them using the Shift key + click combination. Then freeze them in the same way. The selected columns would be moved to the left of the table and become static. If you scroll to the right, only the other columns would move. The technique applied to the tables in the following Practical Learning section can also be applied to a wide query.

Practical Learning: Freezing Columns


1. Open the Students1 table and click any field in the Last Name column 2. On the menu bar, click Format -> Freeze Columns 3. Notice that the Last Name column has moved to the left 4. Scroll to the right to view the Notes column 5. To release the Last Name column, on the main menu, click Format -> Unfreeze All

274

Columns 6. Close the table. When asked to save, click No 7. Reopen the Students1 table 8. Make sure the cursor is in a field of the Student ID column 9. Press and hold Shift 10. Click the Last Name column header to select all columns in the range 11. After selecting the range of columns, right-click a field in the selection and click Freeze Columns 12. Click anywhere on the table and scroll to the right to see the effect 13. To dismiss the freezing of columns, on the main menu, click Format -> Unfreeze All Columns 14. Close the table. When asked if you want to save, click No.

Table and Query Datasheet Formatting


Cells Font
Although you will usually not give access of your database tables to the users, there are techniques you can use to improve the table's appearance just in case people would use it. This is also helpful if you create a form that looks like a table (Datasheet Form). A table appears as a series of cells. Their font is a regular black Arial in size 10. Microsoft Access allows you to modify the font of the text that displays in cells. To do this, you can use the Font dialog box available either from the Format item of the main menu or by selecting Font after right-clicking the title bar of a table.

Practical Learning: Changing the Cells Font


1. Open the Rockville Techno database and, from the Tables section, double-click the Employees table to open it 2. On the main menu, click Format -> Font... 3. Change the Font Name to Verdana. Keep the Font Style to Regular. Leave the Size to 10 Click the arrow of the Color combo box and select Blue:

4. Click OK

275

Formatting the Table Grids


A table in Microsoft Access appears as a classic spreadsheet with a white background and gray grid lines. If this display is not appealing, you have two options. You can apply a gray background with white or dark gray grid lines. You can also change the background to one of the preset colors and change the grid lines to another color. To change the grids appearance, on the menu bar, you can click Format -> Datasheet... You can also right-click the title bar of the table and click Datasheet...t.

Practical Learning: Changing Columns Width and Rows Height


1. On the Database Window, double-click the Employees table to open it in Datasheet View 2. On the main menu, click Format -> Datasheet... 3. In the Cell Effects section, click the Raised radio button and click OK

4. Save and close the Employees table 5. Open the Payment Methods table in Datasheet View 6. Right-click its title bar and click Datasheet 7. In the Cell Effect section, click the Flat radio button if necessary In the Gridlines Shown group, make sure both the Horizontal and Vertical check boxes are checked 8. Click the arrow of the Background Color combo box and select Blue 9. Click the arrow of the Gridline Color to Aqua

10. Click OK

276

11. Right-click the title bar of the table and click Font... 12. Set the Font name to Verdana. Keep the Font Style to Bold and keep the Font Size to 10. Set the Color to Lime and click OK 13. Double-click the lines between the column headers

14. Save and close the table

Exercises
Watts A Loan
1. Open the Watts A Loan database. Using the Simple Query Wizard, create a query based
on the Customers table and that includes the following fields: AccountNumber, FirstName, LastName, and HomePhome. Save the Query as Customers Contact Information and close it

2. Open the Customers Contact Information query and format it as follows:


Font: Verdana Font Color: Lime Gridline Color: Aqua Background Color: Navy Cell Effect: Raised

Save and close the query

Form Design
277

Forms Properties
Introduction
A form appears to be the most regularly used object of a Microsoft Access database. Although there are various means of quickly creating a form, as we saw with the Form Wizard or AutoForm and their variations, at times you will need to further customize the appearance of a form to the user as this can affect the overall understanding of your product. A form by itself is presented as a rectangular object that shares many of the characteristics of a regular container: a system icon, a title bar, one or more system buttons, borders, corners, and a body. Depending on the role of your form, you may want to design forms that present differing characteristics, even if these forms belong to the same database. For example, while one form presents a normal title bar, you may want another form not to present a title bar at all. While you may allow the user to be able to minimize or maximize a form, you may want to present one or both of these actions for the user. As an application design environment, Microsoft Access provides most of the features you will need for a regular and even advanced database product.

Practical Learning: Introducing Details of Form Design


1. From the resources that accompany this ebook, copy the Video Collection1 database and paste it in your Exercises folder 2. Open the Video Collection1 database 3. To create a new form, on the main menu, click Insert -> Form 4. In the New Form dialog box, click Form Wizard to select it. In the bottom combo box, select Videos and click OK

5. In the first page of the wizard, click the select all button
7. In the third page of the wizard, click Standard and click Next

and click Next

6. In the second page, make sure the Columnar radio button is selected and click Next 8. In the fourth page, accept the suggested name as Videos and click Finish 9. After viewing the form, close it 10. In the Database window, click Forms. To create a new form, on the Database toolbar, click the arrow of the New Object button and click Form 11. In the New Form dialog box, click Design View. In the bottom combo box, select Actors and click OK 12. Save the form as Actors 13. Open the Bethesda Car Rental1 database and, in the Database window, click the Forms button 14. To create a new form, on the main menu, click Insert -> Form 15. In the New Form dialog box, make sure nothing is selected in the combo box and doubleclick Design View 16. Save the form as About and close it

Form Automatic Centering


If you either create a new form or modify the design of an existing form, when you save it, Microsoft Access saves the position of the form then would remember and restore that position the next time you reopen the form. Alternatively, you can ask Microsoft Access to position the form in the center of the screen the next time you open the form, even if it was on one corner of the screen when you saved.

278

To center the form by default whenever it comes, set its Auto Center Boolean property to Yes.

The System Menu


As we have seen so far, the top section of a form is its title bar. It displays an icon on the left side. The system icon is fixed and you should not spend time trying to change it. As mentioned already, the system icon holds a menu that allows the user to perform the regular operations of a Windows container, including minimizing, maximizing, restoring or closing the window. To display this menu, the user can click the forms system icon:

The presence of the forms system icon is partly controlled by the Control Box property of a form. In most cases, you should make this system icon and its menu available to the user. If for some strange reason you do not want to provide this functionality, set the Control Box property to No. The form would appear as follows:

If you decide to do this, make sure you provide the user with the ability to close the form and this type of title bar makes it impossible. Of course, a user may know that the form can be closed by clicking the Close menu item under the File group of the main menu or by pressing Ctrl+F4.

The Title Bar


The middle section of the title bar is actually referred to as the title bar. It can be used to change the view of the form after right-clicking it. The title bar uses a color set in the Advanced Appearance of Control Panel as Active Title Bar:

279

Since you cannot control and cannot predict how your users will modify their system colors (because most users are free to set their system colors as they wish, even when they work corporate), you should refrain from changing this color when designing your forms, especially if you plan to distribute your product. Otherwise, the result you see on your form may be different from your users computers (and this can invite trouble with users telephone calls asking you why Leonie's form appears with a different color than mine; what did I do to deserve this? Why does everybody hate me?). When designing your forms, try to keep colors to their default and to their minimum. In this lesson, we are showing most options simply to let you know that they exist, not because you should or must use them.

Practical Learning: Using the Forms Title Bar


1. Open the Video Collection1 database
2. On the Database window, in the Forms section, right-click the Videos form and click Design View

3. Double-click the button at the intersection of both rulers

to open the forms Properties window. In Properties window, click the Format property page and click Caption

4. Type Video Collection Video Details and press Enter. If you are using Microsoft Access 2000 and above, click the Other tab of the Properties window. Click the arrow of the Allow Design Changes combo box and select Design View Only 5. Switch to Form View to preview the form 6. Save and close the form

7. Right-click the Actors form and click Design View


8. In Properties window, click the Format tab and click Caption

9. Type Video Collection Actors/Actresses and press Enter


10. Save and close the form

11. Open the Bethesda Car Rental1 database


12. In the Database window, right-click the About form and click Design View

13. In the Format tab of the Properties window, click Caption.


Type About Bethesda Car Rental and press Enter

280

14. Save and close the form

The System Buttons


The right side of the forms title bar displays three system buttons , or , . The group of these buttons is called the Control Box. If you do not want these system buttons at all, access the Properties window of the form and set the Control Box Boolean property to No from its Yes default value. In this case, the form would appear with neither the system icon nor the system buttons as seen above. Once again, if you do this, make sure the user has a way to close the form. Instead of completely hiding all system buttons of a form, you can specify which ones to display and thus control the ability to close, minimize, or maximize the form. The presence and/or the role of the system buttons is (partly) controlled by the Control Box and the Min Max Buttons properties. When the Control Box property is set to No, regardless of the value of the Min Max Buttons property, there would be no system buttons on the title bar (this is also something you learn if you do Windows GUI programming, like Win32). Therefore, in order to control the appearance and behavior of the system buttons, the Control Box property must be set to Yes. The values of the Min Max Buttons produce the following results: Min Max Buttons None Min Enabled Max Enabled Both Enabled Result System Buttons Minimize Maximize Hidden Enabled Disabled Enabled Hidden Close Consequence

Available The form can only be closed The form can be minimized or closed but not maximized The form cannot be minimized but can be maximized

Disabled Available Enabled Available

All operations (minimize, Enabled Available maximize, restore, and close) are allowed

Depending on the role and probably the number of Windows controls on a form, you will decide what button to allow or not.

Practical Learning: Configuring the Forms System Buttons


1. Open the Video Collection1 database
2. Forms section of the Database window, right-click the Videos form and click Design View 3. In the Properties window, click the Min Max Buttons field. Click its arrow and select Min Enabled 4. Switch to Form View to preview the form and try to maximize the form 5. Save and close the form 6. Right-click the Actors form and click Design View 7. In the Format tab of the Properties window, double-click Min Max Buttons a few times (2) until it displays Min Enabled 8. Save and close the form

The Forms Borders


Whether you allow the system icon and system buttons or not, the user needs to be able to know where a form starts and where it ends. This is seen by the borders of the form. In most cases, you will not be concerned with this aspect. Otherwise, you can control the borders of a form. The borders of a form are controlled using the Border Style property. If you set it to None,

281

the form would appear without borders:

The Form's Width


A form displays on the screen using its dimensions. These are the width and height. The form itself controls only the width. The height is controlled by its sections. To change the width of a form, in the Properties window, type the desired decimal value in the Width field of the Format property page. You can also change the form's width by dragging the right border of one of its sections.

Practical Learning: Setting the Forms Width


1. Open the Actors form in Design View and, in the Properties Window, click the Format tab 2. Click Width. Type 5.72 and press Enter
3. Save and close the form 4. In the Forms section of the Database window, right-click the Actors form and click Design View

5. Position the mouse on the right border of the Detail section until the mouse cursor turns
into a cross with two horizontal arrows:

6. Click and drag in the left direction until the vertical line is positioned at 31/2

7. Release the mouse

282

8. Save and close the form

The Detail Section


The most obvious part of a form is an area called Detail. This section starts on a bar labeled Detail and ends at the bottom unless a new section starts. The Detail section serves as the main host of other controls. It can also serve to display messages of various kinds. The Detail section can be enhanced by manipulating its properties. These properties are not necessarily related to the parent form but can be used conjointly with it. During our first design experience of forms, we learned that the form itself controls its width. The vertical dimension of a form is controlled by its sections. This means that a section, such as the Detail section, can "decide" how much height it needs to accommodate its content. The vertical measurement of the Detail section is controlled by the Height property. There are two main ways you can change the Detail section's height at design time: In the Format tab of the Properties window, you can change the value of the Height field. The value must be a natural or a decimal number. In reality it is a decimal number. If you type a natural number, also called an integer, it would be converted to decimal. If you type an invalid number, you would receive an error You can position your mouse in the lower border of the Detail section until the mouse cursor changes into a vertical double arrow. Then click and drag. You can drag up to shrink the section or drag down to heighten it

Practical Learning: Using the Detail Section of a Form


1. Open the Videos form in Design View and double-click an empty area under the Detail bar 2. On the Properties window, click the Format tab. Click Height and type 2.75 3. Click the Back Color field and click its ellipsis button 4. In the Color dialog box, click the Define Custom Colors >> button. Set the color to Red = 255, Green = 232, and Blue = 200 5. Click OK 6. While the new color has been set, click Back Color to select the color and press Ctrl + C 7. Switch to Form View to preview the form 8. Save the form and close it 9. Open the Actors form in Design View and click the Detail bar 10. In the Format tab of the Properties window, click Back Color. Press Ctrl + V and press Enter 11. Switch to Form View to preview the form 12. Save and close the form

The Header and Footer Sections


Besides the Detail section, a form can be enhanced with one or two more sections: Header and

283

Footer. By default, the Header and Footer sections are created on a form if you use the Form Wizard. To add the Header and Footer sections on a form that doesn't have them, you can use the menu bar where you would click View -> Form Header/Footer. Probably the fastest way to add these sections is by right-clicking anywhere on the form and clicking Form Header/Footer. If the form already has these sections but they don't contain anything, they would be removed. If the form already has these sections and they contain anything, you would receive a warning:

If you still want to delete the Header and Footer sections, you can click Yes; this would unrecoverably delete their content. Like the Detail section, the Header and Footer sections control their own height, which you can change the same way we described above for the Detail section. This also applies for the Back Color property. The Special Effect property allows you to raise or sink a section.

Practical Learning: Designing the Header and Footer Sections


1. In the Database window, click Tables and click the Directors table to select it 2. On the Database toolbar, click the arrow of the New Object button and click Form 3. In the New Form dialog box, click Form Wizard. In the bottom combo box, make sure the Directors table is selected and click OK 4. In the first page of the wizard, click the select all button and click Next. In the second page of the wizard, make sure the Columnar radio button is selected and click Next. In the third page, click Standard and click Next. In the fourth page, accept the suggested name as Directors and click Finish 5. Switch the form to Design View and notice that the form displays a Form Header and a Form Footer bars

6. To change the height of the Form Header section, position the mouse between the Form
Header and the Detail bars until the mouse cursor turns into a cross with two vertical arrows

7. Click and drag down until the horizontal line is positioned between the first and the
second marks

284

8. Release the mouse

9. To heighten the Form Footer section, position the mouse on the lower border of the Form
Footer bar

10. Drag down until the horizontal line is positioned on the third mark and release the mouse

11. Save and close the form 12. From the Forms section of the Database window, right-click Actors and click Design View 13. To add the other sections, on the main menu, click View -> Form Header/Footer 14. Click the section between the Form Header and Detail bars. Notice that the Header bar has been clicked to show that it is selected 15. On the Properties window, click the Format tab and click Height, type .385 16. Click Back Color and click its ellipsis button 17. Click Define Custom Color >>. Change the color values as follows: Red = 240, Green =

285

140, and Blue = 0 18. Click OK 19. On the Format property page of the Properties window, click Special Effect 20. Click the arrow of the Special Effect combo box and select Raised 21. Click the Form Footer bar to select its section 22. On the Format tab of the Properties window, change the Height value to .345 and press Enter 23. On the Formatting toolbar, click the arrow of the Fill/Back Color button and click the Brown color (1st row - 2nd column)

24. On the Formatting toolbar, click the arrow of the Special Effect button and select Raised
25. Switch to Form View to preview the form

26. Save the form and close it 27. Open the Bethesda Car Rental1 database 28. From the Forms section of the Database window, right-click the About form and click Design View 29. To add the sections to the form, right-click anywhere on the form and click Form Header/Footer 30. Save and close the form

Record Selectors

286

The Record Selector is a vertical bar on the left side of a form. It allows the user to select all of the fields contents of one or more records and copy them to the clipboard. Such a selection can then be pasted to another record, other records, or to a text or another type of file (for example you can paste the record in Notepad, Microsoft Word, Microsoft Excel, or any text file). There are two reasons you would use record selectors on a form. If you want the user to be able to access all fields of a record as a whole, make sure that the form is equipped with record selectors. In the same way, you can hide the scroll bar if the user would not need them. Another reason you would use a record selector is for aesthetic reasons. Most of the time, if designing a form for data entry, you would mostly allow the presence of record selectors. If you are designing a dialog box that would display the same content all the time, you should not allow the record selectors. The presence or absence of record selectors is controlled by the Boolean Record Selectors property field. If you set the field value to Yes, the form would display the record selector. Setting the field value to No would hide the record selectors.

Practical Learning: Toggling the Record Selectors


1. Open the Bethesda Car Rental1 database 2. In the Forms section of the Database window, right-click the About form and click Design View 3. In the Properties window, click the Format tab. Double-click Record Selectors to change its value to No (from its default Yes) 4. Switch to Form View to preview the form 5. Save and close the form

The Form's Scroll Bars


As much as you can, you should design your (non-Datasheet) form to display all of the fields of a record whenever the/a record comes up. Sometimes this will not be possible. If a form possesses too many fields for each record, Microsoft Access would equip the form with one or two scroll bars. A scroll bar allows the user to scroll from one side of the form to another. The vertical scroll bar is used to scroll up and down while the horizontal scroll allows scrolling left and right. By default, scroll bars come up if the form "judges" that some fields are hidden. The presence of scroll bars allows the user to be aware of hidden fields. Depending on your design, you can control the appearance or disappearance of the scroll bars. To do this, change the value of the Scroll Bars field in the Format property page of the Properties window. There are four possible values. To display only the vertical scroll bar, set the value to Vertical Only. In the same way, you can display only the vertical scroll bar by selecting Horizontal Only. On the other hand, you can display both scroll bars by setting the value to Both. If for some reason you don't want any scroll bar, set the Scroll Bars property value to Neither.

Practical Learning: Configuring a Forms Scroll Bars


1. The Bethesda Car Rental1 database should still be opened. In the Forms section of the Database window, double-click the Customers2 form to open it 2. Notice that the form displays a vertical scroll bar on the right side. Switch the form to Design View 3. In the Format tab of the Properties window, click Scroll Bars. Then click the arrow of the Scroll Bars combo box and select Neither 4. Switch to Form View to preview the form. Notice that, this time, the vertical scroll bar has disappeared 5. After viewing the form, save and close it

Navigation Buttons
287

When studying tables and during form's data entry, we found out that a form (also a table, a query, or a report) is equipped with some buttons on its lower section. These buttons allow the user to navigate back and forth between records. These buttons are very useful during data entry and data analysis. If you are creating a form that would display the same content all the time, such as a form that does not actually display records, you can hide the form navigation buttons. The presence or absence of navigation buttons is controlled by the Boolean Navigation Buttons property. When its value is set to Yes, the form would display the Navigation Buttons. To hide them, set the Navigation Buttons property value to No.

Practical Learning: Hiding the Navigation Buttons


1. In the Forms section of the Database window, double-click the About form to open it. Notice that it is equipped with navigation buttons 2. Switch the form to Design View 3. In the Format tab of the Properties window, double-click Navigation Buttons to change its value from Yes to No 4. Switch the form to Form View to preview it. Notice the absence of navigation buttons 5. After viewing the form, save and close it

Dividing Lines
A form is equipped with special horizontal lines used to visually separate sections of a form. They do not perform any other special function. They can be useful on a continuous form. To equip a form with dividing lines, add a header and a footer sections. On the other hand, if you create a form that is directly equipped with a header and a footer sections, it would display the dividing lines. The presence or absence of the horizontal lines is controlled by the Boolean Dividing Lines property. Its default value is Yes, which means that the dividing horizontal lines would display on the form. To hide both lines, you can set its value to No. To hide an individual line, you can completely reduce its section.

Practical Learning: Using Dividing Lines


1. From the Forms section of the Database window, double-click the About form to open it. 2. Switch it to Design View. If it is not equipped with Form Header and Form Footer bars, right-click anywhere on the form and click Form Header/Footer. Switch it back to Form View 3. Notice that it is equipped with horizontal dividing lines

4. Switch the form to Design View 5. To remove the line that divides the Form Header and the Detail sections, click the Form Header bar 6. In the Format tab of the Properties window, click Height. Type 0 and press Enter

288

7. Switch the form to Form View to preview. On the main menu, click Window -> Size To Fit Form. Notice that, this time, the form displays only a lower dividing line. 8. Save and close the form

Dialog Boxes
Introduction
A dialog box is a rectangular object that is used to host or carry other controls without itselft being hosted by another object:

A dialog box is primarily characterized by two main features: its title bar and its body. The title bar, on top of the dialog box, has a title and the system close button (only, mostly). Although this is the classic appearance of a dialog box, it is not strictly exclusive. Some dialog boxes display the system icon. On the right side of the title bar, a classic dialog box displays only the system Close button made of X. Again, this is not exclusive. It is not unusual for a dialog box to display the minimize and the maximize/restore buttons but, according to Microsoft standards, a dialog box should appear as the one above: no system icon, only the system Close button, and a type of border referred to as Dialog Frame. To use a dialog box, the user must open it one way or another. Your job is to decide how and when the user will be able to open a dialog box. To create a dialog box in Microsoft Access, you start from a form and display it in Design View. To convert an existing form into a dialog box, set its Border Style property to Dialog. This reduces the system buttons to the Close button only. There are two types of dialog boxes: modal and modeless.

Practical Learning: Creating a Modal Dialog Box


1. The Bethesda Car Rental1 database should still be selected. On the Database window, double-click the About form to open it 2. After viewing it, switch it to Design View 3. In the Format tab of the Properties window, click Border Style. Then click the arrow of the Border Style field and select Dialog 4. Switch it to Form View to preview 5. Save and close the form 6. To create a new form, in the Forms section of the Database Window, click New 7. In the New Form dialog box, make sure the bottom combo box is empty and double-click Design View

8. Save the form as RentalRates


9. On the Properties window, click the Format tab and click Caption 10. Type Bethesda Car Rental - Rental Rates and press Enter 11. Click Width. Type 3.875 and press Enter

12. To make this form a dialog box, in the Format tab of the Properties window, change the
following properties:

289

Record Selectors = No Navigation Buttons = No Dividing Lines = No Border Style = Dialog 13. Click the Detail bar to select it. Then, in the Format tab of the Properties window, click Height. Type 1.875 and press Enter 14. Preview, save, and close the form

Modal Dialog Boxes


A dialog box is characterized as modal if the user must close it before continuing with another task on the same application. The Date and Time dialog box of WordPad is an example of a modal dialog box: if opened, the user must close it in order to continue using WordPad. In order to use a dialog box in your application, you should analyze a scenario and define if the dialog box is necessary. Use a dialog box if you want the user to first terminate whatever task she would be performing. For example, if a user is performing a payment of an order processing, it is natural to process and finish that payment before starting another task. A classic (or normal) dialog box would need neither a Record Selectors bar nor the record navigation buttons. Therefore, you should decide how the dialog box would be used. If you want a regular dialog box as defined by the Microsoft standards, you should set the Record Selectors, the Navigation Buttons and the Dividing Lines properties to No each.

Practical Learning: Creating a Modal Dialog Box


1. The Bethesda Car Rental1 database should still be opened. Open the About dialog box in Design View 2. On the Properties window, click the Other tab 3. Double-click Modal to change its value from No to Yes 4. Switch the dialog box to Form View to preview 5. Try clicking the Forms button of the Database window. Notice that the dialog box is modal 6. To save it, press Ctrl + S. Then close the About dialog box

Modeless Dialog Boxes


A dialog box is referred to as modeless if the user doesn't have to close it in order to continue using the application that owns the dialog box:

290

The Find dialog box of WordPad (also the Find dialog box of most applications) is an example of a modeless dialog box. If it is opened, the user doesn't have to close in order to use the application or the document in the background. Since the modeless dialog box doesn't display its button on the task bar, the user should know that the dialog box is opened. To make the presence of a modeless dialog box obvious to the user, it typically displays on top of its host application until the user closes it. To create a modeless dialog box, or to convert a form into a modeless dialog box, when in Design View, set the Popup property to Yes. This makes sure that the user can work on another form and the modeless dialog box or form would remain on top of any other form of the database.

Practical Learning: Creating a Modeless Dialog Box


1. The Bethesda Car Rental1 database should still be opened. Open the RentalRates form in Design View. If you did not design your own RentalRates form, use the RentalRates1 2. To make it a modeless dialog box, in the Other tab of the Properties window, double-click Pop Up to change its value from No to Yes 3. Save and close the RentalRates dialog box 4. Open the OrderProcessing form. Without closing it, from the Database window, doubleclick the RentalRates dialog box to open it 5. Move the OrderProcessing form around and notice that it is always behind the Rental Rates dialog box 6. Close the OrderProcessing form and close the Rental Rates dialog box

Exercises
Watts A loan
1. Open the Watts A Loan database and open the Customers form in Design View.
Disable the Maximize button on the form and set its Caption to Watts A Loan - Customers Account Information Make the form center when it comes up Add the Form Header and Footer sections Raise the Form Header and the Form Footer sections. Change the Form Header's background color to Gray 50%. Set the Form Footer's background color to Gray 80%

291

2. Use the same features to configure the employees form but set its Caption to
Watts A Loan - Employees Records Design the other forms accordingly

3.

Yugo National Bank


292

Open the Yugo National Bank Make all forms center themselves when they appear Add a Form Header and a Form Footer to all forms Disable the Maximize buttons on the Customers and the Employees forms Give a Dialog Border Style to the AccountTypes, the ChargeReasons, and the TransactionTypes forms Make the ChargeReasons form Modal

293

Overview of Windows Controls


Text-Based Controls: The Label
Introduction
A label is a control that serves as a guide to the user. It provides a static text that the user cannot change but can read to get information about another control on the form. You can also use it to display simple information to the user. Most controls on the form are not explicit at first glance and the user would not know what they are. Therefore, you can assign a label to the control as a help to the user. To add a label to a form, on the Toolbox, click Label and click on the form or report. Type the text that the label will display and press Enter (as we will see, most controls add their own label to the form).

Properties of a Label
Probably the most important and the most obvious characteristic of a label is the text it is displaying. The text is the label's Caption. If you click the Label on the Toolbox and click on the form, you must first define its caption. If a label already has a caption, there are various ways you can edit it. For example, use the same techniques we reviewed for editing text-based properties. On the other hand, to edit the caption of a label, on the form, click inside the label. That would put it into edit mode and you can edit it as you wish. The appearance of a label is visibly controlled by its font characteristics. The Font name, also called its face, is the name of the font as defined by the operating system. We saw that there are various ways you can define the font characteristics of a control like the label. The

294

Formatting toolbar is equipped with appropriate combo boxes and buttons. These characteristics can also be modified using their corresponding properties from the Properties window. The dimensions of a label control its Width and Height. Although the dimensions are closely related to the font characteristics, they can be independently defined. There are two main ways you can resize a label, which is equivalent to changing its dimensions. To set your own dimensions, in the Format tab of the Properties window of the label, change the values of the Width and Height properties. Unless you plan to show the background color of a label, probably the best way to resize a label is to make it adjust to the dimensions depending on the font size and the total characters width. To do this, position the mouse on one of the label's handle and double-click. The label's width and height would be set to accommodate its caption. The position of a label is controlled by its Top and Left properties. The Top property defines the measure from the top left corner of the section where the label is positioned, to the top left corner of the label itself. There are two main ways you can set the position of a label. On the Properties window, you can change the values of the Top and Left properties. On the other hand, you can place your mouse on the top left corner of the label until the mouse pointer turns into a pointing finger. Then click and drag in the desired direction.

Practical Learning: Designing Labels


1. Open the Video Collection1 database 2. From the Forms section of the Database window, right-click the Videos1 form and click Design View

3. From the Toolbox, click Label

and click in the top left section under the Header bar.

4. Type Video Collection Video Details and press Enter 5. While the new label is still selected, on the Formatting toolbar, click the arrow of the Font
combo box and select Garamond

6. Click the arrow of the Font Size combo box and select 20 7. Click the Bold button 8. Click the arrow of the Font/Fore Color button and click Yellow (column 3 - row 4).
9. To resize the label, position the mouse on one of the handles surrounding the label and double-click 10. To reposition the label, on the Format property page of the Properties window, click Left, type 0.25 and press Enter

11. Change the value of the Top property to 0.040


12. While the label is still selected, on the Properties window, click the Other tab

13. Click Name, type lblMainTitle and press Enter


14. Click anywhere on the form (to deselect the label) 15. Right-click the Video Collection label and click Copy 16. Right-click anywhere in the same Form Header section and click Paste 17. While the new label is still selected, on the Properties window, click the All tab

18. Click Name and type lblShadowTitle 19. Click Left and type 0.29 20. Click Top and type 0.075 and press Enter 21. On the Formatting toolbar, click the arrow of Font/Fore Color and click Dark Red (1st 295

column - 2nd row). 22. On the Object combo box of the Formatting toolbar, select lblMainTitle and notice that it is selected on the form 23. On the main menu, click Format -> Bring To Front 24. Drag the top border of the Detail bar up completely to shrink the Form Header section until you cannot drag up anymore 25. Before leaving, in the Form Header section, draw a fake line that touches both labels to select them. Then press Ctrl + C to copy 26. To preview the form, on the Form View toolbar, click the View button 27. On the menu bar, click Window -> Size To Fit Form:

28. Close the form. When asked to save the form, click Yes. 29. On the Database Window, right-click the Actors1 form and click Design View 30. Right-click the area under the Form Header bar and click Paste 31. While both labels are still selected, in the Properties window, click the Format tab. Change or edit the value of Caption to display Video Collection Actors/Actresses and press Enter 32. Double-click one of the handles of the labels to resize them 33. Preview, save and close the form

Text-Based Controls: The Text Box


Introduction
A text box is a Windows control used to get or display text for the users interaction. At its most regular use, a text box serves as a place to fill out and provide information. You can also use it only to display a text without allowing the user to change its content. Like most other controls, the role of an edit box is not obvious at first glance; that is why it should be accompanied by a label that defines its purpose. From the users standpoint, a text box is named after the label closer to it. Such a label is usually on the left or the top side of the corresponding edit box. There are two main ways you can add a text box to a form: From the Toolbox, you can click the Text Box control and click on a section of the form. Unless you have a good alternate reason, most of your text boxes will be placed in the Detail section. Some text boxes used in expressions can be placed in another section. By default, placing a text box on the form also adds a corresponding label to its left. If you drag a text-based field from the Field List and drop it on the form, the field would place a text box and its corresponding label.

Properties of a Text Box


296

Like every control on a form, the dimensions of the text box are controlled by its Width and Height properties. The position of a text box is controlled by its Top and Left properties. To make a text box read-only, that is, if you don't want the user to enter text in an edit box, there are various alternatives. If you change the Enabled property from Yes to No, the text box would have a gray background and cannot receive focus. If you set the Locked property from No to Yes, the control would appear with a normal (white) background. The Special Effects of the text box are expanded as compared to those available on a label. Besides the ability to raise or sink a text box, you can give it a thick, etched, or shadow border. After adding a text box on a form, you can configure it to receive its data from an existing table. This can be done after the Record Source of a form has been defined. To link a text box to the object that is the Record Source of a form, click the arrow of its Record Source combo box and select the desired field.

Practical Learning: Designing Text Boxes


1. In the Forms section of the Database window, right-click the Actors form and click Design View 2. On the form, click the Actor text box

3. On the Formatting toolbar, click the arrow of the Special Effect button and click Special
Effect: Shadowed 4. Preview, save and close the form

The Command Buttons


Introduction
A command button is a rectangular object that allows the user to dismiss a dialog box or to initiate an action. This is done through a decision making process based on what a form or a dialog box is displaying. This could be an acknowledgement, such as a form displaying a simple message to the user. A user could also be asked to choose one button from a group of buttons on a form or a dialog box. To use a button, the user position his mouse pointer on the desired button and presses the left button. This action is referred to as clicking. Depending on how the button is implemented, it should be obvious to the user what to do with it. To indicate what a button is used for or what action it would lead to, a button can display a string on its top. This string is also referred to as the button's caption. The caption should be explicit enough to let the user know what the button is used for. A caption like OK usually means the user accepts what message the form or dialog box is displaying. A caption like Cancel is usually accompanied by another OK button on the form. When a button has a Cancel button, the user would usually click it as if saying, "Never Mind" or "I change my mind", etc. To create a button, you can click the Command Button control on the Toolbox and click on the desired section of the form. On the Toolbox, if the Control Wizard button was down or clicked, the Command Button Wizard would start to help you create a fully functional button. If you do not want to use the wizard, you can click Cancel on the first page of the Command Button Wizard. Also, if you do not want to use the wizard, on the Toolbox, you can click the Control Wizards button to have it up.

Practical Learning: Creating Command Buttons


1. Open the Bethesda Car Rental1 database 2. From the Forms section of the Database window, double-click the About1 dialog box to open it

297

3. After viewing the dialog box, switch it to Design View 4. On the Toolbox, after making sure that the Control Wizard button is down , click the Command Button control and click the empty area in the Form Footer section on the right side of the warning label 5. On the first page of the Command Button Wizard, in the Categories list, click Form Operations 6. In the Actions list, click Close Form 7. Click Next 8. On the second page, replace the content of the Text edit box with OK (and make sure the Text radio button has been selected) and click Next 9. Change the name of the button to cmdOK and click Finish 10. Resize the button as you see fit 11. Preview the dialog box:

12. Save the form. To close it, click OK

Characteristics of Command Buttons


Like all other visual controls, a command button has a Name property, a location (Left and Top), and dimensions (Width and Height). Because of their anticipated behavior, command buttons are the most commonly used object to initiate an action. As such, they are used to open other forms, reports of the same database, or simply to display a message box. As we saw in the second page of the wizard, a command button in Microsoft Access can display either a string or a (small) picture on top. Microsoft Access ships with dozens of pictures you can use, especially made for buttons. If none of these pictures suits your need, you can design your own. To display a picture on a button, after selecting in Design View, click the ellipsis button of the Picture field in the Format tab of the Properties window, locate the picture, and select it. When a dialog box is equipped with an OK and a Cancel button, it is suggested that the user be able to press Enter to perform the same action as if he had clicked OK. To apply this behavior,

298

if you create a button and give it an OK Caption, you can set its Default property to Yes. It is also suggested that, if a button has a Cancel Caption, the user should be able to press Esc and produce the same behavior as if the Cancel button was clicked. To apply this feature, after creating the button with a Cancel caption, set its Cancel property to Yes. Never set the Default and the Cancel properties both to Yes for the same button.

Practical Learning: Configuring Command Buttons


1. The Bethesda Car Rental1 database should still be opened. From the Forms section of the Database window, right-click the About1 dialog box and click Design View 2. On the form, click the OK button to select it. In the Properties window, click the Other tab and double-click Default to change its value from No to Yes 3. Save and preview the dialog box 4. To close, press Enter

Combo and List Boxes


Introduction to Combo Boxes
A combo box is a Windows control made of two parts: a text portion and a list. A text box is used to display a selection made from a list of items. On the right side of the text box, there is a down-pointing arrow that allows the user to know that the control holds a list. The user displays the list by clicking the arrow. To use a combo box, the most basic operation the user can perform is to click the arrow and select an item. Once an item is selected, the list retracts back like a plastic. There are various ways you can add a combo box to a form (or report). This is done the same way we did with the table: using the Lookup Wizard.

Practical Learning: Creating a Combo Box


1. Open Video Collection1 database and open the Videos2 form 2. After previewing it, to switch it to Design View, on the Form View toolbar, click the View button 3. On the toolbox, make sure the Control Wizard button is clicked 4. On the Toolbox, click the Combo Box button 5. On the form, click between the Title and the Year text boxes:

6. On the Combo Box Wizard dialog box, make sure the first radio button is selected and click Next

299

7. In the list of tables, click Directors and click Next 8. From the Availability Fields list, double-click Director and click Next 9. Make sure the Hide Key Column check box is checked and click Next 10. Click the arrow of the combo box and select DirectorID

11. Click Next 12. For the label of the combo box, type Director to replace the suggested label and click Finish 13. Save the form and switch it to Form to preview it 14. After viewing the form, switch it back to Design View

Introduction to List Boxes


A list box presents a list of items to the user. The list appears as a taller text box. The items in the list appear each on its own line. The user makes her selection by clicking in the list. Once an item is clicked, it becomes highlighted indicating that it is the current choice:

Probably the easiest way to create a list is by using the List Box Wizard. This allows you to select the source of data, which would be a table or a query. Then you can select the column that would be displayed as the value of the list box, exactly as done for the combo box.

Practical Learning: Creating a List Box


1. The Video Collection1 database should still be opened with the Videos1 form in Design View. On the Toolbox, make sure the Control Wizard button is clicked 2. On the Toolbox, click the List Box button 3. On the form, click on the right side of the DirectorID combo box 4. On the first page of the List Box Wizard, click the second radio button and click Next

300

5. Click the empty field under Col1 and type G 6. Press Tab and type PG 7. Complete the list with the following options: PG-13, R, NC-17, X, and N/R

8. Click Next 9. Click the arrow of the combo box and select Rating 10. Click Next 11. For the label, type Rating and press Enter 12. Save, preview, and close the form

Properties of Combo and List Boxes


The combo box is one of the highly praised features of Microsoft Access. As the application makes it particular easy to create, it performs all necessary basic behind-the-scene jobs. The Combo Box Wizard, used to create a bound combo box, is able to reconcile a relationship between the primary key of the parent table that holds the actual data to display, and the selected foreign key that exists on the table that host the foreign key. After creating the combo box, especially if you used to wizard to configure it, you can check and adjust the characteristics as you see fit. Like every control, a combo box uses a name that allows you, the database application, or the operating system to identify it. If you create a combo box by dragging, from the Field List, a field whose lookup features have already been configured, the control would receive the same name as the tables column. If you create a combo box using the Combo Box Wizard, the control would receive a name that starts with Combo. An example would be Combo21. If you do not intend to refer to the combo box in an expression, you would not need to pay attention to the name of the control. Otherwise, if you create various controls using wizards, the names might become confusing. In this case it would be a good idea to change the name of the combo box. Like all others, to change the name of a control, access its Properties window and, from the Other or the All table, change the value of the Name property. When we think of a list box, we usually assume that it is made of one column of items. A list box can be made of various columns. In this case, it is sometimes called a list view:

Most of the time, when a multi-column list displays, the user may not be able to identify the items under each column. In this case, you can display a column header on its column. This

301

column

header

would

display

label

that

categorizes

the

items

under

it.

One of the main reasons for using a combo or a list box is to provide a list of items to the user. Sometimes the list would be very large. If the list is long, the control would provide a vertical scroll bar that allows the user to navigate up and down to access all items of the list. The database developer decides how many items to display in the list.

Practical Learning: Configuring a Combo Box


1. Open the Bethesda Car Rental1 database 2. In the Forms section of the Database window, double-click the RentalRates form to open it. If you do not have it, open the RentalRates1 form 3. After viewing the form, switch it to Design View 4. On the Toolbox, make sure the Control Wizard button is down To create a list box, on the Toolbox, click the List Box button and, on the form, cl under Detail on the top-left section 5. On the first page of the List Box Wizard, make sure the first radio button is selected and click Next 6. In the list of tables, click Car Categories and click Next 7. In the Available Fields list, click the select all button and click Next

8. Make sure the Hide Key Column check box is checked and click Next 9. Change the label to Rental Rate by Category and click Finish 10. Preview the form in Form View and switch it back to Design View 11. On the form, click the list box to select it 12. On the Properties window, click the All tab. Click Name. Type lstRentalRates and press Enter 13. Set the Column Heads property to Yes 14. Change the Column Widths as follows: 0;0.875;0.85;0.85;0.85;0.85 15. Resize the list box control and the form appropriately

302

16. Save and preview the form 17. Close the form

Radio Buttons
Introduction
A radio button is a Windows control made of a round box O. In practical usage, a radio button is usually (if not always) accompanied by other radio buttons. In other words, radio buttons come as a group. The user makes his or her decision by selecting or clicking one of the round boxes. Once clicked, the round box is partially filled with a dot. When one button in the group is selected, the other round boxes of the (same) group are empty O. The user can select another button by clicking a different choice, which empties the previous selection. This technique of selecting is referred to as mutually-exclusive. There are two main ways you add a radio button to your form or report. While in Design View, if you add an Option Group control to a window while the Control Wizard button is down, the Option Group Wizard would start, allowing you to create a list of items where each item would be later converted into a radio button. If the radio button must be linked to a column of the data source, you will need to specify it. Such a column should have a natural number as data type (Byte, Integer, Long Integer).

Practical Learning: Adding Radio Buttons


1. Open the Danilo Pizza1 database 2. From the Forms section of the Database window, double-click the CustomersOrders form to open it

3. After viewing the form, switch it to Design View 4. On the Toolbox, make sure that the Control Wizards button is down . Click the Option Group control 5. On the form, click under the Processed By label 6. On the first page of the option Group Wizard dialog box, click the empty box under Label Names and type Small 7. Press the down arrow key and type Medium 8. Press the down arrow key, type Large

303

9. Click Next 10. To set the default choice, click the arrow of the combo box and select Medium 11. Click Next

12. Accept the values suggested for the option buttons and click Next 13. Click the arrow of the combo box and select PizzaSizeID because the option button selected will be held by, or carried by, or stored in, the PizzaSizeID foreign key

14. Click Next

304

15. Accept to have the Options Buttons with an Etched border. Click Next 16. Change the Caption suggested to Pizza Size and click Finish

Properties of Radio Buttons


Because the round box of a radio button does not indicate what it is used for, it is usually (if not always) accompanied by a label. The label can be positioned anywhere (to the left, the top, the right, the bottom side) close to the round box but it is usually positioned to the left or the right side. To move or position the round box, click it to select it. Then position your mouse on it to get a pointing finger arrow and drag in the desired direction:

Like most (if not all) other controls, when you include a radio button, Microsoft Access adds a label to the control. If you do not like the string displayed by the label, you can click it twice to put it into edit mode and change the string.

Practical Learning: Configuring Radio Buttons


1. The Danilo Pizza database should still be opened with the CustomersOrders form in Design View. On the form, click an unoccupied area to make sure nothing is selected. Click the border of the newly added Group Box (the line that surrounds the group and touches the Pizza Size label) to select the frame 2. In the Properties window, click the All tab and click Name. Type fraPizzaSize and press Enter 3. Enlarge the border of the option group to include the text boxes that correspond to the option buttons 4. Save and preview the form

305

5. Switch it back to Design View

Check Boxes
Introduction
A check box is a control that allows the user to validate or invalidate an option. A check box appears as a little square box . The user makes his or her decision by clicking in the square, which toggles a check mark R. Toggling means, that if the square box were empty , after clicking it, a check mark would appear in it R:

Although it can appear by itself, a check box can come in a group with others, allowing the user to select as many choices as are available, as opposed to radio buttons where only one in the group can be selected

Check boxes provide a non-exclusive choice, which means that if they come as a group, each can behave independently with regards to the other check boxes of the same group. Therefore you can create check boxes anywhere on the form. It is recommended that, when they act as an ensemble, you should include check boxes in a group so their belonging to the same group would be obvious to the user.

Practical Learning: Adding a Check Box


1. The Danilo Pizza database should still be opened with the CustomersOrders form in Design View. On the Toolbox, click the Check Box control and click the group box under the Toppings label 2. While the new check box is still selected, in the Properties window, click the All tab and

306

click Name. Type txtPepperoni and press Enter 3. In the Control Source, select Pepperoni 4. On the form, click the label of the new check box. Click it again and edit its string to display Pepperoni 5. From the Field List, drag Sausage and drop it in the group box under the Toppings label 6. In the same way, drag the ExtraCheese, the Onions, and the Olives fields to the same group box 7. Using the techniques of control resizing and moving, complete the design of the controls 8. Save and preview the form

9. Close the form

Toggle Buttons
Introduction
A toggle button is a type of button that behaves like a check box. The first difference is that it displays like a command button but behaves like a check box. The second difference is that, while a check box should be accompanied by a label that indicates what the check box is used for, a toggle button, like the command button, can display a string on its face. To create a toggle button, you can click the Toggle Button control on the Toolbox and click the form. Like the check box and the radio buttons, there is no wizard to follow.

Properties of a Toggle Button


Configuring the toggle button is particularly easy. Like the check box, the toggle button should be used for a Boolean field. Therefore, after adding it to a form, in the Control Source of the toggle button, select the field that would carry or show its value.

Exercises
Yugo National Bank
1. Open the Yugo National Bank database
Open the Customers table in Design View. Insert a new field just under CustomerID. Name it Created By and set its Data Type to Lookup Wizard. In the Lookup Wizard, select the LastName and Title fields from the Employees table. Keep the label as Created By and delete 0 as the Default Value. Save and close the table

2. Open the Customers form in Design View and delete the AccountTypeID text box.
Use the Combo Box Wizard to create a field for the AccountTypeID column. Include the AccountType field from the AccountTypes table. Store its values in the AccountTypeID

307

field and set its label to Account Type. Change the Name of the combo box to cboAccountType Re-adjust the Tab Order then design the form as follows and save it before closing it:

3. Open the Customers table in Design View. To make sure that only employees who are

allowed to, can actually create new accounts, in the Lookup section of the EmployeeID field, open the SQL statement. Add the CanCreateNewAccount field and set its Criteria to be True but don't show it to the user

Save and close the table

4. Create and design a form based on the Transactions table. Save it as Transactions

Close the form

5. Open the Transactions form and perform a few transactions then close it 308

6. Using the Command Button Wizard, create a button used to close the form on each form
of the database. Set the caption of the button as Close and name it cmdClose

Watts A Loan
1. Open the Watts A Loan database.
Design a form based on the LoanProcessing table Use the Combo Box Wizard to create a field for the EmployeeID column. Include the LastName and the Title fields of the Employees table. Make sure its values are stored in the EmployeeID field and set its label to Processed By. Change the Name of the combo box to cboEmployee. Use the Combo Box Wizard to create a field for the CustomerID column. Include the AccountNumber and the LastName fields from the Customers table. Make sure its values are stored in the CustomerID field and set its label to Account Number By. Change the Name of the combo box to cboCustomer Use the Combo Box Wizard to create a field for the TypeOfLoanID column. Include the TypeOfLoan field from the TypesOfLoan table. Make sure its values are stored in the TypeOfLoanID field and set its label to Type of Loan. Change the Name of the combo box to cboTypeOfLoan Using the items from the Field List, complete the design of the form as follows:

Save and close the form 2. Create a title with a shadow label in the Form Header section of each form as follows:

309

3. Using the Command Button Wizard, create a button used to close the form on each form
of the database. Set the caption of the button as Close and name it cmdClose

Sectional and Tabbed Forms


310

Sectional Forms
Introduction to Form Breaks
Many databases are made of various objects and it is not unusual for one of these objects to contain various fields. If you try to create a form for such an object, you may encounter a big real estate deficiency. Even if you decide to reduce the amount of information on a table, because you still need to follow your customers goal, you may not have this complete liberty. Therefore, instead of deleting necessary fields, you can one of the various alternatives offered by Microsoft Access. When logistic becomes a problem for the amount of information you need to include in a form, you can divide the form into sections and allow the user to access only one section at a time, although still remaining in the same form. This is made possible by a special control called the Page Break.

Page Breaks
To create sections on a form, on the Toolbox, click the Page Break control and click on the left side inside the Detail section of a form. You can add as many sections as you want. To make the roles of your form sections efficient, they should have the same height. Otherwise, when you decide to display them, part of one section might appear in another section, which would deceive the purpose of creating sections.

Practical Learning: Dividing a Form in Sections


1. Open the Bethesda Car Rental1 database and, from the Forms section, double-click the Customers2 form to open it 2. After viewing the form, switch it to Design View

3. On the Toolbox, click the Page Break button and, on the form, click in the Detail section at
21/4 of the vertical ruler

4. From the Toolbox, click the Page Break button and, on the form, click in the Detail section at 4.5 of the vertical ruler

311

5. Save and close the form

Tabbed Forms
Introduction
Besides the page breaks you can use to divide a form, if you are designing a form for a long list of fields, you can group them in tabs. A tab control is an object that is used to hold other Windows controls. This control presents a tab button on its top section. This tab button should present a label that indicates what the tab is used for. Sometimes, a tab is also called a property page. The primary job of a tab control is to hold, host, or carry other controls. It can appear by itself. Here is an example:

In most cases, a tab control comes in a group with one or more others. In this case, each tab hosts or carries its own controls. Tabs are arranged in a 3-dimensional coordinate where the Zaxis moves from the computer screen towards you. In this scenario, tabs are positioned one in front of the other(s). To use a tab control, the user clicks a tab. The tab that was clicked comes in front and displays its children. The other tab(s) goes(go) to the back and hides(hide) its(their) child(ren). If there is more than one tab, all tabs display a labeled button on top. To change the list, the user simply clicks another tab and the scenario renews. Here is an example:

312

To create a tabbed form, while in Design View, on the Toolbox, click the Tab Control button and click the form

Practical Learning: Creating a Tabbed Form


1. The Bethesda Car Rental1 database should still be opened. From the Forms section, double-click the Customers1 form to open it 2. After viewing the form, switch it to Design View

3. On the Toolbox, click the Tab Control button


of the Detail section

and click somewhere in the top-left part

4. Save and preview the form 5. Switch it back to Design View

Characteristics of a Tab Control


By default, after adding a new tab control to a form, it is equipped with two property pages. Before manipulating a tab control, there are details you should keep in mind. In the programming world, we consider that a tab control is actually made of two objects presented as one. A tab sheet, also called a property sheet is like the desk of a table. If you listened to your teacher in primary or elementary school, you probably heard her saying over and over that you should/must not write on the desk of a table. This is also true here. In real life, every on a table is positioned on that table, like pieces of paper. On a tab sheet, the tab controls, also called property pages, are positioned on the tab sheet (in Microsoft Access, you cannot access the tab sheet, meaning you cannot place anything on it; in some programming environments, like Microsoft Visual C++, you can certainly access the property sheet). This discussion is intended to show you that there is a separation between the tab control and the area on which it lies. This makes it possible to move all tab controls with one movement. The tab sheet is a rectangle that surrounds the tab controls and holds them as their parent. To tab sheet is represented by the area on the right side of the tabs. To select that tab sheet, you

313

can click that area:

When the tab sheet is selected, you can see that its Name in the Properties window starts with TabCtlX. If you select the tab sheet and move it, the tab controls, also called property pages, on it would move also. If you delete the tab sheet, its property pages would be deleted also. For this reason, the tab sheet is considered their parent. As mentioned already, the tab controls you use are actually positioned on a tab sheet. Each tab control or property page is considered on its own and its only relationship with the other tabs is that they belong to the same sheet. Based on this, each tab can be accessed separately. To manipulate the properties of a tab page, you should select it first. To do that, click its label (not necessarily its body). By default, after adding a new tab control to a form, it is equipped with two tab pages. To add a new tab, you can right-click one of the tabs or the area of the tab sheet and click Insert Page. To remove a tab page, you can click its tab and press Delete. Alternatively, you can right-click a tab and click Delete Page. We stated that a tab control (property page) acts as a parent for other controls positioned on it. Based on its role, it should indicate its role. This is specified by its button, which displays a caption. Therefore, after adding a tab control, one of the first actions you probably should take is to specify its role. This is role by changing the value of its Caption in the Properties window. After you have typed a string for the Caption of a tab, its width is adjusted to accommodate its string. This is done for each tab. Consequently, one tab with a Resume Caption and another tab with Personal Information, as Caption, would have different widths. Alternatively, you can give the same width to all tabs regardless of their different lengths of strings. In this case, a tab with Resume and another with Personal Information labels would have the same width. To give the same width to the tabs, in the Format tab of the Properties window of the tab control (the property sheet itself), change the value of the Tab Fixed Width. The default value of 0 means that you let Microsoft Access determines the necessary width to contain the label on the tab. You can then change the value as you wish. In the same way, the Tab Fixed Height can be used to control the height of the tabs or buttons. You can display either or both a picture and a label on the tab. Although picture can be any size, you should limit it to 16x16 pixels. To add a picture to the button, select the tab. In the Properties window, click the Picture property and click its ellipsis button. Locate and select a picture. It should be a bitmap (with bmp extension) or an icon (with ico extension). By default, property pages display their labels on a tab. If you do not like the tab, you can use either a button or nothing. This property is called by the Style field in the Properties window of the tab sheet. Like the Tabs value, the Buttons property allows each property page to display a label that indicates its role. If you set the Style property to None, the property sheet would appear as a simple rectangular box and the user would not be able to change the pages. Therefore, if you decide to use this option, unless you want to hide the other pages, make sure you provide the user with the means of switching to a difference property page. Based on the role of the tab sheet, some properties of the tab sheet are also imposed on the tab pages. For example, on the Properties window, if you change the value of the Top or the

314

Left properties, the tab sheet moves and at the same time, the corresponding values of the tab pages are changed.

Practical Learning: Configuring Tab Controls


1. The Bethesda Car Rental1 database should still be opened with the Customers1 form in Design View. Click the empty gray section on the right side of the right Page tab to select the tab sheet and hold the mouse down 2. Drag it in the left direction 3. To add a new property page, right-click one of the Page buttons and click Insert Page 4. Double-click the most-left Page button. In the Properties window, click the Format property page and click Caption 5. Type Contact and press Enter 6. Click the middle Page button. In the Properties window, change the Caption to Drivers License 7. Click the most-right Page button. In the Properties window, change the Caption to Notes/Comments

8. Save and preview the form 9. After viewing it, switch it back to Design View 10. To add bitmaps to tabs, you will first design one. Start Microsoft WordPad (Start -> (All) Programs -> Accessories -> WordPad. On the Formatting toolbar, change the Font to Wingdings. Change the Font Size to 12. Type + (which is Shift and +) to produce an envelope. Select the character. Press Ctrl + C to copy it. Start Microsoft Paint (Start -> (All) Programs -> Accessories -> Paint. With the new empty document, press Ctrl + V to paste. As the picture is still selected with a dotted rectangle around it, click it and hold the mouse down. Then drag left until its left border touches the left border of the frame. To enlarge the picture, on the Tool Box, click the Magnifier button. To reduce the size of the picture, on the main menu, click Image -> Attributes In the Attributes dialog box, change the Width and the Height to 16 each. Using the tools in the Tool Box and the colors in the Color Box, design the picture as follows:

315

11.

To save the picture, on the main menu of Paint, click File -> Save. Save it as contact in your Exercises folder. Make sure you keep the default bmp extension.

12. To use a bitmap on a tab, on the form in Design View, double-click the Notes/Comments tab 13. In the Properties window, click Picture and click its ellipsis button. In the Picture Builder dialog box, scroll down in the Available Pictures list box and click Compile Modules

14. Click OK 15. On the form, click the Contact tab. In the Properties window, click the Picture field and click its ellipsis button 16. In the Picture Builder dialog box, click the Browse button. Locate your Exercises folder and display it in the Look In combo box 17. Select contact and click Open 18. In the Picture Builder dialog box, click OK 19. Save and preview the form

316

20. Switch the form back to Design View 21. To add a control to the form, on the form, click the Contact tab. From the Field List, drag FirstName and drop it under the Contact tab 22. On the form, click the Drivers License tab. On the Field List, click and drag DateIssued to the form 23. Save and preview the form

Close the form 24. Open the Music Collection2 database and click Forms 25. Double-click the MusicAlbums form to open it 26. After viewing it, switch it to Design View 27. On the right side, double-click the empty area on the right side of the Comments tab to select the property sheet 28. In the Properties window, click the Format tab. Click Tab Fixed Width. Type .98 and press Enter 29. Save and preview the form

30. Close the Music Collection Albums form

Subforms
Overview of Subforms
Introduction
Relational database allows you to separate data in objects so that these objects can hold different pieces of information and make data available to other objects that need it. Sooner or later, users constantly need information held by one form while they are working on another

317

form. There are various ways you can solve such a problem. One solution is to "embed" one form or report into another form or report. A subform is a form that you position inside of another form. In order to "include" one form into another form, both objects must have a relationship, as we have learned in the past. The form that is hosting the other form is the parent. The form that is added to the parent is called the child form. The parent form must have a primary key that "links" or relates it to a foreign key in the child form. This foreign key of the child object must be of the same data type as the primary key on the parent object.

Microsoft Access >= 2000 Automatic Subforms


Microsoft Access 2000 and later versions allow you to quickly create a form that has a subform already. Before using this feature, you should make sure that the table you want to use has a sub datasheet, which can be verified by the + button on the left of its records:

As you may know already, a sub datasheet exists if a relationship had previously been created between two tables. Using this feature, to create a form that is automatically equipped with a subform, after selecting the table on the Database Window, on the Database toolbar, you can click the arrow of the New Object button and select AutoForm.

Practical Learning: Automatically creating a Form With a Subform


1. If you are using Microsoft Access 97, skip this exercise. 2. Open the Book Collection1 database

3. From the Tables section of the Database Window, double-click the Categories table to
open it in Datasheet View

318

4. After viewing it, close it but make sure it is sill selected in the Tables section of the Database window

5. On the Database toolbar, click the arrow of the New Object button and select AutoForm:

6. To close and save the new form, click its Close button

7. When prompted whether you want to save the objects, click Yes

Automatic Forms
319

As done with all the other forms we have used so far, there are two main techniques you can use to create a subform. Keeping the tradition of its many wizards, Microsoft Access provides the means of automatically creating a subform. There is no particular design you need to follow for a subform. A subform is primarily a form. The only true rule you must follow is that one of its fields must have a field, usually its primary key, that will allow it to be related to a field on the form in which it would be added. If you are not using the Form Wizard, you can still design a form and make it a subform. You can also create a form equipped with a subform, using the Form Wizard. To do this, in the first page of the wizard, select the parent form. Select the necessary fields for the form (report). In the Tables/Queries combo box, select another table or query that holds the fields for the child form (report). Continue with the wizard. The wizard will verify that the tables or queries share a relationship. If they do not, you would receive an error or the result of the form (report) would be unpredictable.

Practical Learning: Automatically Creating an Auto-Subform


1. Open the Bethesda Car Rental1 database
2. On the main menu, click Insert -> Form 3. On the New Form dialog box, click Form Wizard and click OK 4. In the Tables/Queries combo box, select CarCategories 5. Click the Select All button 6. In the Tables/Queries combo box, select Table: Cars 7. Double-click the following fields to select them: Make, Model, CarYear, NbrOfDoors, and TransmissionID

8. Click Next

9. On the second page, make sure the Form With Subform radio button is selected.
Otherwise, select it

320

10. On the 3rd page, make sure the Datasheet radio button is selected. Otherwise, click it. Click Next 11. On the 4th page, click the Standard style and click Next 12. Change the name of (main) form to CarsByCategory

13. Change the name of the sbfCars

14. Click Finish 15. After viewing the form, switch it to Design View

16. Move the controls around and change their position to appear as follows:

17. Save, preview, and close the form

Types of Subforms
Introduction
Microsoft Access provides various techniques to create a subform. We saw above how a form

321

can be created automatically with a subform. This is sometimes referred to as Master-Detail. Besides using the wizards, you can also design a subform. Subforms typically come in three layouts and each can be used for a specific purpose.

Practical Learning: Introducing Subform Design


1. Open the College Park Auto Shop1 database
2. To create a new table, on the main menu, click Insert -> Table and, in the New Table dialog box, double-click Design View 3. Create the following fields for the table Field Name WorkOrderID InvoiceNumber WorkOrderDate WorkOrderTime Data Type Caption AutoNumber Work Order ID Text Invoice # Additional Information Primary Key Save the table as WorkOrders Field Size: 20 Format: Long Date Input Mask: 99/99/00;0;_ Format: Medium Time Input Mask: 00:00;0:_ Start the Lookup Wizard and accept the first radio button. Select the Employees table. Select the LastName and Title fields. Click Next and click Finish. Caption: Processed By Start the Lookup Wizard and accept the first radio button. Select the Customers table. Select the TagNumber, the LastName, and the FirstName fields. Click Next and click Finish. Caption: Customer Problem Description Decimal Places: 2 Decimal Places: 2 Decimal Places: 2 Decimal Places: 2 Decimal Places: 2 Decimal Places: 2 Tax Rate Field Size: Double Format: Percent Default Value: 0.0755

Date/Time Date Date/Time Time

EmployeeID

Lookup Wizard

CustomerID

Lookup Wizard

ProblemDescription Labor1 LaborCost1 Labor2 LaborCost2 Labor3 LaborCost3 Labor4 LaborCost4 Labor5 LaborCost5 Labor6 LaborCost6 TaxRate Comments

Memo Text Currency Text Currency Currency Currency Currency Currency Number Memo

4. Save and switch the table to Datasheet View 5. Close the table 6. To create a new form, on the main menu, click Insert -> Form. In the New Form dialog

322

box, double-click Form Wizard

7. In the first page of the wizard, in the Tables/Queries combo box, select WorkOrders 8. In the Available fields list, double-click the following fields: WorkOrderID,
InvoiceNumber, WorkOrderDate, WorkOrderTime, EmployeeID, CustomerID, ProblemDescription, and Comments 9. Click Next 10. In the second page, make sure the Columnar radio button is selected and click Next

11. Select the Standard style and click Next 12. Accept the suggested name of the form as WorkOrders and click Finish
13. After viewing the form, switch it to Design View and modify its design as follows: 14. Save, preview and close the form

The Datasheet Form


The automatically created forms and reports provide a simplistic design. Instead of generating such form, or after creating them, you can design or redesign your subforms. To support this, there are three types of layout you can use for a subform. A subform, like a form can display like a spreadsheet, as seen on the above form:

Such a form is designed like any other. To get the spreadsheet display, select the form in Design View and, in the Properties window, change its Default View to Datasheet. You can use the Datasheet view to display data as done on a table, if you have users who like working on columns, rows, and prefer to display all information in the same view, all records at the same time. If a subform contains sections other than the Details, the Datasheet layout would not show them. Therefore, use this view if either you do not need/want to show any field from the Form Header or the Form Footer sections.

Practical Learning: Using a Datasheet Subform


1. Open the Music Collection2 database and click Forms in the Database window 323

2. To create a new form, on the Database window, click the New button. When the New

Form dialog box comes up, in the lower combo box, select AlbumTracks. In the upper list, double-click Design View

3. Save the form as sbfTracks 4. Reduce the width of the form so its right border is at 21/4 5. If the Field List is not displaying, on the Form Design toolbar, click the Field List button
In the Field List, click TrackNumber. Press and hold Shift. Then click TrackLength and release Shift. This selects the TrackNumber, the TrackTitle, and the TrackLength fields

6. Click and drag the selected fields to the Detail section of the form. There is no need to

change the positions or locations of the labels and text boxes. The only changes you should make are to click each label twice (not double-click; simply click it once and click it again) to put it into edit mode and then delete the colon : on the right side of each string. Also, click the TrackNumber text box and, on the Formatting toolbar, click the Center button. Other than that, your form could look as follows and nothing would change its behavior:

7. Double-click the button at the intersection of both rulers. In the Properties window, click
Format and change the following properties: DefaultView: Datasheet Record Selectors: No Navigation Buttons: No Dividing Lines: No

8. Switch the form to Form View 9. Right-click the # column header and click Column Width... Type 3.85 and press Enter 10. Right-click the Track Title column header and click Column Width Type 24.15 and press Enter

11. Right-click the Length column header and click Column Width Type 10 and press Enter

324

12. Save and close the form 13. Double-click MusicAlbums form to open it 14. After viewing it, switch it to Design View and click the Tracks tab on the tab control 15. On the Toolbox, make sure the Control Wizard button is clicked. To add the new subform, on the Toolbox, click the Subform/Subreport button and click in the body of the Tracks button 16. In the first page of the Subform/Subreport Wizard, click the arrow of the combo box and select sbfTracks

17. Click Next.

In the second page of the wizard, make sure the Choose From A List radio button is selected. Also, in the Select One Of These Links list box, make sure the relationship is based on the AlbumID field

18. Click Next 19. Accept the suggested name of the subform as sbfTracks and click Finish 20. Click the label that was added to the subform and press Delete (to remove the label). You will also need to move the subform and resize the property sheet

21. Save and preview the form

22. Close the form

The Single Form


A single form is the type of form that displays its data one record at a time. This concept, which was used on most forms we have used so far, can also be applied to a subform. The single layout can be valuable if you want to show one record from a related form as it is linked to a record on the current form. While a Datasheet form can clearly show that it is an embedded object, the fields of a single form can easily be mixed with those of the hosting form but it is usually determined to be apart. A single subform is designed like a regular form where fields are created in the Detail section

325

and other optional controls can be added to the other sections of the form. When selecting the fields that would be part of the subform, make sure you include only those that can be useful in the form that will host the subform.

Practical Learning: Designing a Single Subform


1. Open the College Park Auto Shop1 database
2. To create a new form, on the main menu, click Insert -> Form and, in the New Form dialog box, double-click Form Wizard

3. In the first page of the wizard, in the Tables/Queries combo box, select Table:

Customers. In the Available Fields list double-click FirstName, LastName, CompanyName, Address, City, State, ZIPCode, TagNumber, Make, Model, CarYear, and Mileage

4. Click Next 5. In the second page of the wizard, make sure the Columnar radio button is selected and press Enter 6. In the third page of the wizard, click the Standard style and press Enter

7. Change the name of the form to sbfCustomers and click Finish 8. After viewing the form, switch it to Design View and redesign it as follows:

9. Double-click the button at the intersection of the rulers and, in the Format tab of the
Properties window, change the following properties: Scroll Bars: Neither Record Selectors: No Navigation Buttons: No Dividing Lines: No

10. Save, preview, and close the form 11. From the Forms section of the Database window, double-click the WorkOrders form to open, then switch it to Design View 12. On the Toolbox, make sure the Control Wizard button is clicked. To use the above subform, on the Toolbox, click the Subform/Subreport button

13. On the form, click under the ProblemDescription memo

326

14. On the first page of the Subform/Subreport Wizard, click the arrow of the combo box and
select sbfCustomers

15. Click Next.

In the second page of the wizard, make sure the Choose From A List radio button is selected and make sure the relationship is defined based on the CustomerID field

16. Click Next 17. Accept the suggested name of the subform and press Enter 18. On the form in Design View, click the label of the newly added subform and press Delete (to remove the label). Move the subform to the left. On the Toolbox, click the Option Group control and click the lower-right side of the form. When the wizard comes up, click Cancel. Using the items from the Field list, add the LabelX and their corresponding LaborCostX 19. Complete the design of the form as follows (below picture): 20. Save, preview, and close the form

327

The Continuous Form


Microsoft Access provides another type of table, sometimes more flexible: the Continuous form. Like the Datasheet form, the Continuous form displays as many records as the height of the form can afford. While the fields of a Datasheet are usually reproduced as they would be on the source table, the fields of a Continuous form must be (carefully) designed to play their roles. We saw that a single form displays the values that belong to a record and only one record displays on the form. Here is an example:

A continuous form also displays one record at a time in the Detail section but each record displays under the previous record, like the Datasheet form except that the fields must be visually designed. Here is an example:

328

Unlike the datasheet form, but like the single form, a continuous form equipped with other sections than the Detail would display them in Form View. This means that you can include additional record in the other sections. Based on this, a typical design of a continuous form consists of creating some labels in the Form Header section and positioning their corresponding controls under them but in the Detail section. The fields can be horizontally aligned and adjacent each other. You should (strongly, if not must) avoid including Memo and OLE Objects (pictures, linked documents, etc) in a continuous form because such fields may take too much space. This would deceive the purpose of the continuous form. As mentioned already, a continuous form is designed with the same care used on a single form. To make a form behave as a continuous form, it depends on the technique you use to create the form. If you create the form using the Form Wizard, in the second page of the wizard, select the Tabular radio button:

If you use the Form Wizard to create the form but select fields from more than one table (or query), in the third page of the wizard, select the Tabular radio button

329

If you are designing the form, in the Properties window set its Default View to Continuous Form.

Practical Learning: Designing a Subform or Subreport


1. The College Park Auto Shop1 database should still be opened.
To create a junction table, on the main menu, click Insert -> Table and, in the New Table dialog box, double-click Design View

2. Set the first Field Name to OrderAndPartsID and set its Data Type to AutoNumber. Also, make it a Primary Key

3. Save the table as OrderAndParts


4. For the second field, set its Field Name to Work Order and set its Data Type to Lookup Wizard When the wizard starts, make sure the first radio button is selected and click Next. Select the WorkOrders table and click Next. Double-click InvoiceNumber to select it and click Next then click Finish. When asked to save the table, click Yes and delete the 0 in the Default Value field

5. Set the Field Name of the third field to Part and set its Data Type to Lookup Wizard
When the wizard starts, make sure the first radio button is selected and click Next. Select the Parts table and click Next. Click the Select All button fields. Click Next , UnitPrice, and Description

and click Finish. When asked to save the table, click Yes and delete 0 in the Default Value 6. Click the Lookup tab in the lower of the table and click Row Source. Click its ellipsis button. In the SQL Statement window, in the Sort field of the Description column, select Ascending

330

6. Close the SQL Statement window. When asked whether you want to save it, click Yes 7. Complete the table as follows: Field Name WorkOrderID PartID UnitPrice Quantity Data Type Number Number Currency Number Integer Caption Work Order Part Unit Price Default Value: 0 Default Value: 1 Additional Properties Primary Key

OrderAndPartsID AutoNumber

8. Save the table and switch it to Datasheet View 9. Close the table 10. To start a new form, on the main menu, click Insert -> Form 11. In the New Form dialog box, click Design View. In the combo box, select OrderAndParts and click OK 12. To save the form, on the Form Design toolbar, click the Save button

13. Type sbfParts and press Enter


14. Right-click in the middle of the form and click Form Header/Footer 15. If the Toolbox is not displaying, on the Form Design toolbar, click the Toolbox button. On the Toolbox, click the Label button

16. Click just under the Form Header bar on the left side:

17. Type Part and press Enter


18. If the Field List is not available, on the Form Design toolbar, click the Field List button From the Field List, drag PartID and drop it somewhere in the Detail section. Click its Part label to select it and press Delete to remove it 19. Move the PartID combo box and place it under the Part label but in the Detail section

331

20. On the Toolbox, click the Label and click under the Form Header bar to the right of the existing Part label. Type Part Name and Press Enter 21. On the Toolbox again, click the Text Box control and click in the Detail section to the right of the existing combo box. Delete its TextX label and select the new Unbound text box. Using the Other tab of the Properties window, change its Name to txtPartName

22. Design the rest of the form as follows:

23. Double-click the button at the intersection of both rulers

. In the Properties window, click the Format tab and change the forms properties as follows: Default View: Continuous Form Record Selectors: No Navigation Buttons: No Dividing Lines: No

24. Save, preview and close the form 25. From the Forms section of the Database window, double-click the WorkOrders form to open it in Form View. After viewing it, switch it to Design View 26. On the Toolbox, make sure the Control Wizard button is clicked To add a subform for the parts, on the Toolbox, click the Subform/Subreport button 27. On the form, click in the lower left side of the Detail section under the Customers subform 28. On the first page of the Subform/Subreport Wizard, click the arrow of the combo box and select sbfParts 29. Click Next 30. In the second page of the wizard, make sure the Choose From A List radio button is selected. Also make sure the relationship is defined based on the WorkOrderID field and click Next 31. Accept the suggested name of the subform and press Enter 32. On the form in Design View, click the label of the newly added subform and edit it to display Parts Used. To complete the list of fields from the source table, from the Field list, drag the TaxRate item and drop it in the lower right section of the form 33. Complete the design of the form as follows (below screenshot): 34. Save and preview the form 35. Close the form

332

Exercises
Watts A Loan
1. Open the Watts A Loan database.
Using the Form Wizard, create a Tabular form that includes the TransactionNumber, the TransactionDate, and the TransactionAmount fields from the Transactions table. Set its Style to Standard and save it as sbfAccountTransactions. Complete its design as follows:

Save and close the form

2. Create a new form based on the Customers table but that includes only the CustomerID,
the AccountNumber, the FirstName, and the LastName fields. Save the form as CustomersTransactions. Add the sbfAccountTransactions to the bottom section and design the rest of the form as follows:

333

Save the form and close it

Yugo National Bank


1. Open the Yugo National Bank database.
Use the Form Wizard to create a new Columnar form using the Standard style and based on the Customers table. Include the following fields: EmployeeID, DateCreated, AccountNumber, and CustomerName. Save the form as CustomersTransactions Use the Combo Box Wizard to add a combo box that uses the AccountType field from the AccountTypes table and store its values in the AccountTypeID field. Set its label to Account Type and change the Name of the combo box to cboAccountType Aadjust its design as follows before saving and closing it:

2. Design a new form based on the Transactions table. Include the following fields:

TransactionTypeID, TransactionDate, TransactionNumber, DepositAmount, WithdrawalAmount, and ServiceCharge Save the form as sbfTransactions Design it as a tabular form as follows before saving and closing it:

3. Open the CustomersTransactions form in Design View and add the sbfTransactions 334

form under the other controls before saving and closing it:

4. Open the CustomersTransactions form to view the result then close it

Introduction to Expressions
Overview of Expressions
Introduction
An expression is a combination of data fields, operators, values, and/or procedures destined to produce a new value. There are various types of expressions you will be using in your applications. When creating an expression, you would ask the database engine to supply data of a specific field following your recommendation. Data you specify is usually not provided by a field on a table. Instead, you can create a field that is a combination of fields from a table, a form, a query, or a report. The data of the expression can also be the result of a combination of dependent fields or values external to any table, form, query, or report. There are two main things you will use to create your expressions: operators and functions. As we saw in the past, an operator is a symbol (or a character) that is applied to one or more items to produce a new value. As we will learn later on, a function is an assignment that accomplishes a specific and isolated job then gives back a result.

Algebraic Expressions
To create an expression, you use any combination of the operators we have used so far. Once the expression is ready, you can assign it to a field on a form or report. To do that, while in Design View, you can access the Control Source of the field in its Properties window, type the

335

assignment operator =, followed by the expression. For example, imagine you want to create an expression as 126.55 + 42.808. To display the result of this expression in the text box of a form, in the Control Source of the text box, you can type = 126.55+42.808 and press Enter

When such a form displays in Form View, the field that holds the expression would display the result (provided it can successfully get the result). Later on, we will see other techniques of creating an expression. So far, we have seen that, data provided to a form is controlled by the Data Source property. Therefore, when creating an expression for a form's field, you must supply the expression to the Data Source field of the Properties window. Probably the simplest expression you can create is by transferring the value from an existing field to another field. Imagine you have a field from a form and the field is named MailingAddress. If you want the value of the MailingAddress field to be transferred or assigned to a field named ShippingAddress, in the Control Source of the ShippingAddress field, you would type =MailingAddress. You can also include the name of a field in square brackets as we saw when studying operator. Instead of MailingAddress, it would consider it as [MailingAddress]. If you were assigning a field to another, you would write the assignment as =[MailingAddress]. Suppose you have a field named HourlySalary and another field named WeeklyHours. If you want to calculate the weekly salary of an employee, you would multiply the HourlySalary by the WeeklyHours and assign the result to another field. In the Control Source property of the resulting field, you would type =[HourlySalary]*[WeeklyHours]

Practical Learning: Basic Expressions


1. Open the GCS application you created 2. Open the OrderProcessing form:

336

3. After viewing the form, switch it to Design View 4. Click the Unbound field under the left Total that corresponds to the Pants

5. In the Properties window, click Control Source and type


= QtyPants * PricePants

6. Press Enter. Notice that Microsoft Access adds the square brackets in the expression to
become =[QtyPants]*[PricePants] 7. Switch the form to Form View to preview it and switch it back to Design View 8. Click the Unbound text box on the right side of the Order Total label In the Control Source of the Properties window, type the following: =[txtPants]+[txtMenSuit2]+[txtMenSuit3]+[txtSweater]+ [txtRegularShirt]+ [txtSilkShirt]+[txtTie]+[txtOther1]+[txtWomenSuit] + [txtDresses]+ [txtRegularSkirt]+ [txtSkirtHook]+[txtCoat]+[txtJacket] + [txtSwede]+[txtOther2] 9. Click the Unbound text box on the right side of the Change label 10. In the Properties window, click Control Source. Type = [txtAmountTended] [txtTotalOrder] and press Enter

11. Preview the form:

337

12. Save and close it. Click the Customer text box (the text box on the right side of the Customer: label)

VBA and Expressions


Introduction
As we will see in this and later chapters, the various functions available in Microsoft Access make it a valuable application to create good functional databases. Nevertheless, Microsoft Access is not a programming environment but a good platform to visually create databases. As your experience grows, you will face some demands that become difficult to achieve. For this reason, Microsoft Access ships with a computer language called Visual Basic For Applications or VBA. Although in this book we will not explore computer programming, we will take a glimpse at what some of the code lines look like.

Automatically Generated Code


You may recall that when we created subforms, we selected only a few fields from the data source. This was purposely done so the user can have the handiest pieces of information about the data that the current form is related to. While the user is performing data entry, he may want to have more details about the data that is displaying. You can achieve this by calling the originating form. To implement this functionality, you can create a command button and let Microsoft Access write code that would take you straight to the related record only.

Practical Learning: Generating VBA Code


1. Open the Rockville Techno1 database and, in the Database window, click Forms
2. Double-click the Clients form to open it 3. After viewing the form, switch it to Design View

4. On the Toolbox, make sure the Control Wizard button is clicked


To generate code that closes the form, on the Toolbox, click the Command Button and click an empty area in the Form Footer section to the right of the Preview Invoice button 5. On the first page of the Command Button Wizard, in the Categories list, click Form Operations. In the Actions list, click Close Form and click Next 6. In the text box, delete Form to have only Close and click Next

7. Change the name to cmdClose and click finish 8. Resize and reposition the buttons as follows:

9. To see the code that Microsoft Access had generated, right-click the Close button you just
added and click Build Event

338

10. Close the window or Visual Basic to return to Microsoft Access 11. Switch the form to Form View. To close it, click the Close button you created 12. When asked whether you want to save it, click Yes

Procedures and Functions


Introduction to Procedures and Functions
A procedure is a task that must be performed aside of a table, a form, or a report, to complement it. It is like an operation or an expression with the first difference that someone else created it and you can just use it. Microsoft Access ships with various procedures to perform different tasks. There are so many of them that we will review only those that are most regularly used. If you had to create a procedure, one of the syntaxes you would use is: ProcedureName() End This syntax is very simplistic but indicates that the minimum piece of information a procedure needs is a name. The name allows you to refer to this procedure in other parts of the database. In reality, a procedure is meant to perform a task. This task would be defined or described in the body of the procedure. In our simple syntax, the body of the procedure would start just under its name and would stop just above the End word. The person who creates a procedure also decides what the procedure can do. Following our simple syntax, if we wanted a procedure that can open Solitaire, it could appear as follows: ProcedureExample() Open Solitaire End Once a procedure has been created, it can be used. Using a procedure is referred to as calling it. To call a simple procedure like the above ProcedureExample, you would just type its name. The type of procedure we have referred to so far in this section is usually called a sub procedure. Most of the procedures we will use in Microsoft Access are called functions. As opposed to a sub procedure, a function would use the syntax: ReturnType FunctionName() End The main difference, as you may see here is that a function produces a result. This is also stated that a function returns a value. Based on this, the result of a function can be provided for further use and assigned (passed) to a field, a sub procedure, or another function. To display the result of a function in a field, you can access its Control Source property, use the assignment operator =, type the name of the function, followed by its parentheses. The person who creates a function also decides what kind of value the function can return. For example, if you create a function that performs a calculation, the function may return a number. If you create another function that combines a first name and a last name, you can

339

make the function return a string that represents a full name. Because most, if not all, of the built-in procedures you will use in Microsoft Access are functions, from now on, we will use only the word function but this refers to both types of procedures.

Procedures, Functions, and their Arguments


When asked to perform its task, a function may need one or more values to work with. If a function needs a value, such a value is called an argument. While a certain function may need one argument, another function would need many arguments. The number and types of arguments of a procedure depend on its goal. The arguments of a function are provided in parentheses. The syntax used to create such a function would be: ReturnValue FunctionName(Argument) End Once again, the body of the function would be used to define what the function does. For example, if you were writing a function that multiplies its argument by 12.58, it would appear almost as follows: Decimal FunctionName(Argument) Argument * 12.58 End While one function may use only one argument, another function may use more than one, depending on its goal. When a function uses more than one argument, a comma separates them. A possible syntax would be: ReturnValue FunctionName(Argument1, Argument2, Argument_n) End If you were creating a function that adds its two arguments, it would appear almost as follows: NaturalNumber AddTwoNumbers(Argument1, Argument2) Argument1 + Argument2 End Once a function has been created, it can be used in other parts of the database. Once again, using a function is referred to as calling it. If a function is taking one or more arguments, it is called differently than a function that does not take any argument. We saw already how you can call a function that does not take any argument and assign it to a field using its Control Source. Here is an example:

If a function is taking one argument, when calling it, you must provide a value for the argument, otherwise the function would not work (when you display the form or report, Microsoft Access would display an error). To call a function that takes an argument, type the name of the function followed by the opening parenthesis (, followed by the value (or the field name) that will be the argument, followed by a closing parenthesis ). The argument you pass can be a regular constant value or it can be the

340

name of an existing field. The rule to respect is that, when Microsoft Access will be asked to perform the task(s) for the function, the argument must provide, or be ready to provide, a valid value. As done with the argument-less function, when calling this type of function, you can assign it to a field by using the assignment operator in its Control Source property. Here is an example:

If the function is taking more than one argument, to call it, type the values for the arguments, in the exact order indicated, separated from each other by a comma. As for the other functions, the calling can be assigned to a field in its Control Source. Here is an example:

Default Arguments
We have mentioned that, when calling a function that takes an argument, you must supply a value for the argument. There is an exception. Depending on how the function was created, it may be configured to use its own value if you fail, forget, or choose not, to provide one. This is known as the default argument. Not all functions follow this rule and you would know either by checking the documentation of that function or through experience. If a function that takes one argument has a default value for it, then you do not have to supply a value when calling that function. Such an argument is considered optional. Whenever in doubt, you should provide your own value for the argument. That way, you would not only be on the safe side but also you would know with certainty what value the function had to deal with. If a function takes more than one argument, some argument(s) may have default values while some others do not. The arguments that have default values can be used and you do not have to supply them.

The Expression Builder


There are three main ways you create expressions. If you know, based on experience, what the expression is made of, you can just write it in the Control Source of the field that will hold the expression. This technique is faster but prone to error. Creating an expression is a technique of giving a "made-up" value to a field. The field that would hold such an expression is referred to as unbound because it is not directly linked to any field of a table. Since the new value that constitutes the expression is in fact "assigned" to the expression-field, you must use the assignment operator which is "=". Therefore, the first symbol you will use in an expression is =. When you acquire more experience with Microsoft Access, you will be able to perform some operations very quickly with little or no help. Nevertheless, to assist you with creating

341

expressions, Microsoft Access, continuing with its limitless number of wizards, provides a special dialog box for this specific purpose. This is the role of the Expression Builder. To access it, click the Control Source field in the Properties window, which would reveal its ellipsis button . Then click the ellipsis button . This would call the Expression Builder dialog box

Once the Expression Builder displays, you can include an operator by clicking its corresponding button. You can also type the symbol of the operator using your keyboard. To select a field that already exists in the current form or report, in the left list, you can click the first item. To access a field that exists in another object, you can first double-click a category (Tables, Queries, Forms, or Reports) in the left list. This would display the list of objects of that category. Then you can click the object itself. To actually include a field in your expression, you can double-click it in the middle list. To use one of the built-in functions of Microsoft Access, in the left list, you can double-click the Functions node to expand it. Then click Built-In Functions. The categories of functions would display in the middle list. The real functions appear in the right list. To see the syntax of a function, you can simply click it once. Its syntax would appear in the bottom section of the Expression Builder dialog box:

Without being particularly explicit, the syntax of the function allows you to know the number and order of arguments of a function. To get more information about the function, you can check its documentation in the help files. To actually include the desired function in your expression, you can double-click its name in the right list. If you already know the name of the function, you can still manually type it in the desired section of the expression. When creating an expression, if you click the button of an operator, the <<expr>> would display as a placeholder, indicating that a value is expected:

342

If you double-click the name of a function in the right list, if the function takes one or more arguments, a placeholder would be created for each argument:

You have the responsibility to supply an appropriate value for each placeholder. To do that, you have two alternatives. If you know the value that should be used in a placeholder, you can just type it. Alternatively, you can use the operator buttons or the built-in functions to fill a placeholder. We should point out that not all functions are available in the list of functions of the Expression Builder but, as long as you know that a Visual Basic function is supported and you know its syntax, you can use it.

Introduction to Built-In Functions


Overview
To ease your job with database implementation, Microsoft Access ships with many functions. These functions have been tested and are highly reliable, so much that in this book, we will use only the built-in functions. Because there are so many of them, they are classified in categories and you are not likely to use all or even most of them. The users of your database will be presented with fields they can fill to either provide new values or change the existing values. Anything the user types in a field is primarily considered a string. Before performing any type of operation that involves such a value, you should make sure you can identify what kind of value it is. For example, you should not try to multiply a string by a date such as FirstName * January 16. Although you will not be able to avoid every single type of problem that could occur in your database, you can reduce errors by checking the value that a control holds.

Page Break References


In the previous lesson, we mentioned that a form could be divided in various sections separated by a page break. Although such sections are created in the Design View of a form, Microsoft Access does not inherently provide a way to access them. You have two alternatives.

343

You can use a macro or VBA. For one thing we will not use macros in this book. For another, we will afford to write one line of code to apply the functionality we need. On a form, to access a section that was separated with a page break, you can call the GoToPage() function (in reality, GoToPage() is a method of the DoCmd class). The GoToPage() method takes as a required argument the number that corresponds to the section you are trying to access.

Conversion Functions
The first action you should take when dealing with the value retrieved from a field is to convert it to the appropriate type. There are various conversion functions adapted to the different possible kinds of values. The general syntax of the conversion functions is: ReturnType = FunctionName(Expression) The expression could be of any kind. For example, it could be a string or value the user would have entered in a form. It could also be the result of a calculation performed on another field or function. The conversion function would take such a value, string, or expression and attempt to convert it. If the conversion is successful, the function would return a new value that is of the type specified by the ReturnType in our syntax. The conversion functions are as follows:

Function Name CBool CByte CDate CDbl CInt CCur CLng CSng CStr Return Type Boolean Byte Date Double Integer Currency Long Single String Description Converts an expression into a Boolean value Converts an expression into Byte number Converts and expression into a date or time value Converts an expression into a flowing-point (decimal) number Converts an expression into an integer (natural) number Converts an expression into a currency (monetary) value Converts an expression into a long integer (a large natural) number Converts an expression into a flowing-point (decimal) number Converts an expression into a string

Practical Learning: Converting Data Values


1. Open the College Park Auto Shop2 database and click Forms in the Database window 2. Double-click the sbfParts subform to open it
3. After viewing the subform, switch it to Design View

4. Widen the form so its right border touches the 41/4 mark of the horizontal ruler 5. On the Toolbox, click the Label
and click on the right side of the Qty label in the Form Header section. Type Total and press Enter

6. Make it appear Bold like the other labels 344

7. On the Toolbox, click the Text Box control


8. Delete its label

and click in the Detail section

9. Using the Properties window, change the following properties for the new unbound text
box: Name: txtSubTotal Control Source: =CDbl([UnitPrice]) * CInt([Quantity]) Format: Currency Decimal Places: 2 Top: 0.02

10. Save the subform and close it

Logical Functions
Introduction
In the strict sense, because Microsoft Access is not a traditional programming environment, it does not provide a feature called conditional or control statement, which is used to check a condition. Instead, it provides functions you can use to check that a condition is true or false. There are various functions that can be used to create an expression as complex as an algorithm would allow. It is important to note that, although most of these functions perform conditional checking, they do not return the same type of value. For this reason, you should choose the right function. Most of these functions will also be used in combination with other functions as necessary.

Immediate If
The most regularly used function to perform conditional statements is called IIf. The Immediate If function, IIf(), needs three pieces of information in order to accomplish its assignment. The syntax used is: IIf(Condition, WhatToDoIfConditionIsTrue, WhatToDoIfConditionIsFalse) The first action this function performs is to evaluate a condition. This condition could involve an operation or the result of an operation. If the Condition is true, then the function would execute the first expression, which is identified in our syntax as WhatToDoIfConditionIsTrue. The Condition could lead to only one of two results. For example, the Condition could consist of checking whether an employee is married or not. If the field is a combo box, it might have only a Yes and a No values. In that case, the user would select only either Yes or No. A Condition could also result in more than two values. For example, suppose a combo box holds the book categories of a database. Such a combo box could display values such as History, Entertainment, Biographies, Computers, Computer Programming, Geography, and Artificial Intelligence. When a field can hold various values, the Condition you specify as the first item of your IIf() function would be checked. If it produces a true result, the WhatToDoIfConditionIsTrue statement would be executed. If the Condition renders false, the WhatToDoIfConditionIsFalse statement would be executed. This is important to keep in mind: the IIf() function checks only one condition. If you want to check more than one condition, you would have to write a more elaborate expression. Imagine that you have a list of students and you want to take some action depending on a student being a boy or a girl. You can pose a condition that would check whether the field that

345

holds the student's gender is displaying Male or Female. The IIf() function used here could be =IIf(Gender = "Male", WhatToDoIfMale, WhatToDoIfNotMale). Imagine that a combo box holds the values of M and F. If you have a text box named txtGender that would display a gender string depending on the value selected from a combo box named cboGender, in the Control Source of the text box, you can write the IIf() function as follows: =IIf([cboGender]="M","Boy","Girl")

Practical Learning: Using IIf


1. Open the Bethesda Car Rental1 database 2. Open the Customers1 form in Design View
3. Click the middle tab

4. On the Toolbox, click Text Box 5. Click on top of the DriversLicNbr text box

6. Change the label's caption to Full Name:


7. Click the new text box to select it

8. On the Properties window, change its name to txtFullName and press Enter 9. In the Control Source, type (in one line)
=IIf([MI]="",[FirstName] & " " & [LastName],[FirstName] & " " & [MI] & " " & [LastName]) 10. Switch to Form View. Click the Driver's License tab and navigate through a few records, those whose customer has a middle initial and those that do not have a middle initial 11. Save and close the form

Field Emptiness
The conversion functions we reviewed above are effective if they are supplied a value to convert. In some of your expressions, you will provide a data field as argument to use by a function. Even if you decide to convert a field to the appropriate value, you may need to first

346

check whether the field is empty. This can be taken care of by calling the IsEmpty() function. Its syntax is: IsEmpty(Value) This function checks its argument, which could be a field or an expression. If it is a field and the field is empty, this function returns True. If the field is not empty, the IsEmpty() function returns False.

Practical Learning: Checking For Empty Field


1. The Bethesda Car Rental1 database should still be opened.
Reopen the Customers1 form in Design View and click the Driving Information tab 2. On the form, click the txtFullName text box and, in the Properties window, change the value of the Control Source to (in one line) =IIf(IsEmpty([MI]),[FirstName] & " " & [LastName],[FirstName] & " " & [MI] & " " & [LastName]) 3. Switch the form to Form View and check the values of different records in the Driving Information tab 4. Save and close the form

Nullity Checking
Another problem you may encounter when involving a field in an operation is to know whether the field has never contained a value. This operation is sometimes confused with that of checking whether a field is empty. Here is the difference (it is important to understand this because it is used in many other environments, including Microsoft Visual Basic and Microsoft SQL Server): Imagine a field is used for first name and the field displays Paul. If the user comes to that record, the field is not empty, it already contains a name, which in this case is Paul. If the user clicks in the field and deletes Paul, the field becomes empty. It is not null Imagine a field is used for first name. If the user comes to a new record, the field for the first name may be empty (if you did not give it a default value). In this case, the field is Null: it is not empty because it has never contained anything. If the user types a name, and then deletes it, the field is not considered null anymore: it has become empty

To check whether a field (or a value) is null, you can call the IsNull() function. Its syntax is: IsNull(Value) Also used on fields, the IsNull() function checks the state of a field (remember, this function does not check whether a field is empty or not; it checks if the field has ever contained a value). If the field it null, this function returns True. If the field is not null, this function returns False.

Numerical Checking
When the word operation is stated, most people think of a numeric value, an operator, and another numeric value. Such values must be valid in order for the operation to succeed. It certainly would not make sense to multiply a DateHired by a HourlySalary. Therefore, before involving a value or field to an operation, you should check that it contains a valid number. To perform this checking, Microsoft Access provides the IsNumeric() function. Its syntax is: IsNumeric(Value) The IsNumeric() function returns True if its argument is a valid number. Otherwise, it returns False.

Practical Learning: Checking for Numeric Value


347

1. Open the College Park Auto Shop2 database and click Forms in the Database window 2. Right-click the sbfParts subform and click Design View 3. Click the text box under the Total label and, in the Data tab of the Properties window,
change the value of the Record Source as follows: =CDbl([UnitPrice])*IIf(IsNumeric([Quantity]),CInt([Quantity]),0)

4. Save and close the subform

Non-Zero Checking
We saw that, before performing any operation on the value held by a field, you should first convert it to the appropriate value. The conversion functions we mentioned assume that the field contains a value. Unfortunately, it is not always the case. Microsoft Access provides the Nz() function that can be used to check whether a field contains a value, whether the field is empty, or is Null. The syntax of this function is: Nz(Value, ValueIfNull) The first argument, Value is required. The second argument is optional. The pseudo-code for this function is: If the field contains a value Return that value Otherwise Return 0 In other words, this function considers the value provided as the Value argument. This could be an expression but it is usually used on a field that is involved in a calculation. If the Value argument or the passed field is empty, this function returns 0. If the field contains a value, this function returns it. The beauty of this function is that it provides a valuable safeguard for an operation. The second argument is optional and it would be used as the return value if the Value argument were null.

Practical Learning: Basic Expressions


1. Open the Gcs database and open the OrderProcessing form in Form View
2. After viewing it, switch it to Design View 3. Click the first text box under the left Total that corresponds to the Pants

4. On the Properties window, change the value in the Control Source to


=Nz([QtyPants])*Nz([PricePants]) 5. Do the same for each of the text boxes under each Total label 6. Save and close the form

Windows Controls and Expressions


Introduction
A persons interaction with the computer is mostly done using Windows controls as these objects hold or present various pieces of information that the person can use. Therefore, Windows controls are highly involved in expressions. The expressions we have used so far were fairly straightforward and did not need any complex algorithm to accomplish their purpose. Unfortunately, as a database developer, you will face various scenarios, some of them might range from difficult to impossible. There are two main tools you need to build these sorts of expressions. First, you should know what is available so you can wisely play with Microsoft Access. Second, you will make use of your ability to logically think and process information.

348

Text-Based Controls
A string is an empty space, a character, or a group of characters. Because the character or group of characters that constitute a string is considered "as is", a string must be included in double-quotes whenever it is involved in any expression. Examples of strings are "g", "Gabriel", "Congo". In reality, these examples of strings are referred to as values. The value of a string is usually stored in the name of a field. For example, the last names of employees, such as "Pierre", "Harvey", "Charles", "Hermine", can be commonly stored in a field named FirstName. The ability to store a category of string in a named field allows such a field to be used in an expression, which then would produce a standard result for all records involved in that field. Based on this, you can use operators on names of fields instead of on values of those fields. The most classic operation you will perform on strings consists of adding strings such as a first name and a last name in order to produce a new string that could represent a full name. Adding two strings is also referred to as concatenating them. To concatenate two or more strings, you can use the addition operator +. An example would be FirstName + LastName. This would produce a string as FirstNameLastName. Instead of having the first and last names tied, you may need to include an empty space between them. For this reason, you can add three strings such as FirstName + " " + LastName to get a new string. Although you can use the addition operator on strings, you might start thinking that any of the other algebraic operations can be used on strings, not at all. The addition operator was especially written (in computer programming, we say that it was overloaded) to be applied to strings. None of the other arithmetic operations (subtraction, multiplication, division, and remainder) can be applied to strings and it would not make sense. For this reason, Microsoft Access (and the (Visual) Basic language) provide an alternate and appropriate operator to add strings. Besides, or instead of, the addition operator, you can also add strings using the & (called ampersand) operator. To add two strings or fields named FirstName and LastName, you can use the concatenation operator as FirstName & LastName. Like the addition operator, this operation appends the second string to the end or right of the first one. To produce a more readable string, you can add an empty string in the middle. The operation would become FirstName & " " & LastName

Practical Learning: Concatenating Strings


1. Open the Danilo Pizza1 database and click Tables 2. Double-click the CustomersOrder table to open it in Datasheet View
3. After viewing the table, switch it to Design View 4. Right-click OrderDate and click Insert Rows. In the new empty field, type Cashier and press Tab. Type L and press F6. In the first page of the wizard, make sure the first radio button is selected and click Next. In the second page, click Employees and click Next. In the Available Fields list, double-click LastName. Click Next and click Finish

5. In the lower section of the table, delete the Default Value and click Lookup 6. Click Row Source and click its ellipsis button 7. Change LastName in the second column to LastName & , & FirstName and press
Enter 8. To preview, on the Query Design toolbar, click the Run button

9. After viewing the query, switch it back to Design View. In the new field, replace Expr1
with Cashier and, in the Sort field of the same column, select Ascending:

349

10. Close the SQL Statement window. When asked whether you want to save, click Yes 11. Save the table and switch it back to Datasheet View. Click the arrow of the Processed By combo boxes and notice that each employee is represented with a last and a first name 12. Close the table

13. Open the College Park Auto Shop2 database and click Forms 14. Double-click the WorkOrders form to open it. Click the arrow of the Processed By combo
box. Notice that each employee name is set only using the last name

15. Switch the form to Design View and double-click the EmployeeID combo box

16. In the Properties window, click the All tab and click Row Source. Then click the ellipsis
button of the field to open its SQL Statement 17. In the lower section of the query window, change LastName to display: IIf(IsNull([MiddleName]),[LastName] & ", " & [FirstName],[LastName] & ", " & [FirstName] & " " & [MiddleName])

18. Preview the query and switch it back to Design View. In the second column, change Expr1
to Employee and set the Sort field to Ascending for the same column

19. Close the SQL Statement window. When asked whether you want to save it, click Yes 20. Still in the All tab of the Properties window, change Column Width value to 0";1.4";1.25" 21. Change the List Width value to 2.65

22. Switch the form to Form View and click the arrow of the Processed By combo box

350

23. Save and close the form

Command Buttons
Command buttons, or simply called buttons, are the most widely used objects to initiate actions on an application. Among other things, they are used to close windows, to open others, to validate a users choice, to present alternatives, etc. When introducing Windows controls, we that the easiest way to create a button consisted of using the Command Button Wizard. Indeed, when using this technique, there is a great deal of code that Microsoft Access writes to apply the desired functionality. The lines of code that Microsoft Access writes have already been prepared and were installed with it in some libraries called DLL. In some cases, either Microsoft Access is not prepared to write the exact functionality you need and it can write only part of the code. For this reason, you will either simply modify the code that Microsoft Access started or, if you know what to do, you can completely write your own code. Imagine that, on the Bethesda Car Rental database, while processing an order and after the clerk has selected a car, the customer may ask various questions about the car. When creating subforms, we learned that an efficient subform includes only a reduced list of the fields that would be valuable on its parent form. You can then allow you the user to open the main form that holds more information about the subform but you should make sure that only the current record is made available to the user.

Practical Learning: Using Command Buttons


1. Open the Bethesda Car Rental2 database and click Forms
2. Double-click the OrderProcessing form to open it 3. After viewing the form, switch it to Design View

4. On the Toolbox, make sure the Control Wizard button is clicked


In the Toolbox, click the Command Button combo box select Form Operations and click to the right side of the CarID

5. When the first page of the Command Button Wizard comes up, in the Categories list box, 6. In the Actions list, select Open Form and click Next
7. In the second page of the wizard, click Cars and click Next

8. In the third page of the wizard, click the first radio button: Open The Form And Find
Specific Data To Display and click Next

9. In the fourth page, in the OrderProcessing list box, click CarID. In the Cars list box, click
CarID. Click the button between both lists

351

10. Click Next 11. In the text box, replace the string with Car Details and click Next

12. Change the name of the button to cmdCarDetails and click Finish
13. Resize and position the button for a better layout then close the form 14. When asked whether you want to save it, click Yes

Radio Buttons
Options buttons are used in a group, which makes it particular to refer to them. If you design your option buttons in a "normal" way, which is classically done by including them in an Option Group, to find out which option button is selected in a group, you can call the Value property of the Option Group control. The first option button has a value of 1, the second has a value of 2, etc. Imagine you have an Option Group control called fraGender that has three radio buttons and a text box called txtGender. If you want to find out what radio button is selected from the option group and display its value in the text box, in the Control Source of the text box, you can type =fraGender.Value

In the same way, if you have radio buttons on an Option Group box, you can use the IIf() function to find out what button the user would have clicked. If you have only two option buttons, or if you have more than one radio button but want to consider only two possibilities, the use of the IIf() function would be easy. You can just decide which option button in the group would hold the necessary value. The database engine recognizes that when you access an option button that is part of a group, you are actually asking the group control (the Option Group box is in fact the "parent" of the radio buttons because it "carries" them) to find out what radio button was selected. In reality, the default property of an Option Group box is the Value. Therefore, in your expressions, you can omit the calling to the Value property. This means that when you write Frame12 for the name of a group box, you are in fact accessing the Value property of the control. Based on this, the minimum validation you can perform on an Option Group is to do something if the desired option button is selected, or to do something else otherwise. Such a validation can be written with the IIf() function as follows =IIf([fraGender]=1,"You are the man!","You go girl!!!")

352

If you want to navigate through a group of radio buttons and validate each, you would have to include IIf() functions inside of others. This is referred to as nesting. Imagine that when processing the orders of a pizza application, you want to specify the price of a pizza based on the size selected and there are three sizes. A simple IIf() function would not suffice. If the user selects the small size, you would apply the price for a small pizza. In a simple IIf() function, if the user selects another size, you would have only one price left. In a text box that holds the price according to the selected size, you could write an expression as: =IIf(fraPizzaSize=1, PriceSmall, PriceMedium) What if the user selects a large size? The only solution is to nest another IIf() function and to include it as the False part of the Condition. The pseudo code you could use is If Small Size is selected Then Apply Small Price Otherwise If Medium Size is selected Then Apply Medium Price Otherwise Apply Large Price End If End If

Practical Learning: Using Radio Buttons


1. Open the Danilo Pizza1 database and click Forms in the Database window
2. Double-click the OrderProcessing form to open it 3. After viewing the form, switch it to Design View 4. On the form, click the text box to the right of Total Price to select it

5. In the Properties window, click the All tab and click the Control Source field
6. Click the ellipsis button to call the Expression Builder dialog box 7. On the left list, double-click Functions and click Built-in Functions 8. In the middle list, scroll down and click Program Flow. In the right list, double-click IIf 9. In the top text box, click <<expr>> to select it 10. In the left list, click OrderProcessing 11. In the middle list, double-click fraPizzaSize 12. Type =1 13. In the top text box, click <<truepart>> 14. In the middle list, double-click PriceSmall 15. In the top text box, click <<falsepart>> 16. In the left list, click Built-in Functions. In the middle list, click Program Flow. In the right list, look for and double-click IIf 17. In the top text box, click <<expr>> 18. In the left list, click OrderProcessing 19. In the middle list, double-click fraPizzaSize

353

20. Type =2
21. In the top text box, click <<truepart>> 22. In the middle list, double-click PriceMedium 23. In the top text box, click <<falsepart>>

24. In the middle list, double-click PriceLarge

25. Click OK 26. On the Properties window, set the Format to Currency and the Decimal Places to 2 27. Switch the form to Form View 28. On the form, click different option buttons and notice that the price of the pizza changes depending on the selected radio button 29. Switch the form back to Design View. 30. We will make invisible the text box we had added because the user will not need access to it. On the form, click the txtPizzaPrice text box that was just added 31. In the Properties window, click the Format tab and set the Visible property to No 32. Save and close the form

Toggle Buttons
We defined a toggle button as a variant of a radio button or a check box. When toggle buttons come as a group and are treated as a group, they behave like radio buttons. When a toggle button is created as its own button, it behaves like a check box. To create toggle buttons that would behave like radio buttons, you should use the Option Group control. Otherwise, to create a toggle button that behaves like a check box, you can use the Toggle Button control on the Toolbox. After creating a toggle button, you can implement its functionality. As stated already, a toggle button is first of all a button. Therefore, when it is clicked, it sends a message stating that it has been clicked. You can then take the necessary action. When a toggle button is part of a group created in an Option Group control, the host (the Option Group control) can be used to take care of the action. To do this, each toggle button is represented by the Option Value property. Therefore, when implementing the Option Group, to know what button was clicked in the group, you can use a logical function like IIf (or a conditional statement like IfElse) to check the value of the clicked button. Once you know what button was clicked, you can do what you want.

Practical Learning: Configuring Toggle Buttons


1. Open the Bethesda Car Rental2 database and click Forms in the Database window
2. Double-click the Customers2 form to open it

354

3. After viewing the form, switch it to Design View 4. Scroll down to display the Form Footer section. In the Toolbox, make sure Control Wizard button is clicked. In the Toolbox, click the Option Group button and click somewhere under the Form Footer bar

5. On the first page of the Option Group Wizard, under Label Names, type Contact and
press the down arrow key

6. Type Driving Information and press the down arrow key 7. Type Notes/Comments and press Enter

8. Click Next 9. In the second page of the wizard, accept to have Contact as the Default Choice and click Next 10. In the third page, accept the suggested values and click Next 11. In the fourth page, make sure the Save The Value For Later Use radio button is selected and click Next

12. In the fifth page, click Toggle Buttons and accept the Etched Style

13. Click Next 14. In the sixth page of the wizard, accept the suggested Caption and click Finish

15. While still in Design View, click the label that was added and press Delete to remove it.
Move and resize the controls to redesign them as follows:

16. To add a button to close the form, on the Toolbox, click the Command Button and click to

355

the right of the Notes/Comments button in the Form Footer section and inside the group control 17. When the first page of the Command Button Wizard comes up, in the Categories list, click Form Operations. In the Actions list, click Close Form and click Next. In the second page, in the text box, delete Form to have only Close and click Next. In the next page, change the name to cmdClose and click Finish

18. Resize the button to occupy the area on the right side of the group control

19. Double-click the border of the group control. In the Properties window, click the All tab
and change the following two properties: Name: fraSections Border Style: Transparent 20. Save the form

Check Boxes
A check box can have only two states: selected or not selected. (In most programming environments, a check can actually have three states, depending on how it was created. The third state would appear as "half" checked, also referred to as gray or indeterminate. For our databases here, we will consider that a check box can only be clicked or not clicked). When a check box is selected, it has a value of True, Yes, On, or 1. When it is not clicked, it holds a value of False, No, or 0. This value can be used as you see fit. For, example, while only one option button can be selected in a group box, as many as necessary check boxes can be selected in a group. In fact, you do not have to include your check boxes in a group. You can use the IIf() function to do something if a check box is selected or do something else if the same check box is not selected. You can use the IIf() function as follows: =IIf([chkMaritalStatus],"Welcome to the club","We can't allow you")

Practical Learning: Using Check Boxes in Expressions


1. Open the Danilo Pizza1 application. From the Forms section, right-click the OrderProcessing
form and click Design View 2. On the Toolbox, click the Text Box control and click the area under the Olives label 3. Change the caption of its label to Number 4. Change the Name of the text box to txtToppings 5. Drag PriceTopping from the Field List to the left group 6. Change its label's Caption to Each

7. Design the rest of the form as follows:

356

8. To count the number of check boxes that are selected, that is, to get the number of toppings, set the Record Source of the txtToppings text box to =Abs(([Pepperoni]+[Sausage]+[ExtraCheese]+[Onions]+[Olives])) 9. To calculate the amount produced by the number of selected toppings, on the Toolbox, click Text Box and click an empty are on the form (anywhere will be fine as long as you can see it since this will be a temporary field) 10. Set its Control Source to =Abs([Pepperoni]+[Sausage]+[ExtraCheese]+[Onions]+[Olives])*Nz([PriceTopping]) 11. Switch the form to Form View to see the result. Then switch the form back to Design View and delete the text we just added 12. On the form, click the text box on the right side of Total Order

13. In its Control Source, type the following (this formula appears long but it contains only the
functions we have used so far): =CDbl(IIf([fraPizzaSize]=1,[PriceSmall],IIf([fraPizzaSize]=2, [PriceMedium],[PriceLarge])))+CDbl([txtBreadSticks])+CDbl([txtBuffaloWings])+ (Abs([Pepperoni]+[Sausage]+[ExtraCheese]+[Onions]+[Olives])*[PriceTopping])+ CDbl([txtSodaCan])+CDbl([txtSoda20Oz])+CDbl([txtSoda2L])+CDbl([txtOJ])+ CDbl([txtWater])

14. Preview the form and perform a few orders:

15. Save and close the form

Combo Boxes
357

We have learned to use or create a field whose data is available through a combo box. We also know that a combo box can be made of more than one field of data. In that case, data is organized in columns when the combo box drops. Unfortunately, a combo box can display only one field of data when it is not dropped. If you want a combo box to display more than one field, you can create an expression that combines fields from the originating table.

Practical Learning: Designing a Time Sheet


1. Open the Bethesda Car Rental1 database
2. On the Database Window, click Tables and click the New button 3. From the New Table dialog box, click Design View and click OK

4. For the first Field Name, type TimeSheetID and make it an AutoNumber Data Type. Also
make it a Primary Key 5. To save the table, on the Table Design toolbar, click the Save button

6. Type TimeSheet and press Enter 7. Set the name of the second Field Name to EmployeeID and set its Data Type to
Number

8. Set the name of the third Field Name to DateSigned and set its Data Type to
Date/Time

9. Set the next Field Name to MondayIn and for its Data Type, select Lookup Wizard...
10. When the first page of the Lookup Wizard dialog box comes up, click the second radio button and click Next.

11. Under Col1, type 00:00 AM and press the down arrow key. 12. Type 00:30 AM and press the down arrow key
13. Complete it with the other values so that when you finish, the list will include 00:00 AM, 00:30 AM, 01:00 AM, 01:30 AM, 02:00 AM, 02:30 AM, 03:00 AM, 03:30 AM, 04:00 AM, 04:30 AM, 05:00 AM, 05:30 AM, 06:00 AM, 06:30 AM, 07:00 AM, 07:30 AM, 08:00 AM, 08:30 AM, 09:00 AM, 09:30 AM, 10:00 AM, 10:30 AM, 11:00 AM, 11:30 AM, 12:00 PM, 12:30 PM, 01:00 PM, 01:30 PM, 02:00 PM, 02:30 PM, 03:00 PM, 03:30 PM, 04:00 PM, 04:30 PM, 05:00 PM, 05:30 PM, 06:00 PM, 06:30 PM, 07:00 PM, 07:30 PM, 08:00 PM, 08:30 PM, 09:00 PM, 09:30 PM, 10:00 PM, 10:30 PM, 11:00 PM, 11:30 PM 14. Click Next 15. Accept the suggested name of the field and click Finish 16. In the lower section of the table, click the Lookup property sheet

17. Set the Limit To List field to Yes and click General 18. Set the Default Value to "12:00 PM"
19. On the upper section of the table, right-click the gray box on the left of MondayIn and click Copy 20. Right-click the first empty field and click Paste 21. Change the name of the new field to MondayOut 22. Continue pasting into the empty field names and changing their names so that when you finish, you should have a complete time sheet

23. Set the last Field Name to Notes and set its Data Type to Memo

358

24. Save and switch the table to Datasheet View to preview it 25. Close the table 26. To start a new form, on the menu bar, click Insert -> Form 27. On the New Form dialog box, click Design View. In the combo box, select TimeSheet and click OK. 28. Save the form as TimeSheet

29. On the Toolbox, make sure the Control Wizards button is down
click the form

. Click Combo Box and

30. When the first page of the Combo Box Wizard comes up, make sure the first radio button is selected and clicked Next 31. In the list of tables and queries, click Employees and click Next 32. In the Available Fields list box, double-click EmployeeNumber, FirstName, and LastName 33. Click Next 34. Make sure the Hide Key Column check box is checked and click Next 35. Click the arrow of the combo box and select EmployeeID 36. Click Next and click Finish

37. Change the name of the combo box to cboEmployeeID


38. On the Toolbox, click Text Box and click the form

39. Change the Control Source of the Unbound text box to


=[cboEmployeeID].[Column](3) & ", " & [cboEmployeeID].[Column](2)

40. Design the form as follows:

359

41. Change the names of the text boxes under Total from top to bottom to txtMonday, txtTuesday, txtWednesday, txtThursday, txtFriday, txtSaturday, txtSunday, and txtWeeklyTotal repectively 42. Save and preview the form. Switch back to Design View

Page Breaks
We saw that a form can be segmented in different sections to save space. This allows you to show only one group of controls at a time while still maintaining all of the controls of a large table on the same form. We also mentioned that, when using this technique, you should make sure that the user could get to the hidden controls when needed. One solution consisted of using scroll bars. If you decide to hide the scroll bars, you can use another technique to get to the other group(s) of controls.

Practical Learning: Configuring Page Breaks


1. The Bethesda Car Rental2 database should still be opened with the Customers2 form in
Design View. On the Form Design toolbar, click the Code button 2. In the Object combo box, select fraSections

3. In the Procedure combo box, select Click

4. Implement the event as follows: Private Sub fraSections_Click() If [fraSections] = 1 Then GoToPage 1 If [fraSections] = 2 Then GoToPage 2 If [fraSections] = 3 Then GoToPage 3 End Sub 5. If you are using MS Access 97, close the window that contains the code. In other versions, close Microsoft Visual Basic

6. Switch the form to Form View and click the Contact, Driving Information, and
Notes/Comments buttons

360

7. To dismiss the form, click its bottom Close button. When asked whether you want to save, click Yes

Subforms and Subreports


Everything stated here for a subform also applies to a report and a subreport. A subform is valuable for its ability to host its own fields that do not belong to the form it is embedded on. This feature also makes it possible to create an expression on a subform and then simply transfer the result of that calculation to the form that is hosting the subform. Furthermore, if an example involves a large value of all records on a subform, the resulting value can be made available to the hosting form only its record, based on the relationship the form and the form share.

Exercises
Yugo National Bank
1. Open the Yugo National Bank
Open the Customers table in Design View and make sure the EmployeeID displays each item in its list as LastName, FirstName. Also, sort that field

Save and close the table 2. Open the Customers form in Design View. Delete the EmployeeID combo box and, from the Field List, drag the EmployeeID field and drop it where the other was Save and close the Customers form 3. Open the Customers form and complete the accounts with the following information: Created By Yuen, Matt Marconi, Catherine Account Number Account Type 28-3782-8 92-3782-4 Checking Checking

361

Holland, Andy Kast, Aaron Yuen, Matt Kast, Aaron Young, Sylvie Marconi, Catherine Holland, Andy Yuen, Matt Holland, Andy Marconi, Catherine Holland, Andy Marconi, Catherine Kast, Aaron Yuen, Matt Holland, Andy Marconi, Catherine Yuen, Matt Holland, Andy Young, Sylvie 4. Close the form

38-4227-5 68-6434-5 83-4654-7 47-4783-2 82-3763-2 72-3474-2 34-5458-4 29-4586-4 68-3465-8 40-4658-6 56-8468-5 94-7785-3 37-5764-8 34-9754-7 72-9375-4 37-5490-6 20-3454-9 76-5475-4 27-3457-4

Checking Checking Savings Checking Checking Checking Checking Savings Checking Checking Checking Savings Checking Checking Checking Checking Savings Checking Checking

5. Open the sbfTransactions form in Design View.


Add a Text Box to the Form Footer section. Name it txtWithdrawals. Set it to get the sum of withdrawals Add another Text Box named txtDeposits that gets the sum of the deposits Add another Text Box named txtServiceCharges that gets the sum of the service charges Set the Format of these text boxes to currency and that display 2 Decimal Places

Reduce the heights of these text boxes completely and position them just under the Form Footer bar, then hide them from the user Save and close the form

6. Open the CustomersTransactions form in Design View


Add a Text Box below the subform. Name it txtTotalDeposits and make it displays the value of the txtDeposits control from the sbfTransactions. Also, set its Format to Currency and to display 2 Decimal Places Add another Text Box below the subform. Name it txtTotalWithdrawals and make it displays the value of the txtWithdrawals control from the sbfTransactions. Also, set its Format to Currency and to display 2 Decimal Places Add another Text Box below the subform. Name it txtTotalCharges and make it displays the value of the txtServiceCharges control from the sbfTransactions. Also, set its Format to Currency and to display 2 Decimal Places Add another Text Box below the subform. Name it txtCurrentBalance. Make it subtract the value of the txtTotalWithdrawals text box from the value of the txtTotalDeposits text box.

362

Also, set its Format to Currency and to display 2 Decimal Places

Save and close the form

Watts A Loan
Open the Watts A Loan database Open the sbfAccountTransactions form in Design View. Add a Text Box to the Form Footer section of the form. Set its Name to txtTransactions. Make it get the sum of the TransactionAmount values. Set its Format to Currency for 2 Decimal Places. Reduce its height and hide it Save and close the form

Built-In Functions Fundamentals


Conditional Functions
The Choose Function
Once again, since Microsoft Access doesn't inherently provide a programming environment, it relies on logical functions to take care of this aspect. The Choose() function is one of those that can test a condition and provide alternatives. The Choose() function works like nested conditions. It tests for a condition and provides different outcomes depending on the result of the test. Its syntax is: Choose(Condition, Outcome1, Outcome2, Outcome_n) The first argument of this function is the condition that should be tested. It should provide a natural number. After this test, the Condition may evaluate to 1, 2, 3, or more options. Each outcome is then dealt with. The first, Outcome1, would be used if the Condition produces 1. The second, Outcome2, would be used if Condition produces 2, etc.

The Switch Function


We have seen that the IIf() function is used to check a condition and can perform one of two statements depending on the result of the condition. In some expressions, there will be more than one condition to check. Although you can nest IIf() functions to create a complex expression, Microsoft Access provides another function that can perform this task. The function is called Switch and its syntax is: Switch(Expression1, What To Do If Expression1 Is True,

363

Expression2, What To Do If Expression2 Is True, Expression_n, What To Do If Expression_n Is True) Unlike IIf(), the Switch() function does not take a fixed number of arguments. It takes as many combinations of <Expression -- Statement>s as you need. Each expression is evaluated. If the expression evaluates to true, the statement that follows it executes. Although you can spend a great deal of time tuning a conditional expression such as one involving a Switch() function, it is still possible that none of the expressions evaluates to true. In this case, you can add a last expression as True and provide a subsequent statement to use. The syntax you would use is: Switch(Expression1, What To Do If Expression1 Is True, Expression2, What To Do If Expression2 Is True, Expression_n, What To Do If Expression_n Is True, True, What To Do With A False Expression)

Practical Learning: Using the Switch Function


1. From the resources that accompany this book, copy the Operations database and paste
it in your Exercises folder

2. Open the Operations database and, on the Database window, click the Forms button (it
should be clicked by default). The double-click frmSwitch to open it in Design View 3. On the form, click the Result text box and, on the Properties window, click Control Source and change it as follows (on one line): =Switch([fraOperations]=1,Nz([txtNumber1])+Nz([txtNumber2]), [fraOperations]=2,Nz([txtNumber1])-Nz([txtNumber2]), [fraOperations]=3,Nz([txtNumber1])*Nz([txtNumber2]), [fraOperations]=4,Nz([txtNumber1])/Nz([txtNumber2]))

3. Test the form:

4. Save it

Arithmetic Functions
The Absolute Value
The decimal numeric system counts from minus infinity (-) to infinity (+). This means that a number can be usually negative or positive, depending on its position from 0, which is considered as neutral. In some operations, the number considered will need to be only positive even if it is provided in a negative format. The absolute value of a number x is x if the number is (already) positive. If the number is negative, then its absolute value is its positive equivalent. For example, the absolute value of 12 is 12, while the absolute value of 12 is 12. To get the absolute value of a number, you can use one of the Abs() function. Its syntax is: Abs(number)

364

The Exponential
The Exp() function is used to calculate the exponential value of a number. Its syntax is: EXP(number) The argument, number, a double-precision value, represents the number to be evaluated. If the value of number is less than -708.395996093 (approximately), the result is reset to 0 and qualifies as underflow. If the value of the argument x is greater than 709.78222656 (approximately), the result is infinity and qualified as overflow.

The Square Root


The Sqr() function is used to calculate the square root of a double-precision number. Its syntax is: Sqr(number) This function takes one argument as a positive floating number. After the calculation, the function returns the square root of x.

String Functions
Character Retrieval
The Chr() function is used to retrieve a character based on an ASCII character number passed to the function. It could be used to convert a number to a character. It could also be used to break a line in a long expression. The syntax of this function is: Chr(Number) Based on the table of ASCII characters, a call as Chr(65) would produce the letter A. Not all ASCII characters produce a known letter. For example, when Chr(10) is used in a string, it creates a new line.

The Message Box


A message box is a special form used to display some information to the user. As opposed to a regular form, the user cannot type anything on the box. There are usually two ways you can use a message box: You can simply display a message to the user, or you can get an answer from her. If you only want to display a message, the syntax you would use is: MsgBox(Message To Display, Flag, Caption) This function takes only one required argument, the message, and some optional arguments. You use the name of the function, MsgBox, to create a message box. Between its parentheses, type the desired message to display. An example would be: MsgBox(Remember to submit your time sheet) If you want to display the message box on various lines, edit the string to include a call to Chr(10). Here is an example: MsgBox(Remember to submit your time sheet + Chr(10) Only time sheets received on time will be honored, ) The message to display can also be created as an expression. After providing the message, you can display it without the other arguments. Here is an example of a message box created with MsgBox("Remember to submit your time sheet")

365

After the message, as mentioned already, the other argument are optional. If you provide only the message, the message box displays the OK button. The second argument allows you to specify the button(s) to display. The options are as follows: Value 0 1 2 3 4 5 If you provide a value other than those in the list, the message box would display only the OK button. Here is an example of a message box created with: MsgBox("Do you want to submit your time sheet?",4) Buttons

Besides displaying a button, the second argument is also used to display an icon. To get an icon, you add one of the following values: Value 16 32 48 64 Icon Suited when Warning the user of an action performed on the database Informing the user of a non-critical situation Asking a question that expects a Yes or No, or a Yes, No, or Cancel answer A critical situation or error has occurred. This icon is appropriate when informing the user of a termination or deniability of an action

To use one of these icons, add (a simple addition) its value to that of the desired button or combination of buttons from the previous table. Here is an example created with MsgBox("Do you want to submit your time sheet?", 32 + 4) The same as: MsgBox("Do you want to submit your time sheet?", 36)

366

When the buttons of a message box displays if the message box has more than one button, one of them has a thick border. This button is referred to as the default button. If the user presses Enter, such a button would be activated. Besides selecting the buttons and displaying an icon, the second argument can also be used to specify what button would have focus, that is, what would have a thick border and would be applied if the user presses Enter, on the message box. The default button is specified using one of the following values: Value If the message box has more than one button, the default button would be If the message box has more than one button, the default button would be The first button The second button The third button The fourth button add the number to the button and/or icon value(s).

Value 0 256 512 768 To specify this option,

The third argument of the MsgBox function, Caption, is the string that would display on the title bar of the message box. It is a string whose word or words you can enclose between parentheses or that you can get from a created field. As mentioned already, you can create a message to simply display a message to the user. Because MsgBox is a function, you can also retrieve the value it returns and use it as you see fit. The value this function returns corresponds to the button the user clicks on the message box. Depending on the buttons the message box is displaying, after the user has clicked, the MsgBox function can return one of the following values: Displayed Button(s) If the user clicked The return value is 1 1 2 3 4 5 6 7 2 6

367

7 4 2

Date and Time


The Values of the Current Date and Time
Microsoft Access provides various functions to perform date and time related operations. These functions allow you to add dates or times, find the difference between dates or times, or add constant values to dates or times. The current date is represented by a function called Date() while the current time of the computer is represented by a function called Time(). These two values (the current date and the current time) can be combined and are represented by a function called Now().

Practical Learning: Setting Current and Time on Data Fields


1. Open the Bethesda Car Rental2 database and click Tables in the Database window
2. Double-click the OrderProcessing table to open it 3. After viewing the table, switch it to Design View 4. Click OrderDate and press F6

5. In the lower section of the table, click Default Value. Type =Date() and press Enter 6. In the upper section of the table, click OrderTime and press F6 7. In the lower section of the table, click Default Value. Type =Time() and press Enter
8. Save the table and switch it to Datasheet View

Adding to a Date
Operations on dates and times are performed using functions such as DateAdd() and DateDiff(). The DateAdd() function is used to add an interval date value to the specified date. It is used to add a number of days, weeks, months, or years to another date. The syntax of the DateAdd() function is DateAdd(Interval, Number, date) The Interval argument is required and it specifies the kind of value needed as a result. This argument is passed as a string, thus enclosed between double quotes and can have one of the following values: Interval s n h w ww d y m q yyyy Used To Get Second Minute Hour Numeric Weekday Week of the Year Day Numeric Day of the Year Month Quarter Year

368

The Number argument is required also. It specifies the number of units you want to add. If you set it as positive, its value will be added. If you want to subtract, make it negative. The date argument is the date to which you want to add the number.

Subtraction From a Date


The DateDiff() function is used to find the difference between two date or time values. It allows you to find the number of seconds, minutes, hours, days, weeks, months, or years when you supply two recognizable values. The DateDiff() function takes 5 arguments, 3 are required and 2 are optional. The syntax of the function is DateDiff(Interval, Date1, Date2, Option1, Option2) The Interval argument is required and it specifies the kind of value you want as a result. This argument is passed as a string and can have one of the following values: Interval s n h w ww d y m q yyyy Used To Get Second Minute Hour Numeric Weekday Week of the Year Day Numeric Day of the Year Month Quarter Year

Required also, the Date1 and Date2 arguments specify the date or time values that will be used when performing the operation. By default, the days of a week are counted starting on Sunday. If you want to start counting those days on another day, supply the Option1 argument using one of the following values: 1, 2, 3, 4, 5, 6, 7. There are other variances to that argument. If your calculation involves weeks or finding the number of weeks, by default, the weeks are counted starting January 1st. If you want to count your weeks starting at a different date, use the Option2 argument to specify where the program should start. For our time sheet that we want employees to use, we will use a series of combo boxes so the user can only select the time instead of typing it. This reduces the likelihood of errors. When an employee signs a time sheet, he or she can select both starting and ending shifts. We should develop a basic algorithm that can solve our problem in a simple but effective manner. We need to make sure that the start time is less than or equal to the end time. In the same way, the end time should be set higher or equal to the start time. Since we cannot prevent the user from selecting a start time that is higher than the end time or from selecting an end time that is less than the start time, we will set the result to 0 hours whenever the user selects an invalid time sequence. We will start with the following pseudo-code: IF Time Out is greater than or equal to Time In THEN We can calculate the time OTHERWISE Set the shift value to 0 END IF This translates to

369

IF TimeOut >= TimeIn THEN Result = TimeOut - TimeIn ELSE Result = 0 END IF Now, we need to figure out how to calculate the time difference. Because the result will be used to calculate the employee's salary using the hourly wage, we need to have this result as a number, namely a decimal number (as 0.00). If we use the DateDiff() function, we can calculate the minutes or the hours value of the difference. If both start and end times are divisible by 60, as in 09:00 AM to 05:00 PM, the difference can be easily calculated to produce the number of hours, in this case 8.00. To find out if a number is divisible by another number, we can use the Mod operator. This can be done as follows: IF (TimeOut - TimeIn) Mod 60 = 0 Result = TimeOut - TimeIn END IF ' The difference is evaluated in minutes ' The result is calculated in hours

If one of either the start or end time doesn't fall on a straight hour value, the resulting time will have a decimal value of 0.50. Therefore, we need to calculate the time difference in minutes instead of hours. Since we are dealing with minutes this time, we can divide the difference by 60 to get the result in minutes. Our pseudo-code would become: IF (TimeOut - TimeIn) Mod 60 = 0 Result = TimeOut - TimeIn OTHERWISE Result = TimeOut - TimeIn ' The difference is evaluated in minutes ' The result is calculated in hours ' The result is calculated in minutes

Now that we know how to calculate the time difference, we can include our pseudo-code with the original that would reset the result to 0 if the user selects a wrong time sequence.

Practical Learning: Using Dates and Times


1. Open the Bethesda Car Rental1 assuming that you had created the time sheet form
2. Open the TimeSheet form 3. Click the total text box for Monday and, in the Properties window, click the ellipsis of the Control Source field

4. On the Expression Builder dialog box, type the following expression:

Which is: =IIf( IIf(DateDiff("n",[MondayIn],[MondayOut]) Mod 60=0,

370

0)

DateDiff("h",[MondayIn],[MondayOut]), DateDiff("n",[MondayIn],[MondayOut])/60)>=0, IIf(DateDiff("n",[MondayIn],[MondayOut]) Mod 60=0, DateDiff("h",[MondayIn],[MondayOut]), DateDiff("n",[MondayIn],[MondayOut])/60),

5. Click OK

6. Set the Format to Fixed and the Decimal Places to 2


7. In the Properties window, right-click Control for the same Monday total and click Copy 8. Open Notepad, right-click inside of Notepad and click Paste 9. Press Ctrl + Home. On the main menu of Notepad, click Edit -> Replace...

10. In the Find What text box, type Mon and press Tab 11. In the Replace With text box, type Tues and click Replace All
12. On the Replace dialog box, click Cancel 13. Right-click in Notepad and click Select All. Right-click again and click Copy 14. In Microsoft Access, click the total for Tuesday 15. In the Properties Window, right-click Control Source and click Paste

16. Set the Format to Fixed and the Decimal Places to 2


17. Use the same steps to get the total for the remaining days 18. Click the Weekly Total text box and set its Control Source to =Nz([txtMonday])+Nz([txtTuesday])+Nz([txtWednesday])+Nz([txtThursday]) +Nz([txtFriday])+Nz([txtSaturday])+Nz([txtSunday])

19. Set its Format to Fixed and the Decimal Places to 2 20. Save the form and preview it

371

21. Perform a few selections for different shifts

22. Close the form

23. Open the Bethesda Car Rental2 database


24. In the Database window, click Forms and double-click the OrderProcessing form to open it 25. After viewing the form, switch it to Design View

26. On the form, double-click the text box on the right side of Days 27. In the Properties window, click the All tab and click Control Source
Type =DateDiff("d", StartDate, EndDate) and press Enter

28. On the form, click the text box on the right side of the Sub-Total label 29. In the Properties window, click Control Source. Type
=Nz(RateApplied) * Nz(txtNumberOfDays) and press Enter =CLng([txtSubTotal]*[TaxRate]*100)/100

30. Click the box to the right the Tax Amount label and set its Control Source property to 31. On the form, click the text box to the right of Rent Total 32. In the Properties window, set its Control Source to
33. Save and close the form 34. Open the RentalRates form and open the OrderProcessing form to display both on the screen 35. Perform a few rental orders =(CLng([txtSubTotal]*[TaxRate]*100)/100) + txtSubTotal

372

36. Close both forms

373

You might also like