Professional Documents
Culture Documents
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
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.
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:
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
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...
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:
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.
5. Click Open
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
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
2. Double-click Employees
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
2. Double-click MembersByGender
12
2. Double-click Camps
2. Double-click Camps
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.
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 )
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
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.
18
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
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.
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
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
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
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
19. To close the CompanyAssets table, click its system Close button 25
Model
26
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
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.
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.
AssetType Printer Computer Laptop Printer Digital Camera Computer Computer Ctrl + '
Model
Gateway 200XL
10/20/2002 1120.55
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.
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
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:
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
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.
2. On the Database window, click the Queries button and click the Employees Pay 31
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
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
5. Click OK
10. Accept the name of the form as CompanyAssets and click Finish
An automatic form is created for you
34
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
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
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
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.
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
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
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.
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
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
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.
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.
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
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
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.
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.
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..
2. In the New dialog box, click General if necessary. Make sure Database or Blank Database is selected and click OK
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
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:
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.
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.
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
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.
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.
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
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
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
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.
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.
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.
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.
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
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,
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.
3. On the New Table dialog box, click Design View and click OK
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.
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.
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
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
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
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
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
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
8. Click OK 9. To add another field, click Address 10. On the main menu, click Insert -> Rows
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.
60
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...
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
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.
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
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
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
23. Notice a vertical line that guides you. Drag left until the vertical guiding line gets between
Make and Model:
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
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
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
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
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.
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
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.
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
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.
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).
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
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.
2. On the New Report dialog box, make sure Design View is selected and the combo box is empty. Then click OK
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.
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.
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.
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.
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
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
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)
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.
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
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.
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
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.
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
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
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.
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.
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.
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
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.
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
90
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
3. To display the Properties window, double-click the button at the intersection of the rulers
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.
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.
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.
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.
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.
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
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
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:
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
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.
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.
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
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.
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
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
21. Click different field and observe the message on the status bar 100
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
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
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.
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
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
. 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
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.
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.
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
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.
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:
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.
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.
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
. 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
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
117
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
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.
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
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
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.
In some other cases, the assignment operator will be part of a longer expression. We will see examples we move on.
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.
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:
126
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
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
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 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
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.
130
Note that the > and the <= operators are opposite each other.
131
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
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.
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.
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
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
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.
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
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
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.
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.
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:
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
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
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
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.
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
DayOfWeek Text
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
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:
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
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.
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
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
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.
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.
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
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
Caption Video ID
Field Size
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.
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
159
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
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.
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
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
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:
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:
Field Name
Data Type
ChargeReasonID AutoNumber
163
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.
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
9. Then enter the number of the DirectorID from the Directors table to the corresponding
Director in the Videos table
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.
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
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
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
170
If you are using Microsoft Access >= 2000, print the Relationships diagram and save it as Watts A Loan Map
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.
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
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.
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
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
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).
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:
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
Exercises
Watts A Loan
Open the Watts A Loan database and configure the cascading of relationships as follows:
178
If you are using Microsoft Access >= 2000, print the Relationships dialog box and save its report as YNB Main Diagram
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.
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
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
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
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.
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
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.
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.
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
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
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.
Of course, there are situations in which these rules can or must be applied differently. When in case, you will be appropriately directly.
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
2. To get a list of students who were born before January 1, 1988, right-click the Date of
Birth field, click Filter For:
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
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.
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;
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
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;
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
194
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
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
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
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
45. After viewing the query, close it. When ask whether you want to save it, click Yes
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.
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
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
Exercises
Watts A Loan
Open the Watts A Loan database and configure the relationships among its tables as follows:
203
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.
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.
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
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
23. To get a list of employees whose salary is greater than $10 AND live in MD, in the Criteria for
Salary, type >=10
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
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
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.
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
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:
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...
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
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.
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
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
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
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.
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.
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
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.
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.
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
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.
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.
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
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.
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
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.
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.
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
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.
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
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.
231
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.
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
20. Save the form 21. Print and close the form
Action Queries
233
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
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.
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
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 );
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
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'.
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
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
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
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
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
247
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
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.
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.
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)
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.
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
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
253
6. Click OK
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 Next
7. On the 2nd page, make sure the First Row Contains Column Headings check box is 255
10. To view the table in Microsoft Access, double-click the Employees linked table 11. After viewing the table, close 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
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.
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
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
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
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
262
4. Click OK twice 5. Return to Microsoft Access and open the CompanyAssets table
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
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).
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.
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.
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
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
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
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 .
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
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;
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-
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.
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.
4. Click OK
275
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
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
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.
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
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
278
To center the form by default whenever it comes, set its Auto Center Boolean property to Yes.
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.
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.
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
280
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
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.
281
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
282
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.
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
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.
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.
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.
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.
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
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.
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.
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
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.
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
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
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.
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
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:
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.
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
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.
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
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.
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).
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
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
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.
305
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.
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
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.
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
4. Create and design a form based on the Transactions table. Save it as Transactions
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 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.
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
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
313
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.
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
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.
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.
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.
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
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:
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.
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
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
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.
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
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
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.
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
326
14. On the first page of the Subform/Subreport Wizard, click the arrow of the combo box and
select sbfCustomers
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
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.
2. Set the first Field Name to OrderAndPartsID and set its Data Type to AutoNumber. Also, make it a Primary Key
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
16. Click just under the Form Header bar on the left side:
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
. 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:
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
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:
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]
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
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
337
12. Save and close it. Click the Customer text box (the text box on the right side of the Customer: label)
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
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.
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.
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.
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
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
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
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")
4. On the Toolbox, click Text Box 5. Click on top of the DriversLicNbr text box
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.
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.
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)
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.
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
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
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.
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
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>>
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.
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")
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])
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.
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
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
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.
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
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
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
362
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
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)
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]))
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.
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.
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).
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
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.
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.
370
0)
5. Click OK
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
19. Set its Format to Fixed and the Decimal Places to 2 20. Save the form and preview it
371
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
373