Upload
others
View
6
Download
0
Embed Size (px)
Citation preview
Chapter 1. Database Models and Design.............................................................3
1.1. Schemas, Instances and Database States...................................................................5
1.2. A Database application Design.......................................................................................9
1.3. The Entity-Relationship Model....................................................................................111.3.1. Entities and attributes...................................................................................................................111.3.2. Relationships................................................................................................................................121.3.3. The Entity Relationship diagrams................................................................................................15
1.4. Implementing an Entity Relationship model as a Microsoft Access data model...........................................................................................................................................17
1.4.1. Entities representation..................................................................................................................171.4.2. Relationships representation.........................................................................................................191.4.3. Rules of Databases Normalization...............................................................................................211.4.4. Referential Integrity......................................................................................................................22
1.5. Refining the Design.............................................................................................................23
1.6. Objects and Naming Conventions...............................................................................23
1.7. The Northwind Database..................................................................................................24
Chapter 2. Queries....................................................................................................................28
2.1. Create queries using the Query Wizard...................................................................302.1.1. Simple queries..............................................................................................................................312.1.2. Crosstab Queries...........................................................................................................................402.1.3 Find Duplicates Queries................................................................................................................452.1.4. Find Unmatched Queries.............................................................................................................47
2.2. Create queries without a Query Wizard..................................................................48
2.3. The Expression Builder.....................................................................................................50
Chapter 3. Form Basics....................................................................................................57
3.1. The AutoForm Wizard.......................................................................................................58
3.2. The Form Wizard..................................................................................................................60
3.3. The Chart Wizard..................................................................................................................62
Chapter 4. Reports....................................................................................................................68
4.1. Creating AutoReports.........................................................................................................70
4.2. Using the Report Wizard..................................................................................................71
4.3. Creating a Chart Report...................................................................................................77
4.4. Adding a chart to an existing report...........................................................................77
4.5. Changing a Report Design.............................................................................................78
Chapter 5. Customizing forms.....................................................................................79
5.1. Bound, Unbound, and Calculated Controls...........................................................81
5.2. Text Boxes.................................................................................................................................82
5.3. List boxes and Combo boxes.........................................................................................845.3.1. Displaying a Value list.................................................................................................................855.3.2. Displaying a list of fields from a table or a query........................................................................885.3.3. Creating a form to update a table.................................................................................................905.3.4. Controlling Entry of New Values in a Combo Box.....................................................................91
5.4. Ensuring Correct Data Entry..........................................................................................92
1
5.5. Check Boxes, Option Buttons and Toggle Buttons..........................................93
5.6. Option Groups.........................................................................................................................94
5.7. Command buttons.................................................................................................................96
Chapter 6. Using Macros...................................................................................................97
6.1. Creating, Saving and Running a Macro...................................................................97
6.2. Macro Groups........................................................................................................................100
6.3. Referring to Control Names in Expressions.......................................................102
6.4. Macros Conditions..............................................................................................................103
6.5. Finding problems in macros: Single Stepping...................................................104
6.6. Using Macros in Forms...................................................................................................1066.6.1. Opening a form from another form............................................................................................1076.6.2. Synchronizing two forms to show related records.....................................................................1096.6.3. Using the OnCurrent property to keep two Open Forms Synchronized....................................110
6.7. Special Macros: AutoExec and AutoKeys.........................................................113
Chapter 7. Communication with other Applications.........................115
7.1 Merging Access Data with Word Documents.....................................................1167.1.1. Creating a mail-merge document...............................................................................................1167.1.2. Merging to a linked document....................................................................................................119
7.2. Publishing data with Microsoft Word.....................................................................119
7.3. Analyzing Data with Excel...........................................................................................120
Chapter 8. Database Administration...................................................................121
8. 1. Backing Up a Database..................................................................................................121
8.2. Compacting a Database...................................................................................................122
8.3. Encrypting a Database......................................................................................................123
8.4. Recovering a Damaged Database..............................................................................123
8.5. The Database Performance Analyzer Wizard....................................................124
8.6. Documenting a Database................................................................................................125
Chapter 9. Applying Security to the Database..........................................126
9.1. Setting a Database Password........................................................................................127
9.2. Implementing the User-Level Security..................................................................1289.2.1. Creating and Using Workgroup Information Files.....................................................................1289.2.2. Defining User and Group Accounts...........................................................................................131
9.3. The User-Level Security Wizard...............................................................................134
9.4. Setting User and Group Permissions.......................................................................135
Chapter 10. Access and the Internet....................................................................137
10.1. Including Hyperlinks in a database.......................................................................13810.1.1. Hyperlink addresses:................................................................................................................13810.1.2. Hyperlink Fields.......................................................................................................................13910.1.3. Adding Hyperlinks to forms and reports..................................................................................140
10.2. Publishing data from a database to the Web....................................................14010.2.1. Exporting Static Web Pages.....................................................................................................14110.2.2. The Publish to the Web Wizard................................................................................................141
2
10.3 Importing and Linking data from Web Pages into an Access database...................................................................................................................................................................144
REFERENCES...........................................................................................................................................144
3
Chapter 1. Database Models and Design
Databases and database technologies have a major impact on the growing use of
computers. It is fair to say that databases play a critical role in almost all areas where
computers are used, including banks, business, engineering, medicine, law, education,
libraries, etc. In the past few years, advances in technology have been leading to new
applications of data base systems. Multimedia databases can now store pictures, video
clips and sounds. Geographic Information Systems (GIS) can store and analyze maps,
weather data and satellite images. Real-time and active database technology is used in
controlling industrial and manufacturing processes.
A database is a collection of related data. By data, we mean known facts that can be
recorded and that have implicit meaning. For example, consider the names, telephone
numbers and addresses of the people you know. You may have this data recorded in an
address book, or you may have stored it in a database.
A database can be of any size and of varying complexity. For example, a database of
a large library may contain half a million of records that can be organized under different
categories-by primary author’s last name, by subject, by book title.
A database may be created and maintained either by a group of application programs
written specially for that task or by a database management system. A database
management system (DBMS) is a collection of programs that enables users to create and
maintain a database.
The structure of a database is defined using a data model . By structure of a database
we mean the data types, relationships and constraints that should hold on the data. A
high-level or conceptual data model provide concepts that are close to the way many
users perceive data, whereas low-level or physical data models provide concepts that
describe the details of how data is stored in the computer. Concepts provided by low-
level data models are generally meant for computer specialists, not for typical end users.
Between these two extremes is a class of representational (or implementation) data
4
models, which provide concepts that may be understood by end users but that are not too
far from the way data is organized within the computer.
Conceptual data models use concepts such as entities, attributes and relationships. An
entity represents a real-world object or concept, such as an employee or a project that is
described in a database. An attribute represents some property of interest that further
describes an entity, such as the employee’s name or salary. A relationship among two or
more entities represents an interaction among the entities, for example, a „works-on“
relationship between an employee and a project. The Entity-Relationship model, which
is used in the Microsoft Access Database Management System, is such a conceptual data
model.
Example: the COMPANY database
To exemplify different database concepts, we will consider a particular database
application.
The COMPANY database keeps track of a company’s employees, departments and
projects.
Suppose the following description of the database requirements:
1. The company is organized into departments. Each department has a unique
name, a unique number and a particular employee who manages the department.
The database must keep track of the start date when that employee began
managing the department. A department may have several locations.
5
2. A department controls a number of projects, each of which has a unique name,
a unique number and a single location.
3. We store each employee’s name, address, salary and birth date. An employee is
assigned to one department but may work on several projects, which are not
necessarily controlled by the same department.
The database must keep track of the number of hours per week that an employee
works on each project.
This description highlights the entities, the attributes and the relations between entities:
Entities (Objects): departments, employees, projects.
Entities characteristics: department name, employee’s name, address, salary, etc.
Relations between Entities: department control projects,
Employee assigned to department
1.1. Schemas, Instances and Database States
In any data model it is important to distinguish between the description of the
database and the database itself. The description of a database is called the database
schema, which is specified during database design and is not expected to change
frequently. Most data models have certain conventions for displaying the schema as
diagrams. For example, a preliminary database schema for the COMPANY database,
derived from the previous description, may be displayed as in the figure 1. 1.
The diagram displays the structure of each record type but not the actual instances of
records.
The actual data in a database may change quite frequently. For example, the
employees, the salaries, the projects, etc. The data existent in a database at a particular
moment in time is called a database state or snapshot. Figure 1. 2 illustrates a possible
state of the COMPANY database.
The distinction between the database schema and a Database State is very
6
important. When we define a new database, we specify its database schema only to the
DBMS. At this point, the corresponding Database State is the empty state, with no data.
The initial state of a database is the state after the database is first populated or loaded
with initial data. Every time an update operation is applied to the database, we get
another Database State. At any point in time, the database has a current state. The DBMS
is partly responsible for ensuring that every state of the database is a valid state-that is, a
state that satisfies the structure and constraints specified in the schema.
Figure 1.1. Preliminary schema diagram for the COMPANY database.
7
Figure 1. 2. A state of the COMPANY database.
The architecture of a database can be described at three levels of abstraction
(see figure 1.3):
1. The internal level
An internal schema describes the physical storage structure of the database. The internal
schema uses a physical data model and describes the complete details of data storage and
access paths for the database.
2. The conceptual level
A conceptual schema describes the structure of the whole database for a community of
users. The conceptual schema hides the details of physical storage structures and
concentrates on describing entities, data types, relationships, user operations and
constraints. A high-level data model or an implementation data model can be used at this
level.
8
Figure 1. 3. The three-schema architecture.
3. The external or view level
This level includes a number of external schemas or user views. Each external schema
describes the part of the database that a particular user group is interested in and hides the
rest of the database from that user group. A high-level data model or an implementation
data model can be used at this level.
9
1.2. A Database application Design
Figure 1. 4 shows a simplified description of a database application design
process. This process begins after the Requirements Collection and Analysis. During
this first step, the analyst interview prospective database users to understand and
document their data requirements. The result of this state is a concisely written set of
users’ requirements. These requirements should be complete and enough detailed.
In parallel with specifying the data requirements, it is useful to specify the
known functional requirements of the application. These consist of the user-defined
operations (or transactions) that will be applied to the database, and they include both
retrievals and updates.
Once all the requirements have been collected and analyzed, the next step is to
create a conceptual schema for the database, using a high-level conceptual data model.
This step is called conceptual design. The conceptual schema is a concise description of
the data requirements of the users and includes detailed descriptions of the entity types,
relationships and constraints. These are expressed using the concepts provided by the
high-level data model. Because these concepts do not include implementation details,
they are usually easier to understand and can be used to communicate with nontechnical
users. A high-level conceptual schema can also be used as a reference to ensure that all
users data requirements are met and that the requirements do not include conflicts. This
approach enables the database designers to concentrate on specifying the properties of the
data, without being concentrated with storage details.
The next step in database design is the actual implementation of the database,
using a commercial DBMS. Most current commercial DBMSs use an implementation
data model-such as the relational or the object database model-so the conceptual schema
is transformed from the high-level data model into the implementation data model. This
step is called logical design or data model mapping and its result is a database schema in
the implementation data model of the DBMS.
10
Figure 1.4. The main phases of a database application design.
Finally, the last step is the physical design phase, during which the internal
storage structures, access path and file organizations for the database files are specified.
In parallel with these activities, application programs are designed and implemented as
database transactions corresponding to the high-level transaction specifications.
11
1.3. The Entity-Relationship Model
The Entity-Relationship Model is a popular conceptual data model.
1.3.1. Entities and attributes
An entity is a „thing“ in the real world with an independent existence. An entity may be
an object with physical existence – a particular person, a car, an employee- or may be an
object with a conceptual existence – a company, a job, a university course. Each entity
has attributes – the properties that describe it. For example, an employee entity, in the
COMPANY database design, may be described by the employee’s name, address, salary,
birth date, the department to which he/she is assigned, the projects he or she is working.
A particular entity will have a value for each of its attributes. The attribute values that
describe each entity become a major part of the data stored in the database. For example,
the attribute values of a particular employee entity can be: „Judy Clark“, „Rosenweg 13“,
„25K“, „12.03.1970“, „01“, „01 (20)“ (see figures 1.1, 1.2).
Entity Types and Entity Sets
A database usually contains groups of entities that are similar. For example, a
company employing hundreds of employees may want to store similar information
concerning each of the employees. These employee entities have the same attributes, but
each entity has its own value for each attribute. An entity type defines a collection (or
set) of entities that have the same attributes. Each entity type is described by its name and
attributes. The collection of all the entities of the same type is usually referred to using
the entity type name. Ex: EMPLOYEE refers to both a type of entity as well as the
current set of all employee entities in the database.
Key attributes of an Entity Type
An entity type usually has an attribute whose values are distinct for each
individual entity in the collection. Such an attribute is called a key attribute, and its
12
values can be used to identify each entity uniquely. For example, the „number“ attribute
of the „Department“ entity type can be used as a key attribute because no two
departments are allowed to have the same number. Sometimes, several attributes together
form a key, meaning that the combination of the attribute values must be distinct for each
entity.
1.3.2. Relationships
In an initial phase of the COMPANY database conceptual design, three types of
entities were defined: EMPLOYEE, DEPARTMENT and PROJECT. These are
represented together with their attributes, in the preliminary schema diagram from the
figure 1. 1.
There are several implicit relationships among these entity types. In fact,
whenever an attribute of one entity type refers to another entity type, some relationship
exists. For example, the attribute ControllingDepartment of the PROJECT refers to the
department that controls the project. Department of the EMPLOYEE refers to the
department for which the employee works, and so on. In the ER model, these references
should not be represented as attributes but as relationships. For example, we can define a
relationship type WORKS_FOR between the entity types EMPLOYEE and
DEPARTMENT, which associates each employee with the department the employee
works for (see figure 1. 5).
The WORKS_FOR relationship is of type N:1, or many to one, because it
associates one or more employees with one department.
Suppose each employee can be associated with many departments. In this case,
the relationship, lets name it WORKS_FOR_MANY is of type M:N, or many to many
(see figure 1. 6).
13
Figure 1. 5. The WORKS_FOR relationship (many to one)
Figure 1. 6. The WORKS_FOR_MANY relationship (many to many).
14
Each employee works on many projects and many employees can work on the
same project. The relationship WORK_ON, between the entity types EMPLOYEE and
PROJECT is of type many to many (figure 1. 7).
Each department has a unique employee that is the manager. The relationship
MANAGES (figure 1.8), between the entity types EMPLOYEE and DEPARTMENT is
of type 1:1 (one to one). Other types of relations are of type min:max. For example, 0:N,
1:10, 4:M, etc
Figure 1. 7. The WORK_ON relationship (many to many).
Relationships with attributes
An employee starts managing a department at a certain date. The starting date is
an attribute of the relation between an employee and a department. This relationship,
MANAGES, is of type 1:1. For this reason, the relationship attribute StartDate can be
represented also, either as an EMPLOYEE attribute, either as a DEPARTMENT
attribute.
For a 1:N relationship type, a relationship attribute can be migrated only to the
entity type at the N-side of the relationship. For example, the relationship WORKS_FOR
15
Figure 1. 8. The MANAGES relationship (one to one).
can have an attribute StartDate, indicating when an employee started to work for a
department. This attribute can be included as an attribute of the EMPLOYEE.
For M:N relationship types, some attributes may be determined by the combination of
participating entities, not by a single entity. Such attributes must be specified as
relationship attributes. An example is the attribute Hours of the relationship WORK_ON.
An employee works a different number of hours to each project. The number of hours an
employee works on a project is determined by an employee-project combination and not
separately by either entity.
1.3.3. The Entity Relationship diagrams
There are many types of notations used to represent entities and relationships.
Examples of such notations are exemplified in the figures 1. 9, 1.10 and 1.11. Figure 1.10
adds the attributes to each entity type. Figure 1.11 is an equivalent representation in the
Unified Modeling Language, which is now a de facto standard for software systems
modeling.
16
Figure 1.9. ER diagram of the COMPANY database.
Figure 1.10. ER diagram of the COMPANY database, with attributes.
17
Figure 1. 11. The UML model of the COMPANY database.
1.4. Implementing an Entity Relationship model as a Microsoft Access data model
1.4.1. Entities representation
In the Microsoft Access data model, the set of all existent entities of a given
type is represented by a table. You can give the table the entity type name. For example,
the COMPANY database will contain at least 3 tables: EMPLOYEE, DEPARTMENT,
PROJECT.
Each entity from a table is displayed on a row (see figure 1.12. a). It is a record
of the table. All the rows have the same fields, which are displayed as the table columns.
Each entity attribute is represented by a field. The particular values of the
attributes of an entity are displayed on a row, as the values of the fields.
18
The Datasheet View of a table displays the entire content of the table, at the current
moment.
Figure 1.12. a. The datasheet view of the EMPLOYEE table.
The Design View of a table displays the attributes -that is, the fields- and the data
type of each attribute (figure 1.12. b).
Figure 1.12. b. The Design View of the EMPLOYEE table.
19
The attribute key of an entity type is named primary key of the table. In the diagram
from figure 1.13, the primary keys are displayed by bold characters.
1.4.2. Relationships representation
The one-to-many relationship is the most common type of relationship in a
relational database. It can be directly represented in Microsoft Access. To create such a
relationship, we add the field that contains the primary key on the „one“ side of the
relationship to the table on the „many“ side of the relationship. For example, the
department number, which is declared as the primary key in the DEPARTMENT table,
appears as a field in the table EMPLOYEE (see figure 1.13).
In a many-to-many relationship, a record in a table A can have more than one
matching records in table B and a record in table B can have more than one matching
records in table A. This type of relationship cannot be directly represented in the
Microsoft Access data model. The problem is solved by creating a third table that breaks
down the many-to-many relationship into two one-to-many relationships. We put the
primary key from each of the two tables into the third table. For example, to represent the
relation WORK_ON in the COMPANY database, we introduced the table named
EmployeesProjects, which contains all the links employee-project and associate to each
link the relationship attribute, Hours.
In the conceptual design, the locations of each department are represented by an
attribute of the DEPARTMENT entity. A project has only one location, which was
represented by an attribute of the PROJECT entity. A project can have the same location
as a department. For this reason, it is convenient to represent the locations in a separate
table. In this way, any modification of a location that is a department location and a
project location is made only in one place.
20
Figure 1.13. Relationships between the COMPANY database tables.
In a one-to-one relationship, a record in table A can have only one matching
record in table B and a record in table B can have only one matching record in table A.
This type of relationship is unusual because in many cases the information in the two
tables can simply be combined into one table. For example, to represent the relationship
MANAGES we introduced a field IsManager in the EMPLOYEE table, with possible
values Yes/No and the relationship attribute StartDate was represented by a field in the
DEPARTMENT table. Another possibility is two introduce a field ManagerID in the
DEPARTMENT table and to create a one-to-one relationship between the tables
DEPARTMENT and EMPLOYEE.
21
1.4.3. Rules of Databases Normalization
The translation of an Entity-Relationships model into a set of correlated database
tables is not so directly as it may seem at the first glance.
The normalization is the process of creating and relating tables according to a
fixed set of rules. The most important three are the following:
All fields should be atomic, meaning that the data can’t be divided any further.
All fields in a table must be related to a primary key. A primary key field contains
a unique value for each record.
All fields must be mutually independent, meaning that no field depends on the
information in any other field in the same table.
The first rule
Let’s consider the Name attribute of the Employee type. Based on the first rule,
this attribute was represented by two fields in the EMPLOYEE table: FirstName and
LastName. If the name is represented in a single field it is very difficult to sort the table
by last name or to query the table by the employees last name. If we are interested to
query the EMPLOYEE table by some parts of the address (the country, the town) then the
address must be broken in more fields, like the country, the town, the street, etc.
Another concern is repetitive data in a single field. For example, consider we
represent the Locations attribute of the DEPARTMENT entity type by a field containing
the list of locations. In this case it would be very difficult to do operations based on a
particular location. A second solution would be to have several location fields, Location1,
Location2, Location3, etc. But in this case we must limit the number of locations and
many records will have empty fields because not all the departments have the same
number of locations. The best solution is to create a table containing all the locations.
This is the Locations table in the COMPANY database. The number of records of the
table is not limited. We introduced in this table a field containing the department number,
which is the primary key in the DEPARTMENT table.
22
The second rule
This rule requires each table to have a primary key. A primary key is usually a
single field that provides a unique identification of each record. A primary key can be
composed of more fields. In all operations involving the primary key, Access considers
all the fields declared as primary key.
The third rule
Sometimes, this rule is difficult to discern. The trick to finding dependent fields is
to consider changing the data. If that change affects any other data in the same table, a
problem exists. For example, if a table contains the fields price per unit, quantity and total
sum, then the field total sum depends of the field quantity and also of the field price per
unit. The field total sum must be eliminated. The total sum can be obtained by a query of
the table.
Relationships and Data Protection
Relationships help to protect the data in tables. For example, you cannot delete a
record from the DEPARTMENT table if there are records in the EMPLOYEE table,
containing the department number from that record.
Two tables are related based on a primary key and a foreign key. For example, the
DEPARTMENT table is a parent table that contains a primary key, DeptNumber. The
EMPLOYEE table is a child table that inherits the primary key as a foreign key. Then,
DeptNumber is a foreign key in the EMPLOYEE table.
1.4.4. Referential Integrity
Referential Integrity is another set of rules that Access uses to protect the relationships
between related tables. Referential integrity ensures that the relationship is valid and that
you don’t accidentally corrupt your data by adding or deleting records inappropriately.
Here are the conditions that referential integrity checks for:
Primary key fields must contain unique entries
23
Related fields must be the same data types.
Tables must be in the same database or be linked.
You can’t enter a value in a foreign key before entering it in the primary key field
You can’t delete a record from a parent table if a matching record exists in a
related (child) table.
You can’t change the primary key value in the parent table if that record has
related records.
1.5. Refining the Design
The last step of a database design is to analyze the design for errors. This is done
by loading the database with some sample data and then verify if the results obtained
from tables are correct. These first results enable to make some adjustments and
refinements to the initial design. It is easy to change the design of a database before the
database is created. It becomes much more difficult to make changes to tables after
they’re filled with data and after you have built forms and reports.
1.6. Objects and Naming Conventions
The Access objects are tables, forms, queries and reports.
Naming conventions are rules we are applying when we name the application
objects, that is: tables, queries, forms, reports, macros and others. One naming
convention, which is common in Windows programming, is the Hungarian convention.
Based on this convention an object name is prefixed with the object type. For example,
we can use the following prefixes:
tbl – for tables
qry – for queries
frm- for frames
rpt – for reports
24
For example, tblEmployee could be the name of a table, rptEmployee-the name for a
report, etc.
1.7. The Northwind Database
This database is provided as a sample with the Microsoft Access installation kit.
We will use it in many examples of queries, forms and reports.
The database contains data about the sales of a company, its employees and
customers. The aim of the database is to keep track of the sales orders, products, suppliers
and customers.
A sale order contains data such as:
- the employee which emitted the order;
- the list of products ordered;
- the order date;
- the customer;
- the destination country, and others.
For each product the database must register:
- the type of the product;
- the unit price;
- units in stock;
- the suppliers, and others.
In the mini-world of this database may be identified four types of entities:
- employees;
- customers;
- products;
- suppliers;
- orders;
25
The job of an employee is to emit sale orders. An employee emits more orders. Then, an
employee entity can be linked to many order entities at a time. Then, the relationship
between the entity types Employee and Order is a one-to-many relationship.
A product may have many suppliers. The relationship between the entity types
Product and Supplier is also a one-to-many relationship.
A customer may appear in many sale orders. Then, the relationship Customer-Order
is of type one-to-many.
By an order can be sold many products, each of them in a different quantity.
A product may appear in many orders. Therefore, the relationship between the entity
types Order and Product is a many-to-many relationship.
As we have seen, each entity type identified in the conceptual design phase is
represented by a table, in the logical design. The table will contain all the entities of that
type, existent at a moment.
In the logical design phase of the database it was necessary to break the many-to
many relationship in two one-to-many relationships. This led to a new table, named
“OrdersDetails”, which contains the information on each product asked in an order.
In the detailed design phase other two tables were defined:
- “Categories”, necessary to store the characteristics of each product type;
- “Shippers”, to store details about the companies that may assure the products
transport by ship.
The final result of the logical design is represented in the figure 1.14.
26
Figure 1.14.
You can analyze each table of the database:
Open the Database
Open each table:
o in Design View, to examine the type of each data field;
o in Datasheet View, to see the actual content of the table.
For example, the figures 1.15.a and 1.15.b show the table “Orders” in the Design
View and in the Datasheet View.
27
Figure 1.15.a. The Design View of the table Orders Details
Figure 1.15.b. The Datasheet View of the table Orders Details
28
Chapter 2. Queries
The real power of a database is the ability to see the data it contains as we want,
in the order and grouped as we want, to make analysis and calculations using that data.
By queries we can ask questions about the data in a database. For example, we can query
the Northwind database to see what are the German customers, or which salesperson sold
the most units of a given product.
Queries allow us to view and analyze our data in different ways:
Sort records by fields or by groups.
View records that meet specific criteria.
Perform calculations on groups of records.
Combine tables and other queries.
Create a database
To exercise with queries, which will be discussed in the following, we need a
database. We can create very quickly our own database by importing tables from the
Northwind database. Follow the steps:
Create a blank database.
Import from the Northwind database the tables: Employees, Orders and
Customers (see figure 2.1).
Figure 2.1. Create a new table by importing it from another database.
29
Edit the relationships between the three tables:
o Choose the Relationships command from the Tools menu, to open the
Relationships Window
o To specify the relationship between two tables, drag the foreign key from
the child table to the primary key in the parent table. For example, to add
the relationship between the Orders table and Customers table, drag the
CustomerID field from the Orders table to the CustomerID in the
Customers table (figure 2.2).
Figure 2.2. Editing the relationships between tables.
o Mark in the dialog box that is displayed after the dragging operation
(figure 2.3) the option „Enforce Referential Integrity“ and press Create.
To obtain information about the three Integrity options, put the mouse
cursor on the option and press the right button.
30
Figure 2.3. Create a relationship.
o The new relation will be displayed (figure 2.4).
Figure 2.4.
To see the properties of a relationship or to modify it, double-click on the relationship
line. To delete or edit a relationship, put the cursor on the relationship line and then press
the right button.
2.1. Create queries using the Query Wizard
The simplest way to create a query is by using the Query Wizard.
The Query Wizard can generate four types of queries:
31
Simple Query
Crosstab Query
Find Duplicates Query
Find Unmatched Query
2.1.1. Simple queries
A Simple query retrieves data from specified fields. The fields may belong to one
table or they may be selected from more related tables. Also, by simple queries we can
obtain minimum and maximum values in a field, totals and averages. Also, the number of
records retrieved by a query may be limited by different criteria.
Example 2.1.Suppose we want to know the orders emitted by each employee, and for each
order, the order date, the customer’s company name and country. Therefore, we need a
query from three tables: Employees, Orders and Customers. These tables are correlated:
each record from the Order table contains an EmployeeID and a CustomerID. We create
the query in the following way:
Ask a new query and select Simple Query Wizard (figure 2.5)
Figure 2.5. Create a Simple Query with Wizard.
Select from the Employees table the fields LastName and FirstName (figure 2.6).
32
Figure 2.6. Select the necessary fields from the Employee table.
Select OrderDate from the Orders table (figure 2.7)
Select CompanyName and Country from the Customers table (figure 2.8)
Enter the desired name for the new query.
The query is shown in figure 2.9.
Select Design View from the View menu (figure 2.10).
In the bottom part of this view is displayed the Query by Example grid (the
QBE grid). In this view we can specify one or more criteria for the query. For
example, we may want to obtain only the orders related to a specific company.
We will enter the company name as a query criterion for the Company Name
field.
Select Datasheet View from the View menu. The new query is shown in
figure 2.11. It is sorted by the order date. We can change the record order by
specifying the sort option to the corresponding field in the QBE grid.
33
Figure 2.7.
Figure 2.8
.
34
Figure 2.9. The Datasheet View of the EmployeesOrders query.
Figure 2.10. The Design View of the EmployeesOrders query.
35
Figure 2.11. The Datasheet View of the EmployeesOrders query.
Now, suppose we want to see only the sales to Germany. We switch in the Design
View and enter the name of the country in the Country field (figure 2.12). We see
the desired list of records in the Datasheet View of the query (figure 2.13).
Figure 2.12.
36
Figure 2.13. The orders list to Germany.
You will learn more about how to specify criteria to one or more fields from the
laboratory exercises 2 and 3.
Link to a database a table from an existent database
In the following example, we need another table from the Northwind database, the
OrderDetails table. At the beginning of this chapter we created a database by importing
tables from the Northwind database. In this way we created a copy of each imported table
in our database.
We didn’t need to modify any of the imported tables. We don’t need also to modify the
table OrderDetails, so let’s examine another way to use a table from an existent database.
Suppose we use the same table in two or more databases. Then, when it is necessary to
update the table, it is more convenient to operate the modifications only once and not in
each database that use it. If we import the table, then we must operate the modifications
in each copy of it. If we have only one table, which is shared by more databases, then we
make the modifications only once. To have a shared table we define it in one database
and then we link it to each database that need it. Linking the tables instead of importing
37
them has another advantage: we save disk space! The only restriction on a linked table is
that we may not change the design of the table in the database in which it is linked. Its
structure can be modified only in the database that contains it.
To link a table from an existent database just selects the link option (figure 2.14),
after you asked to add a new table to your database.
Figure 2.14. Link to the database a table from another database.
Example 2. 2. Summary, min, max and average calculations.
When one of the fields selected in a query contains a number or a currency, the
Wizard displays a window by which we can ask the computing of a supplementary
column, containing the sum, the average, the minimum or the maximum from the values
of all the records of the same type. For example, we can query the OrderDetails table to
obtain the total quantity of products specified in each order.
Create a new query and select the fields OrderID and Quantity from the
OrderDetails table (figure 2.15).
38
Figure 2.15.
The Wizard will display the dialog box from the figure 2.16. Select the
Summary option and then press the Summary Options... button.
Figure 2.16.
39
In the Summary Options dialog box (figure 2.17) it is displayed the field
Quantity because it contains a value of type number. Mark the Sum option
and then press the OK button. We obtain the query shown in the figure
2.18.a.
Figure 2.17.
Figure 2.18. a. Figure 2.18. b.
40
The Count Records in Order Details option (figure 2.17) returns the number of records that make up each total. The query will contain a new field showing the result of the count (figure 2.18. b).
2.1.2. Crosstab Queries
The query from the example 2.2 is actually a Totals query. A Totals query performs
calculations on groups of records. For example, we can obtain a subtotal for a group or
the average value for a group.
A crosstab query is just a more complex Totals query. It summarizes data in rows
and columns.
A Crosstab query must contain three elements:
A column heading
A summary field
A row heading
Example 2.3.
Ask to create a new query and select Crosstab Query Wizard (figure 2.5).
In the displayed Dialog Box (figure 2.19) we must select the table or the query that
contains the data necessary in the new query. Only one query or table can be used to
obtain a Crosstab query.
Select the Orders table and then press Next.
In the next three windows we must select:
The row heading (figure 2.20).
The column heading (figure 2.21).
The field to be summarized in the query and the way to calculate the
values (figure 2.22). We selected the field Freight and the function Sum.
The Sample part of the window shows a generic version of the query.
If you want to see Help information on Crosstab queries, select the Display Help
on Working with the Crosstab Query option, in the last dialog box (figure 2.23).
The Datasheet View of the query is shown in the figure 2.24.
41
If you deselect the option „Yes, include row sum“ in the Dialog box from figure
2.22, then the second column of the query table, „Total of Freight“ will be
omitted.
Figure 2.19.
42
Figure 2.20.
Figure 2.21.
43
Figure 2.22.
Figure 2.23.
44
Figure 2.24. A Crosstab Query.
The Total Of Freight field lists the total freight cost per day. The first row is a subtotal for
each country – that’s why there’s no date in the Shipped Date field for that record.
2.1.3 Find Duplicates Queries
This query is useful to find the records that have the same value in a specified field.
For instance, all the employees with the same hire date, all the orders with the same order
date, etc.
Example 2.4.
Ask to create a new query and select Find Duplicates Query Wizard (figure 2.5).
In the first dialog box (figure 2.25), select the Employees table, as the table in which
you want to find the duplicates.
In the next dialog box (figure 2.26), select the field „Hire Date“, as the field used for
finding the duplicates.
In the next dialog box (figure 2.27) you may choose other fields to be displayed. For
example, First Name and Last Name.
The resulted query is shown in the figure 2.28.
45
Figure 2.25.
Figure 2.26.
46
Figure 2.27.
Figure 2.28.
2.1.4. Find Unmatched Queries
Suppose we have two related tables in a database. If the relationship between the
two tables is not of 1-1 type, then not all the records from one table are related to
records from the other table. For example, it is possible that not all the customers
registered in the Customers table to appear in the Orders table. We can easily find
these customers using an Unmatched query. Any missing CustomerID value in the
Orders table indicates customers with no orders.
47
Example 2.5.
Ask to create a new query and select Find Unmatched Query Wizard
option.
Select Customers, as the table where to find records which have not related
records in the other table.
Select Orders, as the table in which to find related records.
In the next dialog box you must specify the related fields in the two selected
tables. The Wizard identified the two fields: CustomerID. You can change this
field in either table if necessary. The selected fields must have the same data
type.
In the next dialog box you can specify the fields to be displayed in the query.
For example, we want to see the company’s name and phone number for any
customer that doesn’t have an order. Then, we select the CompanyName and
Phone fields.
We obtain the query showed in the figure 2.29.
Figure 2.29.
2.2. Create queries without a Query Wizard
Although the Queries Wizards offer a fast way to produce different types of
queries, the most flexible way to create a query is to design it without the Query Wizard.
Details about the editing of queries in Design View are presented in the laboratory
lesson number 4.
Example 2.6. A calculation query for Inventory
In this example we will see how to create a query with calculation fields.
48
Suppose we want to have an inventory of the products in stock, that is for each
product the inventory value is calculated as UnitPrice * UnitsIn Stock. We need a
separate column to display the inventory values.
We ask to create a New query.
In the dialog box from figure 2.30 we select Design View.
Figure 2.30.
The next dialog box (figure 2.31) enables the selection of tables necessary for the
new query. We select Products.
Figure 2.31.
We drag the field ProductName from the table to the Field row on the first
column in the QBE (figure 2.32).
49
We type the calculation expression on the second column in the Field row. The
calculation is expressed as: Inventory Value:[UnitPrice]*[UnitsInStock].
Figure 2.32.
We press the Run button in the Toolbar or ask the Datasheet View from the View
menu. We obtain the query as in figure 2.33.
Figure 2.33.
50
As you can see, the calculation expression begins with the name of the calculation field
followed by semicolon and then an arithmetic expression in which the operands are
values from two fields of the Products table. The value in a field can be included in a
calculation by enclosing the field name between square brackets.
You will learn more about calculations in queries from the LAB 3 exercises.
2.3. The Expression Builder
The Expression Builder is a very useful tool, which can be used to construct very
complicated expressions in a graphical manner.
Expressions are combinations of values, constants, functions, fields and operators that
can be evaluated to a single value.
The Expression Builder can be started by right clicking in any Criteria or Field
row of a query, when the query is opened in Design View (figure 2.34). Select Build…
option from the pop-up menu. The Expression Builder dialog box will appear like the one
shown in figure 2.35.
Figure 2.34.
51
The empty window at the top of the dialog box is used to display an expression,
which can be typed directly in this window or can be constructed graphically by using the
Expression Builder.
The bottom half of the Expression builder is an area containing three boxes that
collectively contain all the expression elements available in Access 97.
The left box lists the folders that contain all the database objects (tables,
queries, forms and reports), built-in and user-defined functions, constants, operators and
common expressions.
The middle box lists specific elements or categories of elements for the
folder selected in the left box. For example, if we select Built_In
functions in the left box, then the middle box will display all the
categories of Access built-in functions (figure 2.36).
The right box contains the values for the selected elements in the left and
middle box (see figure 2.36).
Figure 2.35.
52
Figure 2.36
To create an expression, select each operand and operator and use Paste button to
transfer it in the Expression window. When you press OK the current expression is
copied in the place from where the Expression Builder was started, for example in the
Criteria field.
To construct several criteria, start the Expression Builder separately for each field. For
example, imposing the two criteria from the figure 2.37, the query will contain only the
products having a unit price greater that 10 and which were sold in a quantity less than
100.
53
Figure 2.37
Example 2.7.
Constructing a query that uses a calculated date as a criterion with Expression
Builder.
We want to build a query that returns the set of customers that had orders in the year
1997 and whose orders in that year took longer than 15 days to process from receiving
the order to shipping the order.
Start a new query in Design view (figure 2.30).
Select the tables to use in query. In our example these will be Orders and
Customers.
Drag the necessary fields from the two tables in the QBE grid (figure 2.38)
To obtain the specified result we have to assign a criterion to both the
OrderDate and the ShippedDate fields.
54
Figure 2.38
Start the Expression Builder from the Criteria row of the OrderDate
column.
Make the selections as in figure 2.39 and double-click Year.
Select the Orders table in the left box and OrderDate Field from the
middle box.
Select the placeholder from the expression and then double-click <Value>
to replace it with the value from the OrderDate field.
Click the = button and type 1997 into the Expression box. The expression
looks like in figure 2.40.
Click OK.
55
Figure 2.39
Figure 2.40
Follow the same steps to build the criterion for the ShippedDate field.
Double-click the DateAdd function. The expression should appear like the one
shown in figure 2.41. The DateAdd function enables to calculate a date by
adding a specified time interval to that date.
56
Figure 2.41.
Replace the placeholders (see figure 2.42):
o interval by “d”, meaning “days”;
o number by 15
o date, by the value contained in the OrderDate field
Because we want to find all orders that were processed in more than 15 days
we need to add the greater than sign in front of our expression (figure 2.43).
The result should be like in figure 2.44.
57
Figure 2.42.
Figure 2.43.
Figure 2.44.
58
Chapter 3. Form Basics
Forms are objects used to interact with a database. They can help in viewing,
entering and modifying data. Forms are also parts of the applications user-interfaces. To
understand better what are the forms, we will begin with the Wizard generated forms.
The Access’s form wizards use different defaults to generate forms based on
tables and queries. There are two types of Form Wizards:
AutoForms
Form Wizard
The AutoForms are specific types of forms, containing all the fields of a table or of a
query. The Form Wizard allows selecting the fields to be included in a form.
The Form Wizards generate four types of forms:
Columnar – each record is displayed on one column, with each field on a separate
line. Typically, this form displays one record at a time (see figure 3.2).
Tabular – each record is displayed on a row, in a column format. This is a good
format for displaying multiple records (see figure 3.3).
Datasheet – this is the table format used to display the tables and queries when the
database is opened. Displaying the data in such a form doesn’t need to open the
database (see figure 3.4).
Justified – This form distributes the controls in which are displayed data evenly
between right and left margins and top and bottom margins. This type of form is
available only with the Form Wizard (see figure 3.8).
3.1. The AutoForm Wizard
To create an AutoForm with the Wizard, follow the steps:
Ask to create a new form.
From the „New Form“ dialog box (figure 3.1) select the table or query to display
and one of the three AutoForm formats and then click OK.
The new form is generated. For example, the form generated using the settings from the
figure 3.1 is shown in the figure 3.2. The picture displays only the first record of the
59
Orders table. To see other records use the buttons located the bottom of the form. To add
a new record go to the end of the table using the rightmost button and then enter the
corresponding value in each field.
Repeat the above steps for the same table but using the other two auto formats. The
Tabular and Datasheet forms are shown in figure 3.3 and 3.4
Figure 3.1. Create an AutoForm.
Figure 3.2. A columnar form.
60
Figure 3.3. A tabular form.
Figure 3.4. A Datasheet form.
3.2. The Form Wizard
The Form Wizard offers the three previous form styles and also the justified type. But
more important is that with this wizard we can choose the fields to be included in a form.
Let’s create a justified form with the Form Wizard.
Ask to create a New form
61
Select Form Wizard from the New Form dialog box.
Select the table / query and the fields to be displayed in the form (figure 3.5).
Figure 3.5.
Choose justified option from the Form Wizard dialog box (figure 3.6).
62
Figure 3.6.
Choose one of the styles to display the form (figure 3.7) and give it the desired
name.
63
Figure 3.7.
Figure 3.8. shows the form obtained using the settings from the figures 3.5 and 3.6, in the
Standard style. Try with different styles of displaying offered by the Form Wizard.
Figure 3.8. A Justified form.
When the form is created starting from more that one tables/queries, you may choose
between obtaining a single form containing all the selected fields or a form with
subforms.
3.3. The Chart Wizard
Sometimes it is very useful to have a graphical representation of the dependency
between some data in a table. The Form Wizard can generate such graphically
dependencies as different types of charts. Usually, these charts are added to existing
forms or reports.
Example 3.1.
Ask to create a New form, select the table and the Chart Wizard option (figure 3.9).
64
Figure 3.9.
Select the fields to use for the chart (figure 3.10).
Select the type of chart you want (figure 3.11).
In the next dialog box (figure 3.12):
o You can see a preview of the chart:double-click the button from left-top
corner of the window.
o You can drag and drop the field controls to change the wizard orientation.
o You can change the grouping of data –by, year, by quarter, by month, etc.
o You can change the calculation options.
Try every one of these variants.
The chart form generated by the Wizard using the settings from the figures 3.10, 3.11
and 3.12 is shown in the figure 3.13.a.
65
Figure 3.10.
Figure 3.11.
66
To edit the chart double-click on the chart. The datasheet of the diagram is
displayed as in the figure 3.13.b.
Figure 3.12.
Figure 3.13.a. Figure 3.13.b.
67
Example 3.2. Adding a Chart to an Existing Form
Open the form in which you want to insert the chart. We will use a form (figure
3.14) that displays a query, qryQuantityByMonth. The query was created from the
tables Orders-fields CustomerID and OrderDate- and OrderDetails-field Quantity.
I asked to obtain the Sum of the values from the Quantity field and the grouping
of records by months.
Figure 3.14.
Choose Design View from the View menu.
Choose Chart from the Insert menu.
Click inside the form where you want to position your chart.
Follow the procedure to create a chart. In this example we created a chart starting
from the same query, qryQuantityByMonth. Figure 3.15 explains the chart.
The next dialog box (figure 3.16.) gives you the opportunity to link your chart to
the existing form data.
Choose Form View from the View menu. The chart is shown in the figure 3.17.
Change the record number using the control from the bottom part of the window,
to see the synchronous updating of the document and the chart.
68
Figure 3.15.
Figure 3.16.
69
Figure 3.17.
Chapter 4. Reports
A report is a printed hard copy of some data of a database, presented in a
particular format. A report is based on a table or a query, but the data can be presented in
any fashion we need.
A report (see figure 4.1) usually has a header at the beginning of the report, which
normally contains the title of the report and other introductory information. It also has
footer, at the end, which contains final results like grand totals.
Each page can have a header and footer. The page header contains the column
headings. The page footer typically contains the page number.
A report can be designed “manually” or using a Report Wizard. To design it
“manually”, ask to create a new Report and then choose Design View from the List Box
in the dialog from the figure 4.2. You will have to create the layout item by item. This
can be a very tedious operation. A much easier solution is to use the Report Wizards.
70
Figure 4.1.The format of a report.
The Report Wizards
Many types of reports can be generated using the Report Wizards. If one of these
types of reports is convenient for you, then you can save time creating reports with the
Wizard. Also, you can generate a report using the Wizards and after that, change the
design of the report in any desired way.
The Report Wizards are similar to the Form Wizards in that there are two types:
The AutoReports
The Report Wizard
There are three types of reports:
Columnar - the report displays data in one column, with each field on a separate
line.
Tabular - the report displays all the data from one record in the same row – each
field in a separate column.
71
Justified – The data are distributed evenly between the right and left margins and
the top and bottom margins.
4.1. Creating AutoReports
The AutoReports Wizard automatically generates a specific type of report, using all the
fields in the specified table or query.
Example 4.1.
Ask to create a New report.
From the New Report dialog box (figure 4.2.), select the table or the query you
want to print in the report. Choose AutoReport: Columnar or AutoReport:
Tabular.
The new report is generated.
o Click on the left button when the cursor is on the report surface, to view
the print preview.
o Click on the right button: you can see more that one page at different
levels of zoom.
Figure 4.2.
72
4.2. Using the Report Wizard
The Report Wizard is a little more flexible than the AutoReport Wizard in that it
allows you to select the fields you want to report on. Also, it offers a third style –
justified.
Because you have the possibility to see how are the columnar and the tabular
forms, let’s examine how to use the Report Wizard to obtain a justified report. It is
similar in style to a justified form.
Example 4.2.
Ask to create a new report.
Double-click Report Wizard in the New Report dialog box.
Select the fields you want to include (figure 4.3). In this example I selected
fields from four related tables: Customers, Orders, Order Details and
Products.
Select the table that you want to be used as starting point in report generation
(figure 4.4). For example, selecting the Orders table, the Wizard will traverse
the Order table and for each record from this table will search the related data
in the other tables. The right part of the dialog box shows you a preview of the
report. Select one by one each of the tables listed in the left part to see the
preview of the report.
73
Figure 4.3.
Figure 4.4.
The next dialog box enables to change the grouping of data and the priority of
levels. For example, the figure 4.5. shows the grouping generated by the
74
Wizard. Using the “>” button and the priority buttons I changed the levels and
the grouping of data as in the preview from the figure 4.6.
Figure 4.5.
Figure 4.6.
75
In the dialog box from figure 4.7, you can choose the fields used for sorting
the records in the report. Also, using the Summary Options you can ask to
include in the report a field’s total, its average, and its minimum or maximum
value.
Try different styles of lay out from the next dialog box (figure 4.8). The lay
out is represented in the left window of the dialog box.
Figure 4.7.
76
Figure 4.8.
Figure 4.9.
77
Figure 4.10. shows the report that was generated based on grouping from the
figure 4.5.
Figure 4.10.
4.3. Creating a Chart Report
The procedure to create a chart report is very similar to that of creating a chart form.
Ask to create a new Report.
Select Chart Wizard (see figure 4.2) and the table or query to use in
producing the chart. In this example we selected the Product table.
Select the fields you want to represent in the chart. We selected the Product
Name and Units in Stock.
Select the type of chart you want (see figure 3.7).
Rearrange the defaults arrangements and calculations for the chart (see figure
3.8).
Choose the name of the chart.
Wizard generates a chart like the one in figure 4.11.
78
Figure 4.11.
4.4. Adding a chart to an existing report
The steps to add a chart to a report are very similar to those required to add a chart
to a form.
Open the report in which you want to insert the chart, in Design View.
Select Chart from the Insert menu.
Click inside the report area where you want to insert the chart.
Follow the steps required to create the chart.
The Wizard allows you to dynamically link the chart to the current record. You
can choose No Fields from the Report fields and Chart Fields drop-down lists if
you don’t care to link the chart to the current record.
Figure 4.12 shows a report in which it was included a chart.
79
Figure 4.12.
Chapter 5. Customizing forms
When we want to quickly create a form with standard features, then the Form
Wizards are very appropriate. Otherwise, we can create a form to satisfy the particular
needs of an application, without the Form Wizards, or we can modify a Wizard generated
form.
Forms are used to display data from a database, to enter new data or to modify the
existent data. These output and input operations are performed using special windows
called Controls. Figure 5.1 shows a form containing more types of controls:
80
text boxes, used to display and enter a single string;
list boxes and combo boxes, used to display lists form tables and queries or lists of
arbitrary values;
command buttons;
option groups, and others.
Figure 5.1
A bound object is an object that is attached to a data source. That object can be a form, a
report or a control. For instance, a form bound to a table will display the data in that
table. The form can also be used to enter new data in the table or to modify the existing
data in the table.
A table or a query to which is bound a form is called the form’s Record Source. It is
chosen when the form is created, from the New Form dialog box.
The Record Source is a form’s property and is available through the form’s
property sheet.
81
Figure 5.2. Select the Record Source of the new form.
Figure 5.3. A form property sheet.
5.1. Bound, Unbound, and Calculated Controls
A control can display data that is taken directly from the database, values that are
calculated using more data from a database or values entered by a user.
82
A control whose source of data is a field in a table or query is a bound control. The
bound controls are used to display, enter and update values from fields in a database. The
values can be text, dates, numbers, Yes/No values, pictures or graphs. The text box is the
most common type of bound control. For example, the text boxes that display the Product
Name and the Unit Price from the fields of the Product table (figure 5.5) are bound
controls.
The field to which is bound a control is called the control’s Control Source. The field
must belong to the table or query that is the Record Source of the form. It is available
through the control’s property sheet. The figure 5.4 shows the property sheet of the text
box that displays the Product Name in the form from figure 5.5.
Figure 5.4. A control property sheet.
A control whose source of data is an expression rather than a field is a calculated
control. For example, the text box that displays the discounted price, calculated with the
formula Unit Price *0.75 is a calculated control. A calculated control displays data – the
result of its expression – but that control isn’t bound to a table or a query. In other words,
it displays data but doesn’t store it.
A control that doesn’t have a source of data (a field or expression) is an unbound
control. Such controls are used to display information, lines, rectangles and pictures. For
example, the three controls that label the text boxes are unbound controls.
83
Figure 5.5
Using the Toolbox
The Toolbox is a toolbar specialized for controls. It is displayed automatically when a
form is opened in Design View. The meaning of each graphical symbol from the Toolbox
is shown when you put the cursor on the symbol surface. The general procedure to create
a control is: click on the corresponding button in the Toolbox and then click on the place
in the form where you want to put the control.
5.2. Text Boxes
A text box can be a bound control, an unbound control or a calculated control.
Creating a Bound Text Box
Open the form in Design View.
Display the Field List: click the Field List button or select Field List from the View
menu.
Click on the Text Box button in the Toolbox.
84
Drag the field to which you want bound the control from the Field List to the desired
position in the form.
Figure 5.6. The Toolbox.
Creating a Calculated Text Box
Open the form in Design View
Click on the Text Box button in the Toolbox.
Click on the form surface where you want to place the control
Right-click on the control surface
Select Properties from the pop-up menu
Enter in the Control Source row the expression to be used for calculation.
The calculation expression can be composed of different operators, constants, and fields
of the Record Source and function calls. For instance, to display the current day on a
form, we place the expression =Date() in a text box. Date is a function that returns the
current date as stored in the computer’s system clock. Figure 5.7 shows the Property
sheet of such a control.
To each text box it is associated automatically a label. This is also a control. The
Label text can be changed very easily: double-click on the label text and then enter the
desired text.
Creating a Label Text
Labels are used to display descriptive text such as a title, caption, or a brief instruction. A
label is always an unbound control. To create a label:
85
In the Toolbox, click on the Label button.
Click on the form. Enter the text to be displayed on the control surface. The surface of
the control is modified as you type the text. The surface can be modified to display
text on more than one line.
Figure 5.7.
5.3. List boxes and Combo boxes
In many cases it’s quicker and easier to select a value from a list than to
remember the value you want and type it. A list of choices also helps to ensure that the
value that’s entered in the control is correct. Microsoft Access has two types of controls
that provide a scrollable list of choices: list boxes and combo boxes.
A List box is a simple list of values you can select from. A combo box is like a text box
and a list box combined into one control – you can either type a value in the text box or
select a value from the list. The list is displayed when you click the arrow (figure 5.1).
The list of a list box or combo box consists of a number of rows of data. Each
row has the same number of columns, which can appear with or without headings. For
combo boxes, you can also control whether new values can be entered.
86
To decide whether to use a list box or a combo box, think about how you want the
control to appear on your form and how you expect people to use the control. Each
control offers advantages:
Advantages of a list box. The list appears at all times and the value of the control is
limited to the set of alternatives in the list. You cannot add or modify values in the
list.
Advantages of a combo box. Since the list isn’t displayed until you open it, the
control uses less room on the form. You can type the first few characters of a value in
the combo box to quickly find that value. You can choose to allow entry of new
values in the combo box or you can prevent the entry of new values.
We will examine two types of lists that can be displayed in a list box or combo box:
Lists composed of rows from a table or a query
Lists composed of values entered by you. This is named a value list.
Both types of lists can be created with the Wizard.
Creating a List Box or a Combo box with the Wizard
5.3.1. Displaying a Value list
Ask to create a new form or open an existing one in Design View.
If Access doesn’t open the Toolbox, click the Toolbox button.
In the toolbox, click the Control Wizard tool so that it is highlighted.
Click the List Box tool or the Combo box tool on the Toolbox (figure 5.2) and then
click inside the form where you want to place the control. In response, Access will
lunch the wizard and display the first window, shown in figure 5.8.
87
Figure 5.8.
You may choose between creating your own list of items and displaying the list from
a table or a query. Choose the I Will Type in the Values that I want option for this
example. Click next to continue.
The next window prompts you for the list box values or items (figure 5.9). Enter the
appropriate values in the provided columns. Next, enter one item in each column cell,
in the order you want the control to display them. When you have finished, click Next
to continue.
Figure 5.9.
The final window prompts you for a descriptive label. I entered the label “Animals”.
If you need more help, you can select the Display Help on Customizing the List Box
option. Click Finish. In the Design View you may modify the width of the label
control.
To view the list box click on the Form View from the View menu (figure 5.10).
To choose an item, simply select it.
88
Figure 5.10.
Now, let’s see the properties of the list box. Figure 5.11 shows the property sheet of the
list box. The Row Source Type property is set to Value List. That means, the items from
the list are entered by you. If you want to create this list box without the Wizard, you
must choose this type for the list box. The Row Source property contains the items,
separated by semicolon.
You can modify the list box properties when the form is open in Design View.
Click Properties Button or select Properties from the View menu to see the property
sheet. For example, you can add or delete a string directly in the Row Source property.
This kind of list box has sense only if it is used in connection with another control
on the same form. To correlate the two controls you must attach a Basic event procedure
or a macro to the list box. This will be automatically executed, for example, every time
you click on the list box.
89
Figure 5.11. The property sheet.
5.3.2. Displaying a list of fields from a table or a query
Suppose we have a form that is bound to the Products table. We want to see the list of all
the suppliers registered in the Suppliers table and, when we move from record to record
in the Product table, to see what is the supplier of each product. A list box bound to the
Suppliers table will help us to obtain this effect.
Follow the same steps as in the previous example until the dialog box from figure 5.8
is displayed. Choose the first option.
90
From the next dialog box (figure 5.12) select the table Suppliers.
From the next dialog box select the fields to display.
The next dialog box enables you to adjust the width of the columns. Usually, the first
column contains the key field of the table to which is bound the list box. This field is
useful to bind the list box to the form but it is not recommended to be visible (the user
is not interested to see it!). So, keep this option in the dialog box marked.
The dialog box from figure 5.13 invite you to choose a field to which you want bound
the list box. This field may be only one of the fields of the table to which the form is
bound, that is the Products table. We select SupplierID. In this way, the selection in
the list box will change accordingly with the value of the SupplierID field of the
current record. Also, if we change the selection in the list box for a particular record,
this change will be stored in the database.
Pass in the Form View to see these effects.
Figure 5.12.
91
Figure 5.13.
Figure 5.14. The property sheet of the list box.
5.3.3. Creating a form to update a table
Suppose we want to create a form to enable the user to update the Products table.
We create a form bound to the Products table.
We add on the form surface all the needed controls to display and change the
content of the Product table. For example, in the form from the figure 5.15. I put
three text boxes to display three fields of the table and also a calculated text box.
92
Instead of displaying the SupplierID and the CategoryID that are database internal
data, I displayed the suppliers’ names and their cities and the categories names,
because these data are relevant for the end user of the database.
Figure 5.15.
When we move from record to record, the selections in the two list boxes changes
automatically. When we add a new record to the database, we select the supplier and the
category of the new product from the corresponding list box.
The exercise from the LAB 5 ask you to extend this form with new controls, necessary
for any modification of the Products table.
5.3.4. Controlling Entry of New Values in a Combo Box
The property Limit to list (figure 5.16) of a combo box control has the default
setting “Yes”, that is, you cannot enter new values in the list or modify the existent items.
93
In a combo box, the only column you can edit is the bound column. Set Limit to
list to “No” only if the bound column is displayed in the combo box. If the bound column
is hidden, the Limit to list property functions as if it’s set to “Yes”.
If the Limit to list is set to No and you type a few characters in the Combo Box, then:
if there exist a record beginning with the entered string it will be displayed
if there is not a record (in the bound field) beginning with the entered string, the
string is added to the list.
Figure 5.16. A Combo Box Property sheet
5.4. Ensuring Correct Data Entry
When typing values in a text box or a combo box it is possible to make a mistake.
For example, when entering a date, you might type the wrong year. When you are
entering a phone number, you might enter it in an incorrect format by mistake.
To avoid these problems we can set up rules that govern the values that can be
entered into a field.
The DefaultValue, ValidationRule, ValidationText and InputMask properties are
available in the design view of tables as well as in the design view of forms. In addition,
you can set the InputMask property in query design. These properties can be set also to
help enter the correct data into a control.
DefaultValue property. Specifies a default value to be displayed for a new record.
For example, we can set the default value of a Date text box to the current date.
94
ValidationRule and ValidationText properties. Check the data you enter into a
control and let you know when you’ve entered incorrect data. For example, you can
set the ValidationRule property so you can’t enter discounts greater than 50%. Then
you can use the ValidationText property to define the message that appears when you
enter incorrect data.
InputMask property. Helps you enter data in the correct format. For example,
suppose phone numbers have the format (111) 55-1313. You can set an input
mask that automatically displays parentheses, spaces and hyphens in the correct
places and skips over these characters when you are entering data.
5.5. Check Boxes, Option Buttons and Toggle Buttons
All these controls can be used as stand-alone controls to set Yes/No values. The
differences are in their appearance. The left part of the figure 5.17 shows the three types
of controls in the selected state. They are bound to the field “Discontinued” from the
Products table.
Figure 5.17.
They are useful when they are bound to Yes/No fields. When these controls are bound to
other types of fields Microsoft Access stores the value 1 (Yes or True) in the field when
the control is selected and 0 (No or False) if the control isn’t selected.
95
To speed data entry, you can make one value the default by setting the DefaultValue
property of the control to Yes or No, depending on which value is selected most often.
5.6. Option Groups
An option group is used to present a limited set of alternatives.
An option group on a form is composed of a frame and a set of check boxes, option
buttons or toggle buttons (figure 5.21). The frame has an attached label. In this example,
the label is “Transport”. Only one option in an option group can be selected at a time.
One of the options may be defined as default.
If an option group is bound to a field, it is the group frame that is bound to the
field, not the individual options inside the frame. A group frame can also be set to an
expression or can be unbound.
When used in groups, check boxes, option buttons and toggle buttons have
properties that are different from when they are used as stand-alone. Each option control
from an option group has associated a distinct value. This is the OptionValue property. It
must be set to a number that is meaningful for the field the group frame is bound to.
When an option in a group is selected, Access sets the value of the field to which the
option group is bound to the value of the selected option’s Option Value. For the example
in figure 5.21, the possible values of the field bound to the group are between 1 and 4.
To create an option group with the Wizard:
Click on the Option Group tool in the Toolbox.
Follow the steps illustrated in figures 5.18, 5.19 and 5.20.
From the next dialog boxes you can select the field to which will be bound the group,
the type of control to use and the style of displaying.
96
Figure 5.18
Figure 5.19
97
Figure 5.20
Figure 5.21. Option group
Because the value of an option group can be only a number, not a text, it is
recommended to create option groups for Yes/No fields or Number Fields with the
FieldSize property set to Byte, Integer or Long Integer. For fields with data type other
that Yes/No or Number it is best to use a list box or a combo box to present a list of
values.
5.7. Command buttons
A command button is used to start an action or a set of actions. The action is represented
by a macro or an Access Basic event procedure.
98
Example: Creating a command button with the Wizard
The Wizard offers a number of graphical command buttons that perform standard
actions. We create such buttons to speed up common tasks such as moving to a new
record, opening another form or printing a report.
Click on the Command button tool in the Toolbox and then on the form, where you
want to place the button.
Follow the dialog boxes to choose the type of button and the picture to put on the
button.
Figure 5.22. Wizard generated command buttons.
Every Wizard generated command button has associated an Access Basic event
procedure. You can modify this procedure to change the behavior of the command
button.
Chapter 6. Using Macros
A macro specifies a series of actions that are automatically executed when the
macro is run. When we create a macro, we select the actions we need from a list of
predefined actions, and arrange them in the desired order. For example, we can create a
macro to automatically open a table and a form that we often use together. There are over
50 predefined actions, with several actions that allow additional sub-actions.
Macros are useful for repetitive or routine tasks.
99
6.1. Creating, Saving and Running a Macro
To create a macro:
In the database window, click the Macros button and then New. Access opens a
new Macro window (figure 6.1).
In the upper part of the window we construct the list of actions, selecting each
action from the action list. Select an action. In the lower part of the window,
Access asks you to enter the action arguments.
When editing the list of actions you can use the special macro buttons on the
Toolbar of the main window. Put the cursor on each active button to see what is
it’s meaning.
When you finished to define the actions, Save the macro. Use the Save Button or
the Save option from the File menu.
Run the macro. Use the Run button (!) or the Run command from the Run menu.
Figure 6.1.
The RunMacro action
100
Another way to execute macros is by using the RunMacro action. Run macro specifies
the execution of a macro in another macro.
Example 6.1.
Figure 6.2 shows a macro composed of three actions: Open a table, Display a message
box and Close the table.
In the argument list of the OpenTable action I specified the table Products.
To create a message box:
Select MsgBox from the actions list and then enter the desired values as
arguments. For example, the message box from the figure 6.2 is described as in
the figure 6.3. For the Type argument you can select one of the built-in icons to be
displayed on the Message window.
Figure 6.2.
101
Figure 6.3.
When you run this macro, the table Products will be displayed in Datasheet mode and the
Message Box over the table. When you click OK on the Message Box, the action
“MsgBox” is finished and the next action will be executed, that is, Close the table.
Many actions have an argument that calls for the name of a database object. You
can use a “drag and drop” technique to set these arguments. To have the necessary list of
objects on the screen, click on the button corresponding to the type of object in the
database window.
102
Figure 6.5. Drag and Drop objects from the database to the Macro Window.
6.2. Macro Groups
You may sometimes find it convenient to group a number of related macros
together in one Macro window. To group macros, we create a macro group. A macro
group is a set of one or more macros that appear in the same Macro window. The
individual macros run independently of one another.
For example, suppose we have six command buttons on a form, each of which
opens a different form. Instead of having six separate macros in our database, one for
each button, we can create a macro group that contains a macro for each button. That
way, you have all the macros related to the form together in one convenient document.
A macro group is a database object. Its name appears in the list of macros in the
Database window. Each macro in the group also has a name that you assign, but these
names don’t appear in the Database window.
To create a macro group:
Click on Macro button in the database window and then on New.
Click on the button Macro Names. Access displays the column Macro Name in
the Macro window.
103
Type a name in this column for each macro in the group. A macro may be
composed of one or more actions, each action on a row. For instance, the macro-
group in the figure 6.6 is composed of two macros: the first is named “Edit
Products table”, the second “Today”.
Run a macro group
When you run a macro group using the Run button, only the first macro in the group is
executed.
Figure 6.6. A macro group.
Run a macro from a macro group
A macro from a macro group is specified using the macro group name and the macro
name separated by a period. For example, the name of the group from the figure 6.6 is
“Macro-group”. The two component macros are specified by: “Macro-group. Edit
Products table” and “Macro-group.Today”. If we want to force the execution of the
second macro every time the macro-group is run we insert a RunMacro action at the end
of the first macro (figure 6.7).
104
The Run Macro action has three arguments: Macro Name, Repeat Count and Repeat
Expression. The Repeat Count argument specifies how many times to repeat the
execution. If the Repeat Expression argument evaluates to false, the macro is stopped.
Figure 6.7.
6.3. Referring to Control Names in Expressions
Very often we need to refer to the value of a control in a macro. The following syntax
must be used:
Forms![formname]![controlname]
Reports![reportname]![controlname]
For example: Forms![Suppliers]![SupplierID] refers to the SupplierID control on the
open Suppliers form. Reports![Freight Charges]![Freight] refers to the Freight control on
the open Freight Charges report.
Note: The form or report must be opened to have access to its controls.
105
When the macro is run from a form or report then the controls can be referred only by
their names. For example, [SupplierID] refers to the SuplierID control on the form or
report from which the macro was run.
To test if a record contains no data you can use the function IsNull. For example:
IsNull([SupplierID])
6.4. Macros Conditions
In some cases, you may want to carry out an action or series of actions in a macro
only if a particular condition is true. For example, if you’re using a macro to validate data
in a form, you might want to display one message in response to one set of values entered
in a record and another message in response to a different set of values. In such cases,
you can use conditions to control the flow of the macro.
A condition is a logical expression. The macro execution follows different paths
depending on whether the condition is true or false. Here are some examples of macro
conditions:
Condition Evaluation Forms![Students]![Age]>21 If the value in the Age control on the
Students form is greater than 21,
then…
[City] = “Paris” If the City control value on the form
from which the macro was run is
Paris, then...
Forms![Customers]![Country]=”USA” If the value of the Country control on
AND Forms![Customers]![CustomerID] < 31 the Customers form is USA and the
value of the CustomerID control on
the Customers form is less than 31,
then…..
106
To add a condition to a macro:
In the Macro window, click the Conditions button or choose Conditions from the
View menu. Access displays the Condition column (see figure 6.8).
In the Condition Column, enter the condition to execute the action from the same
line or from a sequence of lines. In the last case, for each following action in the
sequence you must insert an ellipsis (…) in the Condition column, as in the figure
6.8.
Figure 6.8.
6.5. Finding problems in macros: Single Stepping
Single Stepping means moving through the macro one action at a time, with a
pause between each action. Use Single Stepping mode of execution to see the result of
each action. That way, you can observe the result of each action and isolate any action
that causes incorrect results.
107
To single step through a macro:
Open the macro in Design View
Click the Single Step button
Run the macro (for example, by clicking the Run button). Access displays the
Macro Single Step dialog box (figure 6.9), which shows the macro name, the
name of the first action in the macro and the arguments for this action.
Figure 6.9.
o If there is a condition for this action, the dialog box displays the condition,
and whether it evaluates to True or False.
o If you use an expression in an argument, Access normally evaluates the
expression and displays the result in the Arguments box of the Macro
Single Step dialog box. There are two exceptions:
the expression is displayed unevaluated if there is a condition for
the action that evaluates to false
the expression is in the Where Condition argument for the
OpenForm, OpenReport, or ApplyFilter action
Choose the Step button to carry out the action displayed in the dialog box. If this
action has a condition that evaluates to false, the action isn’t carried out. The Step
button just moves to the next action in the macro that has no ellipsis.
108
6.6. Using Macros in Forms
When you use a form, Access recognizes certain things that happen on the form as
events. For example, moving from one record to another on a form is an event; so is a
double-clicking a control. You can use a macro to respond to an event.
Each form and control event type has a corresponding event property. To respond
to an event type, we set the corresponding event property to the name of the macro.
Figure 6.10 shows a form property sheet and a command button property sheet with
the “On Click” property set to a macro name. The two macros are illustrated in
figures 6.11 and 6.12.
Figure 6.10
Figure 6.11.
109
Figure 6.12.
We can use the Macro Builder to create a macro and set the event property
automatically. The Macro Builder is available for each event property (figure 6.13).
Figure 6.13
6.6.1. Opening a form from another form
Open the Northwind database.
Create a macro like in the figure 6.14. and save it with the name “Review
Products”.
110
Figure 6.14
Opens the Suppliers form in design view.
Drag the “Review Products” macro from the database window to the form header.
When you release the mouse button, Access places on the form the command
button “Review Products” (figure 6.15). Also Access sets the On Click property
of the button to the macro “Review Products”.
Switch to Form view and click the button. Access opens the Product List form in
Datasheet view.
111
Figure 6.15
6.6.2. Synchronizing two forms to show related records
We have a command button on the Northwind Suppliers form that opens the Product List
form by running the Review Products macro. To synchronize the two forms, you set the
Where Condition argument for the OpenForm action as following (see figure 6.16):
Figure 6.16.
[SupplierID]=Forms![Suppliers]![SuplierID]
The left part of the expression identifies the SupplierID field in the Products table,
which underlines the Product List form. The right part of the expression identifies the
current supplier ID number from the Supplier form. The OpenForm action finds the
record or records on the Product List form with the same supplier ID number. For
example, suppose you are looking at the Osaka Traders record on the Suppliers form
(figure 6.17). Osaka Traders’s supplier ID number is 6. When you run the macro,
Access evaluates the Where Condition argument to this:
[SupplierID]=6
The OpenForm action displays the records for the Product List form for which the
supplier ID is 6.
112
Figure 6.17.
When you go to a different supplier record, you can click the Review Products button
again to see the products for the current supplier. If the Product List form is already open,
the OpenForm action in the Review Products macro makes it the active window and
displays the appropriate related records for the current supplier.
6.6.3. Using the OnCurrent property to keep two Opened Forms Synchronized
Instead of clicking the Review Products button for each supplier we can make that
the Product List form stay synchronized with the current supplier record as we move
from record to record on the Supplier form.
113
To do that, we write a macro that shows the current supplier’s products in the Product
List form if it is open, but does nothing if the Product List form is not open. So, after
the first click on the Review Products button, the Product List form will be found
open and the Product list will be updated automatically.
We specify the macro as the OnCurrent property setting of the Suppliers form,
because we want Access to update the Product List form each time a new record on
the Suppliers form becomes current.
In Design view, click the OnCurrent property box in the Suppliers form and
then run the Macro Builder (figure 6.18) to construct the desired macro.
Figure 6.18
Click the Condition button on the toolbar. This displays the Condition column
in the Macro window.
We can use the Access Basic function IsLoaded (figure 6.19), to express the
condition we need. This function checks whether the Product List form is
open.
The other settings in the “Show Related Products” macro are shown in figure
6.20.
Save the macro with the name “Show Related Products”.
The Where Condition is the same like in the Review Products macro.
114
Figure 6.19
Figure 6.20
115
Exercise. Setting Values for New Records
Suppose we would like a convenient way to add new products for the current supplier
when you are using the Northwind Suppliers form. We can create a form called Add
Products and put a command button on the Suppliers form that opens the Add Products
form, displays a new record and automatically fills in the value of the Supplier ID
control.
The macro attached to the Add Products button (figure 6.21) uses the OpenForm
action to open the Add Products form. It uses the SetValue action to set the value of the
SupplierID control on the Add Products form to the supplier ID in the current record on
the Suppliers form.
Figure 6.21.
6.7. Special Macros: AutoExec and AutoKeys
There are two special macros that Access handles differently because of their names:
AutoExec and AutoKeys.
AutExec
116
Any macro that you name AutoExec will be executed automatically when anyone opens
the database. This special macro can give you a lot of power because you can set your
application up without relying on the end-user. One of the most obvious uses of the
AutoExec macro is to display the initial screen. Also, you can set up your AutoExec
macro to open a certain form that you want your user to be on after setup.
Example
The following macro (figure 6.22) opens a form (form4) when the user clicks on the
database filename. You can put everything in an AutoExec macro, including the
RunMacro action to execute another macro. Don’t forget, you must save the macro with
the name AutoExec.
Figure 6.22
AutoKeys
Example 6.6.2.
Using the macro from the figure 6.23 as the AutoKeys macros, when a user press the key
F11 the system verifies if the user belongs to a certain group. If the condition is True, it is
displayed the Unhide Window dialog box so that the user can show the database. In this
example, be sure to place yourself in the Admin group when you secure your database.
117
Figure 6.23
The Startup options
Many of the initially settings which may be included in the AutoExec macro are available
in the Sturtup Options.
With a database open, select the Tool menu and the Startup command.
Try different types of settings in the Startup dialog box.
Chapter 7. Communication with other Applications
Access 97 provides several tools called Office Links that facilitate the use of Access data
in other Office applications. Three of these are:
Merge It with MS Word
Publish It with MS Word
Analyze It with MS Excel
118
7.1 Merging Access Data with Word Documents
The merge process is fairly simple and straightforward. First you store data, such as
address information, in an Access database. Second, you use Word to create a mail-merge
document. This document will contain the information you want to share, plus special
field codes that will refer to fields in your Access tables. When you merge your Access
data with the Word mail-merge document, Word will rely on your Access database to fill
the field codes in the Word document.
7.1.1. Creating a mail-merge document
In Access, choose the table or query that contains the data you need to merge into
Word. In our example this will be the Employees table.
Choose the Merge It with MS Word option from the OfficeLinks button drop-
down list on the Database toolbar. The Mail Merge Wizard will display the
window shown in figure 7.1.
Select “Create a new document and then link the data to it” and the click OK.
Word will open a new document.
119
Figure 7.1.
Choose Date and Time from the Insert menu, select the fourth option (month,
date, year) from the dialog box (figure 7.2), click the Update Automatically
option and then click OK. Every time you will use the merge document, Word
will use the current time.
Figure 7.2
Press Enter many times.
Add the fields you need from the Employees table. To select the fields click on
the Insert Merge Fields button.
Enter the Word text, for example a letter. You can also add field codes to the body
of your letter.
If you want to save the document, use the Save As option from the File menu.
Suppose the Merge document has the form from figure 7.3.
When the document is ready to merge with the data from the database, you have two
choices:
Merge to a new document.
120
Merge directly to the printer.
Figure 7.3
To merge to a new document
Click the Merge to New Document button on the Mail Merge toolbar. Word creates
one document with the default name Form Letter1, as shown in figure 7.4:
Figure 7.4
Each page of this document contains one of your merged letters. You can view them,
print them, or even modify them.
121
If you want to return to the mail-merge document, choose that document from the
Window menu.
To merge to the printer, click the Merge to Printer button on the Mail Merge
toolbar. This will print all the merged letters automatically without creating a new
document.
7.1.2. Merging to a linked document
Select the Employees table in the Database window and choose Merge It with
MS Word from the OfficeLinks button drop-down list.
Select Link your data to an existing Microsoft Word document and click OK.
Locate your mail-merge document in the Select Microsoft Word Document
dialog box, select it and then click OK to lunch Word and open your document.
Select the fields to be inserted in the document.
Click one of the merge options-merge to a new document or merge to the printer.
7.2. Publishing data with Microsoft Word
The Publish It with MS Word Office Link enables to quickly create a Word document
from the Datasheet view of tables, queries and forms and also create a document from a
report’s output.
This Office Link creates a file in the Rich Text Format (RTF) and immediately runs the
Word with this document open.
For tables, queries and forms the Publish It Office link produces a new document that
uses a table to display data. For a report, the document will closely resemble the printed
report.
To publish data with Microsoft Word:
Open the database containing the data to be published.
Select the table, query, form or report that you want to publish.
Click Office Links, Publish It with MS Word in the Tools menu.
122
Access gives a name to the new Word file based on the name of the selected
object. If the filename already exists, Access will ask you whether you want to
replace the existing file.
The Office Link opens the Word with the new document.
Figure 7.5.
7.3. Analyzing Data with Excel
This Office Link enables you to transfer your tables, queries, forms and reports to an
Excel spreadsheet. Most of the formatting in the Datasheet views, forms and reports is
preserved in the spreadsheet.
To analyze data with Excel:
Open the database containing the data to be analyzed.
Select the table, query, form or report that you want to analyze.
123
Click Office Links, Analyze It with MS Excel in the Tools menu.
Access gives a name to the new Excel file based on the name of the selected
object. If the filename already exists, Access will ask you whether you want to
replace the existing file.
The Office Link opens the Excel with the new newly created spreadsheet.
Chapter 8. Database Administration
Database administration is the collection of activities required to maintain a
database system. It includes backing up, compacting and repairing databases.
8. 1. Backing Up a Database
Creating backup copies is one of the most important database administration tasks. Its
aim is to prevent the loss of data. Also, if you make unwanted changes to a database, that
can’t be reversed, you can always return to the most recent backup copy.
How often you should back up your database depends primarily on how often it’s
updated. For example, if you are the only person who uses your database and you add
only a few records each day, it may be sufficient to back it up once a week. In a multi-
user environment, where many records are added each day by several people, you should
back up the database more often.
You should also back up your database at the following times:
After creating or making significant design changes to tables, queries, forms,
reports, macros or modules.
Before making large changes to data that you may be unsure of.
After adding, importing or making successful changes to a large number of
records.
To back up a database: Close the database. In a multi-user environment you must also make sure that all
other users have closed the database.
124
Make a copy of the .MDB file to the backup system. You may use a special
backup software.
To restore a database from a backup copy:
Simply copy the .MDB file from the backup directory to your database directory
A good practice is to create a backup database. To back up individual database objects
you can import them from the original database. This method is especially useful in a
multi-user environment, since you can back up objects without requiring other users to
close the database.
8.2. Compacting a Database
When you make changes to a database, such as adding and deleting objects, it can
become fragmented and use disk space in a non-optimal manner. Periodically, you should
compact your database in order to de-fragment the file. The compacted database file
usually becomes smaller.
Before compacting, you should make sure that you have enough storage space on
your disk for the original and compacted versions of the database. The compact operation
stops if you don’t have enough storage space.
To compact a database: Close the database. In a multi-user environment you must also make sure that all
other users have closed the database.
Select Database Utilities from the Tools menu and then Compact and Repair
database…
Select the database to compact
Specify the name for the compacted database.
8.3. Encrypting a Database
125
If you don’t want a database (.MDB) file to be readable outside Microsoft Access,
you can encrypt the database. An encrypted database file is completely unreadable from
another application, such as a text editor.
The database must be closed before encrypting it. In a multi-user environment the
database must be closed by all the users. The encrypted file may be the same as the
original or a different one.
The performances of an encrypted database are slower that that of the original
version. If necessary, you can decrypt the database.
To encrypt or decrypt a database:
Select Security from the Tools menu and then Encrypt/Decrypt
Specify the name of the database to encrypt
Specify the name of the encrypted database file
8.4. Recovering a Damaged Database
If the Access shuts down unexpectedly, such as in a power failure, your database can be
left damaged. To use the database, you have to repair it.
When you try to open a damaged database, Access automatically detects the error and
displays a message telling you that the database is in need of repair. If you choose OK,
Access repairs and opens the database.
It is possible for a database to be corrupted in such a way that Access can’t detect
the damage. In this case, unpredictable behavior may occur. You can ask to repair the
database even if Access doesn’t detect that it’s corrupted, in the following way:
Select Database Utilities from the Tools menu and then Compact and Repair
database…
Select the database to repair
126
8.5. The Database Performance Analyzer Wizard
The performance analyzer can furnish information to improve the design of a database.
Run the Database Performance Analyzer Wizard:
Click on the Tools menu, select Analyze and then Performance.
Select Current Database
Select Relationships (figure 8.1) to have the Wizard analyze the relationships that
exist between the tables in your database, or click on All object types and then on
Select All. This will cause the Wizard to analyze every object in the database.
You can select an object by clicking its Check Box.
Click OK to start the analysis.
There are three types of results: Recommendation, Suggestion, and Idea. For a
recommendation or a suggestion, the Wizard can actually perform the optimization for
you. You can ask also to the Performance Analyzer to do all types of optimizations.
Run the Performance analyzer for many cases and observe the results.
Figure 8.1.
8.6. Documenting a Database
127
It is very useful to have a hard-copy printout of a database’s design. This is not
the data that is stored in the database’s tables, but rather the design characteristics of
tables, queries, reports, macros and modules contained within the database. Using the
Documenter Wizard, you can easily create a report that shows the important
characteristics of any of the objects within a database. The report can be printed,
saved as a new table within the database or output to an external file format, such as
Microsoft Excel spreadsheet or an HTML file.
To use the documenter Wizard:
Open the database that you want to document
Select Analyze from the Tools menu and then Documenter.
Choose Current Database (figure 8.2).
o The Properties entry will output the properties of the database file itself,
which can be viewed and modified using File, Database Properties
menu.
o The Relationships entry will output the relationships that exist between
tables and the properties of these relationships.
Click on All Object Types, and then select each object you want to document by
clicking the check box for its entry.
After you have selected all of the objects that you want to document, click the OK
button. The Object Definition report is created and displayed in a print preview
window.
The report can be printed or saved in an external file.
128
Figure 8.2.
Chapter 9. Applying Security to the Database
Microsoft Access provides several handy methods for securing your databases and their
contents. Three of them, listed in the order of increasing usefulness are:
1. Encrypting the database
2. Setting a database password
3. Implementing User-Level Security
Encrypting and Decrypting the Database
An encrypted Access database is inaccessible to other programs, but anyone who
uses Microsoft Access can open the encrypted database. Therefore, the data inside an
encrypted database is not protected. To protect it you must apply the user-level security
procedures.
In order to encrypt/decrypt a database you must be logged on as the owner of the
database.
To encrypt/decrypt a database follow the procedure explained in chapter 8.
129
9.1. Setting a Database Password
The simplest means of securing a database is to set a database password. This
prevents anyone who does not know the password from opening the database with
Microsoft Access.
However, it does not allow you to prevent anyone from accessing particular
objects within the database – this protection can be assured only by user-level security. If
the user-level security is applied properly, setting a database password is unnecessary and
annoying because users will have to enter two passwords – one for their user account and
one for the database.
Likewise, if user-level security has been applied to the database and you do not
have administrative privileges on the database, you cannot set or remove the database
password.
Once a database password is established, whenever anyone attempts to open the database
Access display a dialog box asking for the password. The number of retries is not limited.
To set a database password
Open the database in Exclusive mode. This is done by opening the File Open dialog
and checking the box labeled Exclusive before selecting the database you’re opening.
Click the Tools menu, select Security and then click Set Database Password.
Enter the password. Enter it again in the Verify box.
The password is set when you click OK.
To remove a database password
Open the database in Exclusive mode.
Click the Tools menu, select Security and then click Unset Database Password.
Enter the current password in the Password box.
Click OK. The password is removed.
130
9.2. Implementing the User-Level Security
Use-level security provides three main benefits:
You can limit the persons who can open the database.
You can restrict user access to specific database objects on a per-user and per-
object basis.
You can create groups of users and restrict access on a per-group basis.
The steps to secure a database:
1. Create a new, secure workgroup information file. This file contains information about
the workgroup represented by the file and needs to be accessible to all of the users
who will log on to the secured database.
2. Open Access 97 and define a password for the Admin user of the new workgroup.
This activates the Logon dialog box next time you start Access.
3. Create a new administrator account for the workgroup. Make sure you put this new
user into the Admins group.
4. Exit and restart Access, this time using the new administrator account’s logon name.
Remove the Admin user (which is created by default in every workgroup information
file) from the Admins group. This step is very important – if you leave the default
Admin user as administrator, anyone can use the default system workgroup to gain
access to your database.
5. Open the database to be secured and invoke the User-Level Security Wizard. This
creates a secured copy of the current database.
6. The new copy is created such that only members of the Admins group will have
access to the objects in the database.
You should grant permission to the secured objects to other users or groups as
appropriate.
9.2.1. Creating and Using Workgroup Information Files
131
The Workgroup Information file contains information about the users in a workgroup and
the groups of which they are members. Access reads this file each time it starts in order
to determine whether to display the Login dialog box.
The default workgroup information file, system.mdv, is installed when Access is
installed. It is placed in the windows\system folder on Windows 95/98 systems and in the
winnt\system32 folder on Windows NT systems. This file contains one user, Admin, and
two groups, Admins and Users. The Admin user does not have a password set for it.
By default, Access attempts to log on as the user named Admin with no password.
Therefore, if we don’t change the password for the Admin user, the Login dialog box will
never be displayed.
Access contains an application named Workgroup Administrator, which can be
used to change workgroups and create new workgroup information files. The application
is available as an EXE file, wrkgadm.exe, which is installed into the windows\system
(for Window 95/98) or winnt\system32 (for Windows NT) folder. Typically, the
application is run from the Start menu:
Click the Start button.
Select Run.
Type wrkgadm
To create a new workgroup information file
Run the Workgroup Administrator program.
The application dialog box is displayed as in figure 9.1.
Click the Create button.
Enter the appropriate information in the Name and Organization fields
(figure 9.2).
Enter a unique workgroup identifier in the Workgroup ID field. This can
contain up to 20 letters or numbers. Make sure it’s unique and known only to
you. The workgroup identifier is used to encrypt the workgroup information
file. It can also be used to create a new version of the workgroup information
file, preventing unauthorized access to your system.
132
Figure 9.1.
Figure 9.2.
Click OK. Enter the path and name for your new workgroup information file.
The next dialog box asks you to confirm the information you’ve entered is
correct.
The new workgroup file contains a single user, Admin, and two groups, Admins and
Users. The Users group is a special group in Access 97. All new user accounts you create
are placed in this group. Likewise, you cannot remove any user account from this group.
To join a different workgroup
Click the Join…button in the Workgroup Administrator dialog box.
133
Enter the path to the workgroup information file you want to join.
A message box will tell you that you have successfully joined the workgroup.
9.2.2. Defining User and Group Accounts
Select Security from the Tools menu and then User and Group Accounts.
The dialog box User and Group Accounts (figure 9.3) will be displayed. This dialog
box enables you to perform several administrative tasks. If you do not have
administrative privileges for the current workgroup (that is, you are not a member of
the Admins group), you are only allowed to view the users and the group membership
and change your own logon password. All other buttons and the Groups tab are
disabled.
Figure 9.3. Defining Users, groups and passwords.
Changing your logon password
134
This operation is possible only if you joined the workgroup for which you want to change
your logon password.
Click the Change Logon Password tab.
In the next dialog box, enter the old password (if you have one) and the new
password.
Clearing another user’s password
You can execute this operation only if you have administrative privileges in the
workgroup. In this case, you can log on as the user whose password you want to change
without entering a password.
Log on as the user whose password you want to change.
In the dialog box from figure 9.3, click Users tab and from the Name drop-down list
select the user.
Click Clear Password button. The user’s password will be cleared. Clicking Cancel
will not undo this operation.
Set the new password following the steps described previously.
Creating new user accounts
To do this operation you must be in the workgroup for which you are creating the new
user account.
Start Access 97 and log on as a user who is a member of the Admins group.
In the User and Group Accounts dialog box click Users tab and then New
button.
In the next dialog box enter the user’s name and a unique personal identifier
(4-20 alphanumeric characters). Access combines this with the username to
create the user account.
Click OK. The new user account is created and appears as the selected user in
the Name list.
Creating new group accounts
135
To do this operation you must be in the workgroup for which you are creating the new
group account.
Start Access 97 and log on as a user who is a member of the Admins group.
In the User and Group Accounts dialog box click the Groups tab.
In the next window click the New button.
In the next dialog box enter the group’s name and a unique personal identifier
(4-20 alphanumeric characters). Access combines this with the group to create
the group account.
Click OK. The new group account is created and appears as the selected name
in the Name list.
Modifying the groups to which a user belongs
To do this operation you must be in the workgroup for which you are modifying group
membership.
Start Access 97 and log on as a user who is a member of the Admins group.
In the User and Group Accounts dialog box click Users tab and then select
the user from the Name drop-down list.
To add the selected user to a group, click the group’s name in the Available
groups list and click the Add button.
To remove the selected user from a group, select the group’s name in the
Member Of list and click the Remove button.
Deleting users and groups
To do this operation you must be in the workgroup that contains the user and or group
accounts you’ll be deleting.
Start Access 97 and log on as a user who is a member of the Admins group.
To delete a user, in the User and Group Accounts dialog box click Users tab
and then select the user from the Name drop-down list.
To delete a group, click the Groups tab and then select the group from the
Name list.
136
Click the Delete button.
Printing the list of user and group accounts
To do this operation you must be in the workgroup whose user/group account list you are
going to print.
Start Access 97 and log on as required and open any database to which you
have access. You don’t need to be a member of the Admins group.
In the User and Group Accounts dialog box click the Print Users and
Groups button. This button is disabled if you did not open a database.
Select the desired option from the Print Security dialog box.
9.3. The User-Level Security Wizard
The User-Level Security Wizard is used to create a secured database accessible only to
Admins group members in the currently active workgroup. The wizard makes a copy of
the current database, assigning the user account with which you logged into Access as the
database’s owner. The original database is not modified in any way. You should modify
the user and group permissions after running the wizard in order to provide access to the
database’s objects to other users or groups besides Admins.
Running the User-Level Security Wizard
Make sure you have joined the workgroup for which you are creating the secured
database.
Start Access 97 and log on as a user who is a member of the Admins group.
Open the database you want to secure.
From the Tools menu, click Security and then select User-Level Security
Wizard. The User-Level Security Wizard dialog box is displayed (figure 9.4).
137
Figure 9.4.
The dialog box displays the currently logged-on user and the location of the
current workgroup information file. If either of these is incorrect click Cancel and
exit Access. If the workgroup is incorrect, use the Workgroup Administrator
application to select the correct workgroup and restart Access. If the user is
incorrect, restart Access and log on as the correct user.
Select the types of objects to secure. Click OK to continue.
Use the Save In drop-down menu to set the folder in which the new database
will be created. Name the database using the File Name text box. Click the
save button.
The Wizard displays a message box to inform you if the new secured database
was successfully created or some errors occurred.
9.4. Setting User and Group Permissions
If all users have the same permissions, it is sufficient to use the Admins group. Add
all of your user accounts to this group.
If you want to segregate administrative and user permissions, you need to add a new
group for your users. You could use the built-in Users group, but guessing the Admin
user’s password is all it would take for an unauthorized user to open your database.
Unfortunately, you can’t delete the Admin account from any workgroup.
138
Permissions are set on a per-object basis. There is a different set of permissions
applicable to each type of object (table, form, query, report,module,macro and the
database itself). These permissions may be combined (see figure 9.5), as necessary, for an
object. For example, you may provide Update Data and Insert Data, but not Delete Data,
to a certain group account.
Apply user-level security permissions
Make sure you have joined the workgroup appropriate for the secured database you are
working with.
Start Access 97 and log on as a user who is a member of the Admins group.
Open the database you want to set permission on.
From the Tool menu, click Security and select User and Group
Permissions.
The User and Group Permissions dialog box is displayed (figure 9.5).
The User/Group Name list displays the current set of users or groups,
depending on the currently selected List option button. You can select only
one user or group at a time to work with. Select the user or group whose
permissions you want to change.
The Object Name list displays all the objects of the type selected in the
Object Type drop-down list, plus an entry for a new object of that type.
Select the object type you are interested in.
Using the Object Name list, select the objects(s) for which you are setting the
permissions for the selected user/group. You can select multiple objects by
using the list box’s Ctrl+click and Shift+click extended selection method. You
can also click and drag through the list box’s entries to select multiple objects.
In the Permissions frame, check the boxes next to the appropriate permissions
for the selected object(s) and user/group.
Click the Apply button.
The object permissions are lost if an object is saved with a new name via the
SaveAs/Export command from the File menu or by pasting or importing the object.
139
Figure 9.5.
Chapter 10. Access and the Internet
A hypertext document a document that contains links to other documents or sections
within the document itself, allowing the viewer to quickly move from one document to
another.
Written in HTML format
An HTML doc. is visualized using a specialized browser application
Dual linking capability:
140
Possibilities to retrieve data from other computers
Possibilities that the data from the database can be viewed from other computers
Create hyperlinks in the database – to link records in an Access database to
objects on a network
Publish the data from the database:
Statically – for data that doesn’t change very often.
Dynamically-for data that require a live connection to the database.
10.1. Including Hyperlinks in a database- in fields
- in form controls
10.1.1. Hyperlink addresses:
To address a document, we use an address format that is dependent on the location of the
document:
Local path for a document located on the same computer. Ex: d:\company\
sales.doc
UNCfor a document located in the same LAN
Ex: \\FileServer\marketing\sales.doc, or generally:
\\servername\sharename\document,
where
--servername -- is the host-name of the network
server
--sharename -- is the name given to the shared
directory
--document – is the exact name of the document
URL for a document located in Internet. The
general form is: protocol:address. Ex:
http://FileServer/marketing/sales.htm
141
10.1.2. Hyperlink Fields
In the Design View of a table/query, create a field of type Hyperlink. Ex:
To edit a hyperlink field:
1. Enter the address when the table/query is opened in datasheet view. Examples:
To display a text in the hyperlink field instead of the
address we can use the format:
DisplayText address subaddress
2. Right-click on the hyperlink field (figure 10.1). Choose Hyperlink.
To edit the displayed text click in the text box labeled Display text. To edit the address and subaddress portions or to remove the hyperlink, click
on Edit Hyperlink.
Figure 10.1.
142
In the next dialog box, using the topmost text box, you can edit the address
portion.
The Named location in File text box allows entering or editing the
subaddress portion of the hyperlink. Using the subaddress, you can point with
the hyperlink to a specific location within the file referenced by the address
portion (Ex: a bookmark in a Word doc. or a named cell in an Excel
spreadsheet.
The Remove Link button can be used to delete the hyperlink.
Follow the same steps if you want to enter hyperlink data into an empty field.
10.1.3. Adding Hyperlinks to forms and reports
1. A bound hyperlink control. Ex: create a Customers form using the Form Wizard,
using all the fields of the table. The hyperlink field will be a bound hyperlink control.
See the property sheet of this control. To see the link in action, switch in Form view.
2. An unbound hyperlink control.
Ex: create a hyperlink label control.
The label must not be a label attached by the Access to a bound control.
Delete the CustomerID label from the Customers form
Create a new label
Type the address in the Hyperlink address and Hyperlink subaddress fields of the
label property sheet or use the Builder button to display the Hyperlink dialog box.
Ex. Create a hyperlink command button.
10.2. Publishing data from a database to the Web
Using the Acces97 Web Wizard we can create:
Static Web pages, that always display the same data
143
Dynamic pages that generates queries to Access databases and produce Web pages
using current data from the database.
10.2.1. Exporting Static Web Pages
Create a static Web page from a single database object (table, query, form,
report) in the current database.
To export a database object to an HTML file:
1. Select the object to export
2. Click File menu and select Save As/Export.
3. Select To an External File or Database and then OK.
4. In the Save dialog box, select HTML Documents.
5. Select the location and name to save the HTML file to. If you want to use an HTML
template file, check the box Save Formatted. Click the Export button.
6. If you selected to use an HTML template file, a dialog box will be displayed to
specify the location of the template file.
7. Use the Internet Explorer to view the content of the HTML file.
Use the Nwindtem.htm template file. See it using a text editor.
10.2.2. The Publish to the Web Wizard
Create static pages from multiple database objects
Create dynamic pages using:
Microsoft’s Internet Database Connector
Microsoft’s Active Server Pages
Static Web Pages
1. Click File and select Save As HTML. Select the items of the database to export to
HTML.
2. Enter the necessary information in each dialog box. To create a static Web page,
select Static HTML option.
144
For each selected database object Access creates a different HTML file. In this case, if
you specified to be created a home page for the exported data, then the created home
page will contain links to the individual pages that are created for each object.
Active Server Pages
ASP run on Internet Information Server as well as the Personal Web Server. These
pages contain some scripting language, typically VBScript, which executes on the Web
server. After the script executes, it returns a Web page to the requestor but doesn’t return
any of the script code that has executed. ASP can access any ActiveX/COM component
installed on the server machine, including database components and ActiveX controls.
To create an ASP file:
1. From the File menu select Save As HTML. Select the objects of the database to
export to HTML.
2. You can ask different types of exports for the selected objects.
3. In the dialog box from figure 10.2 you must specify the ODBC connection. This
information is used by the ASP to connect to the database. The name entered in the
Data Source Name must not exist.
If you have secured or encrypted your Access database, you need to enter a user name and password.
145
Figure 10.2.
4. In the next dialog box you must specify the location to which the ASP page should be
stored.
You must place the output files into a directory accessible by a Web server in
order for them to work as expected --ASP files only work when interpreted by IIS.
The folder specified in the I Want to Put My Web Publication in This Folder text
box must be a server-accessible folder.
5. You can ask to create a home page for your exported data. If created, it will contain
links to individual pages that are created for each object selected to export.
To see the result, run Internet Explorer or other browser and type the URL for the ASP
file just created.
146
10.3 Importing and Linking data from Web Pages into an Access database.
Importingcopy the current data from an HTML file into a database. If the HTML file
used as import source is changed after the data is imported, the data in the Access
database will not reflect those changes.
Linkingthe data is retrieved from the HTML file anytime the linked table that is
created in the database is opened.
To import or link a HTML table to an Access database:1. Open the database
2. From the File menu select Get External Data and then Import or Link Tables.
3. In the Files of type list select HTML Documents.
4. Select the file to be imported. If the selected file does not contain an HTML table you
will receive a message.
5. The next dialog boxes advise you what to do to import data from the HTML file.
REFERENCES
1. Gaylord Henry, Getting Started with Microsoft Access 7.0 for Windows 95, John Wiley & Sons, inc., 1997.
2. Harkins Susan, et al., Using Microsoft Access 97, second edition, Que -Macmillan Computer Publishing, USA, 1999.
3. Kroenke M, David M, Database Processing: Fundamentals, Design, and ImplementationPrentice Hall, 2000
4. Teorey J. Toby, Database Modeling and Design, The Entity-Relationship Approach,Morgan Kauffman Publishers, Inc., 1998.
147