access 2016 - ble.lshtm.ac.uk · unlike it’s office siblings, word, excel, and powerpoint where...
TRANSCRIPT
David Grant LONDON SCHOOL OF HYGIENE & TROPICAL MEDICINE | 2017
Access 2016 GETTING STARTED
CONTENTS Understanding Access ................................................................................................................................................ 1
How Access is Different ....................................................................................................................................... 2
How Access Works ............................................................................................................................................... 2
What can Access be Used for? ............................................................................................................................ 3
Starting Access ....................................................................................................................................................... 4
Understanding the Backstage View .................................................................................................................. 5
Opening an existing database file ...................................................................................................................... 6
Create a new database file.................................................................................................................................... 7
Understanding the Access 2016 Screen ............................................................................................................ 8
The Navigation Pane ............................................................................................................................................. 9
Understanding how Access stores data .......................................................................................................... 10
Commonly used data types .................................................................................................................................12
Designing a database ................................................................................................................................................. 13
Design considerations ......................................................................................................................................... 14
Table Design Window ......................................................................................................................................... 17
Building tables ....................................................................................................................................................... 18
Validation rules .....................................................................................................................................................19
Creating Relational/Lookup tables .................................................................................................................. 22
Default Values ....................................................................................................................................................... 25
Viewing table relationships ............................................................................................................................... 26
Importing data ...................................................................................................................................................... 27
Working with a table .......................................................................................................................................... 29
Adding new records ............................................................................................................................................ 30
Deleting records .................................................................................................................................................... 31
Changing records ................................................................................................................................................. 32
Filtering .................................................................................................................................................................. 33
Find and Replace .................................................................................................................................................. 35
Queries ........................................................................................................................................................................ 37
Querying data ....................................................................................................................................................... 38
The Query Designer ............................................................................................................................................. 39
Adding fields to the query .................................................................................................................................. 40
Running the query ............................................................................................................................................... 41
Removing fields from the query ........................................................................................................................ 42
Sorting .................................................................................................................................................................... 43
Selection criteria ..................................................................................................................................................44
Wildcards .............................................................................................................................................................. 45
Querying Ranges .................................................................................................................................................. 46
Querying with boolean operators – AND, OR, NOT ................................................................................... 47
Calculations .......................................................................................................................................................... 48
Multi-table queries .............................................................................................................................................. 49
Grouping results, summing, counting ............................................................................................................. 53
Forms ........................................................................................................................................................................... 55
Create a single item form.................................................................................................................................... 56
Create a split form ............................................................................................................................................... 57
Create a multiple item form ............................................................................................................................... 58
Moving fields in form layout view.................................................................................................................... 59
Deleting fields from a form ................................................................................................................................. 60
Adding fields to a form......................................................................................................................................... 61
Reports ........................................................................................................................................................................ 62
Reports overview ................................................................................................................................................. 63
Creating a report .................................................................................................................................................. 64
Viewing a report ................................................................................................................................................... 65
Using the report wizard ..................................................................................................................................... 66
1
Understanding Access
2
How Access is Different
Unlike it’s Office siblings, Word, Excel, and PowerPoint where you can start to create something
useful almost immediately and directly on the screen, Access needs you to first design and create
structures to hold your data, and then create special template layouts for displaying, manipulating
and presenting that data in a useful and meaningful way. In other words, rather than just play around
and look and see how things are going, Access requires more thought, more planning, and good
designs in order to be used effectively. While there is a lot of learn by doing involved with Access, there
is also great deal more learn before doing associated with it.
How Access Works
Access allows you to do two main things: firstly, it allows you to store huge amounts of data, and
secondly, it allows you to manipulate that data to produce relevant and useful information. This is
what Database Management Systems (DBMS) are all about, and the good news is that Access is one
of the easiest of these to learn and use. Data is stored in tables. Tables are structures made up of rows
and columns and are similar in appearance and operation to Excel worksheets. You do however need
to design and create these tables yourself, before the data can be entered.
The data in tables is manipulated using forms, reports, and queries. A form is mostly used for data entry
(although you can enter data directly into a table). A report is used to manipulate the data and present
it either on the screen or printed on paper in a more pleasing way. A query is used to produce a sub-set
of the data – for example, in a patient appointments system you may only want to see a list of the
patients who are over 65 years of age. Forms, reports, and queries are created as layout frameworks.
Once the framework has been designed you can then run the data from the tables through them.
Indeed, this is a common theme throughout Microsoft Access: design versus display. You create or
modify a form, or report, or query in design mode, and then preview the data in display mode. Even
tables (that store your data) conform to this design/display metaphor. You design a table structure,
then enter the data in a display (they call it a datasheet) view. Tables, forms, reports, and queries are
known as database objects. In fact each of these is like a mini-application within the broader Access
application. Each has a very large range of commands and options that you can use to both design the
structure or framework and also use to display data.
3
What can Access be Used for?
Virtually anything – no exaggeration! You can use Access to create a system for managing your music
or stamp collection, the membership at your local football club, the petty cash, inventory and stock
control, or sales at work, and much, much, much more. Any situation where you need to store data,
manipulate it, and then present it as useful information is a perfect contender for Access.
The only snag with Access is that unless you use one of the pre-created system templates, you need to
plan and design the system and the database objects (the tables, forms, reports, and queries) used in
that system. And this is what takes time and learning to do. As a very rough rule of thumb, when you
have a set of data that will exceed 2,000 rows you should use an Access database instead of an Excel
workbook
4
Starting Access
To create a new database, or work with an existing one, the first thing that you need to do is to start
Microsoft Access. As a standard software application, how Microsoft Access is started is
determined by Windows. For example, it can be started from the Windows Start menu, from a
shortcut, or even by opening a database that was created previously in Access.
Try this yourself:
1. To start Access, click the Start button at the bottom left of the screen. 2. Click on All Programs. 3. Click on Microsoft Office 2016. 4. Click on Access 2016.
5
Understanding the Backstage View
Before you can start using Access you must have a database file open. A database file is where your
database objects (tables, queries, forms, reports, etc) are stored. The Backstage View is, amongst
other things, a gateway to Access where you can nominate which database to open, or create a new
database file.
Template database files
Your recently opened database files
Open other database files
1 2
3
6
Opening an existing database file
A good way to see how Access works is to open an existing database file. If the database file has
recently been opened it will appear in the Recent Database listing in the left panel of the Backstage
View. However, if it doesn’t appear here you will need to use the Open option to display the Open
dialog
Try this yourself:
Select Open other files in Backstage View to display the Open dialog box
Click Computer
Click Browse/Desktop
In the right pane, double-click on the folder icon for Access
Click on A Sample Database and click on [Open] to open the database
7
Create a new database file
From the Backstage View create a new database file
Try this yourself:
1. Click the Blank desktop database icon. 2. Change the name of the new database file to Patients.accdb 3. You can choose a different location to save the database file if you want 4. Click the Create button
1
2 3
4
8
Understanding the Access 2016 Screen
At first glance there’s nothing much to an Access database screen. The screen really only gives you
access to either create, modify, or run one of the database objects in a database file (tables, forms,
reports, queries, etc). It isn’t until you choose to perform one of these operations that the screen really
becomes more intricate.
The Ribbon is the tabbed band that appears across the top of the window. It is the command
control centre of Access. You use the tabs on the Ribbon to access commands which have been
categorised into groups. Commands can be buttons or sometimes include galleries of formatting
options that you can select from. This area really comes to life when a database object is opened,
and like Word and Excel, the ribbon is context sensitive – the tabs change depending on what is
selected
The File tab of the Ribbon is used to access file management functions such as saving, opening,
closing, printing, etc. Access Options are also available so that you can set your working
preferences and options for Access.
The Navigation Pane is used to list and navigate the various database objects (tables, forms,
reports, queries, etc) that exist in the database. In the screen above this area has been filtered so
that only table objects appear – there is only one table in this database and it is named Asset
Items.
The main part of the screen is the data area. Here a database object will appear either in design
or in preview mode. As the database file was newly created, Access has created a new blank
table to jumpstart the database creation process.
2
1
3 4
5
9
The Security and Message area displays information about the database object that is currently
open. Since there are no objects open the area isn’t really showing much at the moment other
than the fact that it is ready for you to start something.
The Navigation Pane
The Navigation Pane is an essential part of Access as it provides you with access to the database
objects that are in your database file. The pane itself can be filtered to show you more or less objects
and you should get a pretty good grasp on how it operates before commencing to create tables or
other database objects.
Try this yourself:
Click on the drop arrow for All Access Objects in the Navigation pane to display the menu
Click on Queries under Filter by Group to see all of the saved query objects in the database
Click on the drop arrow again and click on Reports to see a list of all of the reports.
Click on the drop arrow again and click on All Access Objects to see all of the database
objects
1
2
10
Click on the up arrow for Forms in the Navigation Pane to hide all of the forms
Click on the down arrow that have appeared to display the forms again
Understanding how Access stores data
Before looking at good database design it is important to know how your data is actually stored in
Microsoft Access. Microsoft Access stores your data in tables. These tables are divided into columns
and rows – similar to the structure of a spreadsheet application like Microsoft Excel. In database
tables, the columns are referred to as fields and the rows as records.
Each field (column) in a database table is given a unique name by which it can be identified.
This name appears at the top of the column, just like a column heading, and is known as the
field name.
5 6
1) Columns 2) Fields
3) Records
4) Record Navigation
5) Scroll bar
11
Each field of the database table contains the same type of information for each record in the
database table. For example, one field in the customer database table shown above may
contain the last name of all of the customers, another the first name, another the suburb, and
so on. You can have up to 255 fields in a table.
Each record of the database table is similar to a card in a paper-based system. For example, if
you were using cards to keep track of customers, you would place each customer on a
separate card. In a database table each customer is placed in a separate row, or record. The
number of records you can have is governed by the size of the table – the maximum size for a
table is 2gigabytes minus the space required for system objects (a tad techo at this stage!).
Each record is numbered sequentially as it is entered into the table. This number is known as
the record number and is shown in the record counter in the status bar of the table window.
If there is more data than can fit in the window, the table will appear with scroll bars – as
shown above. You can use these scroll bars to see more of the data.
12
Commonly used data types
Field Type What It Holds
Short Text Text up to 255 characters long (including spaces and punctuation). Use a Text field, not a Number field, for codes even if they look like numbers, such as phone numbers, zip codes, and other postal codes.
Long Text Text up to 65,536 characters. A Long Text field can contain Rich Text (formatted text), and you can set it to Append Only so that it can accumulate text notes without allowing the user to delete what’s already there.
Number Only numbers. You may use + or – before the number, as well as a decimal point. If you plan to do math with a field, use a Number or Currency field.
Currency Numbers with a currency sign in front of them (£, $, ¥, and so on).
AutoNumber Numbers unique to each record and assigned by Access as you add records, starting at 1. Use an AutoNumber field as the primary key field for most tables.
Date/Time Dates, times, or both.
Hyperlink Text string formatted as a hyperlink. (If you click the link, it takes you to the page.) This field type is especially useful if related information is available on the web.
Yes/No Yes or no (a particular condition is, or isn’t, in effect) — or other two-word sets, such as True/False, On/Off, and Male/Female. Use a Yes/No field if you want to display the field as a check box on forms.
Attachment Stores one or more entire files — pictures, sound, Word documents, even video — in one Attachment field.
Calculated Data created with a formula. Use a Calculated field when a calculated value will be used in many queries, forms, and reports.
13
Designing a database
14
Design considerations
In a flat file database, a database without relational data, we will see duplication of data. Access
databases can store data in a relational format which can help reduce duplication. The following table
shows a flat file table of data. The data is structure in much the same way as you would find in an
Excel spreadsheet. As you can see, there are a number of fields containing repeated data, and there
Surname First name Date of Birth Condition Date Diagnosed
Randolph Jasper 11/06/1975 Epilepsy 01/02/1990
Cannon Alexandra 04/05/1980 Epilepsy 02/05/2000
Randolph Jasper 11/06/1975 Arthritis 09/08/2013
Buckner Kaitlin 23/01/1990 Epilepsy 01/07/2010
Buckner Kaitlin 23/01/1990 Psoriasis 10/10/2000
In a relational database we might separate the data into different tables, clustering relevant fields
together. The fields relating to a person could be put into table together like this:
Person ID Surname First name Date of Birth
1 Randolph Jasper 11/06/1975
2 Cannon Alexandra 04/05/1980
3 Buckner Kaitlin 23/01/1990
The medical conditions data for each person could be put into another table.
Person ID Condition Date Diagnosed
1 Epilepsy 01/02/1990
2 Epilepsy 02/05/2000
1 Arthritis 09/08/2013
3 Epilepsy 01/07/2010
3 Psoriasis 10/10/2000
This table structure will reduce the amount of repeated data as you would not need to record the
person’s surname, first name, and date of birth against each medical condition recorded. Instead, you
record just the Person ID number. Ideally, the Person ID should be unique to each person – no two
individuals should share the same ID. Access has a useful data type for ID numbers called
AutoNumber, which will automatically increment with each new row of data. It is important to note
15
that the AutoNumber field cannot be easily reset to zero. In database terminology the field which
uniquely identifies a single row of data in a table is referred to as the Primary Key.
The tables in our new relational database can be shown in diagram form like this
In this structure one patient can have many different medical conditions, but there is still some
repeated data, since the condition field holds a text value. The repeated condition data means that the
database has a potential structure problem. Consider the following:
Can a patient have many medical conditions? Yes. Can a medical condition affect many people? Yes
This scenario is actually a many-to-many data relationship, and in its unaltered form is a structure
that Access cannot represent, since Access can only have tables that are one-to-many related, one-to-
one related, or unrelated.
The solution is to create an intermediary table which links the patients and the medical conditions.
So, one patient can have many medical conditions, and one condition can affect many people. The
intermediary table must contain the primary keys from the tables it is joining together – in this
example the Patients Conditions table must have the primary keys from the Patients and from the
Medical Conditions tables
Person ID Surname First name Date of Birth
1 Randolph Jasper 11/06/1975
2 Cannon Alexandra 04/05/1980
3 Buckner Kaitlin 23/01/1990
Person ID Condition ID Date Diagnosed
1 1 01/02/1990
2 1 02/05/2000
Patients Medical
Conditions
1
∞ Patients Medical
Conditions
Patients
Conditions
1 1
∞
∞
The Patients table
The Patients Conditions table
16
1 2 09/08/2013
3 1 01/07/2010
3 3 10/10/2000
Condition ID Condition name
1 Epilepsy
2 Arthritis
3 Psoriasis
It is important to note that there are best practices when building a database, but there are also times
when it may be easier to store data in a simpler structure.
Take the following scenario. You wish to record the postal address of each patient, but have realised
that a person can have many addresses, and an address can be shared by many people. It is possible to
represent that many-to-many relationship as follows:
The problem with recording addresses in this manner is that you need to update two different tables
in order to add a new address to the database and then pair a person with an address. You would also
need some method of marking which address is the current one and which addresses are old.
If we do not need to know the entire address history of each patient it would be far simpler to just
store the address in the Patients table like this:
Person ID Surname First name Date of Birth Address Line 1 Post code
1 Randolph Jasper 11/06/1975 101 Vale Lane AB1 8HG
2 Cannon Alexandra 04/05/1980 202 Stile Ave BC2 5HY
3 Buckner Kaitlin 23/01/1990 43 Dell Drive CD1 1PL
The Conditions table
∞ Patients Addresses Patients
Addresses
1 1 ∞
17
Table Design Window
The table design window is where we name the fields which make up each table, set the data types of
each field (and the field properties such as default values or validation rules), nominate a primary key,
and look up related data in other tables.
Field Names. Each name should be unique and succinctly describe the data held in the field
Data types. Choose carefully as it can be problematic to change data types once data has been
entered.
(Optional) Field descriptions. The descriptions are only visible in design view and may be
useful to other database designers
The Field Properties palette. The properties for the currently selected field. In the image
above the ID field is selected
Primary Key icon. Nominate the currently selected field as Primary Key. Each record should
have a unique identifier, by nominating a primary key you are instructing Access to make
sure that the primary key field is always unique. If in doubt use the AutoNumber data type
for the primary key field as the values will automatically be unique for each record.
1 2 3
5
4
18
Building tables
It’s possible to create tables by just entering data into a datasheet and having Access guess the correct
data type for each field based on what you have typed. A slightly more controlled method is to create
a table in Design mode where you choose the field data types before entering the data. We will start
by building the Patients table
Try this yourself:
Click the CREATE tab at the top of the screen
Click the Table Design button, in the Tables group of buttons
Enter the Field Names and choose the Data Types as follows:
Field Name Data Type
ID AutoNumber
Surname Short Text
First Name Short Text
Date of Birth Date/Time
Sex Short Text
Address Line 1 Short Text
Post Code Short Text
Telephone Short Text
Email Short Text
Select the ID field by single clicking on the field name
Click the icon to set the ID field as primary key
Click the Save icon at the top-left of the screen
19
Name the table Patients and click OK
Validation rules
It is important to note that although you can put validation rules on most fields you should use them
vary sparingly. Validation rules prevent data being entered unless that data meets the rules we define.
For example you may wish to prevent patients being entered with dates of birth in the future. If data
you are entering fails validation then the record cannot be saved – you must change the data until it
passes validation, or undo/cancel the change. You can find some sample validation rules at the
following URL or on the next page, but remember to use them sparingly.
http://allenbrowne.com/ValidationRule.html
Try this for yourself:
1) Select the Date of Birth field by click on the field name
2) In the properties palette for the Date of Birth field click into the Validation Rule box and
type the Validation Rule:
<=Date( )
3) Type the Validation Text:
Date of birth cannot be in the future
20
Click the Save icon at the top-left of the screen
1
2
3
21
To do this ... Validation Rule for Fields Explanation
Accept letters (a
- z) only
Is Null OR Not Like "*[!a-z]*" Any character outside the range A to Z is rejected.
(Case insensitive.)
Accept digits (0
- 9) only
Is Null OR Not Like "*[!0-9]*" Any character outside the range 0 to 9 is rejected.
(Decimal point and negative sign rejected.)
Letters and
spaces only
Is Null Or Not Like "*[!a-z OR
"" ""]*"
Punctuation and digits rejected.
Digits and
letters only
Is Null OR Not Like "*[!((a-z)
or (0-9))]*"
Accepts A to Z and 0 to 9, but no punctuation or
other characters.
Exactly 8
characters
Is Null OR Like "????????" The question mark stands for one character.
Exactly 4 digits Is Null OR Between 1000 And
9999
For Number fields.
Is Null OR Like "####" For Text fields.
Positive
numbers only
Is Null OR >= 0 Remove the "=" if zero is not allowed either.
No more than
100%
Is Null OR Between -1 And 1 100% is 1. Use 0 instead of -1 if negative percentages
are not allowed.
Not a future date Is Null OR <= Date()
Email address Is Null OR ((Like "*?@?*.?*")
AND
(Not Like "*[ ,;]*"))
Requires at least one character, @, at least one
character, dot, at least one character. Space, comma,
and semicolon are not permitted.
You must fill in
Field1
Not Null Same as setting the field's Required property, but lets
you create a custom message (in the Validation Text
property.)
Limit to specific
choices
Is Null OR "M" Or "F" It is better to use a lookup table for the list, but this
may be useful for simple choices such as
Male/Female.
Is Null OR IN (1, 2, 4, 8) The IN operator may be simpler than several ORs.
Yes/No/Null
field
Is Null OR 0 or -1 The Yes/No field in Access does not support Null as
other databases do. To simulate a real Yes/No/Null
data type, use a Number field (size Integer) with this
rule. (Access uses 0 for False, and -1 for True.)
22
Creating Relational/Lookup tables
You should aim to build the tables on the “one” side of one-to-many relationships first as this will mean you
don’t have to go back and change the table designs later. So far we have created the Patients and Treatments
tables and now we will create the intermediary table which joins the two together.
Try this yourself:
Click the CREATE tab at the top of the screen
Click the Table Design button, in the Tables group of buttons
Enter the Field Names and choose the Data Types as follows:
Field Name Data Type
ID AutoNumber
Patient Short Text
Treatment Short Text
Timestamp Date/Time
Select the ID field and nominate it as primary key
Click the Save icon at the top-left of the screen
Name the table Patients Treatments and click OK
Change the Patient Data Type from Short Text to Lookup Wizard…
23
You will be asked whether to look up the values or type them in. Leave the top radio button selected
and click Next >
Single click on the Patients table and click Next >
Use the > chevron to move the ID, Surname, First Name, and Date of Birth fields onto the selected
list, then click Next >
24
Sort fields by Surname, First Name, and Date of Birth in Ascending order, then click Next >
You can choose to show the ID field by un-ticking the checkbox if you wish. Click Next >
Keep the label name as Patient. Tick Enable Data Integrity, select the Restrict Delete radio
button. This will ensure that a Patient’s record cannot be deleted if they have related data in the
Patient Treatments table, and is generally the safer of the two radio button options. Click Finish
You will be prompted to save the table, click Yes
25
Default Values
It is possible assign default values to fields when building tables and forms in Access. As we have not yet
looked at forms we will see how to assign a default value to a field at the table level. Manually entering data
in the timestamp field could potentially be time consuming, so we will set the field to the current date and
time of the computer at the time each new record is created
Not all field data types can accept a default value
The following data types will accept a default value:
Short Text,
Long Text
Number
Date/Time
Currency
Yes/No
Hyperlink
Whereas the following data types will not accept a default.
AutoNumber
OLE Object
Attachment
Calculated
You can also use the Date( ) function to assign the current date or the Now( ) function to assign the current
date and time as a default value
Try this for yourself:
If not already open, open the Patient Treatments table in Design view
Click on the Timestamp field to select it
In the Field Properties palette at the bottom of the screen, enter the Default Value as =Now( )
Click the Save icon at the top-left of the screen
26
Viewing table relationships
Table relationships can be viewed and edited using the Relationships tab. This tab gives you a better
understanding of how tables are related or joined together. It also lists all of the fields in each table so that
you can locate content easily. The Relationships tab can be used to document part of your database design
by printing it as a report.
Try this for yourself:
Click on the DATABASE TOOLS tab on the Ribbon
Click the Relationships button in the Relationships group
Access has automatically created the one-to-many relationships between the three tables
If you would like to print a copy of the relationship diagram click the Relationship Report icon,
near the top left of the screen
27
Importing data
Access can import data from a wide variety of applications, including Microsoft Excel. The key is ensuring
that the structure that you import from has the same field names as that of the table into which the data is
to be placed and that the data being imported doesn’t violate any validation rules.
Try this for yourself:
Click on the EXTERNAL DATA tab on the Ribbon
Click the Excel icon, under the Import control group
Browse and select the Patients.xlsx file from the Access course materials folder
Choose the Append a copy of the records to the table radio button
Select Patients
Click OK
3
4 5
6
1
2
28
You will see a preview of the data from the Excel Workbook. Click Next >
The first row will of the data will be detected as containing the field names. Click Next >
Click Finish, then click Close
Double-click the Patients table in the navigation pane to open the table and see the newly imported
data
29
Working with a table
A table is used in a database file to store data. A table has a defined structure and in Access whenever the
table is open, it is seen either in Design mode or in Datasheet mode. When it is in Design mode you can make
changes to the structure of the table but not the data itself, and when it is in Datasheet mode you can make
changes to the data but not the structure.
Try this yourself:
Double-click on under Tables in the Navigation pane, to open the table in
Datasheet mode – this mode provides access to the actual data
On the Home tab of the Ribbon, click on the top half of View in the Views group to switch
to Design view. This mode displays the structure of the table. There are also view buttons at the
bottom of the screen which allow you to toggle between design and datasheet modes…
Click on Datasheet view in the bottom right of the window to see the data again
Click on X to close the table
1) Datasheet mode 2) Design mode
30
Adding new records
The easiest way to enter data is directly into an open table. When you open a table you are shown the
Datasheet view. Access always displays the records in the table plus one additional row at the bottom of the
table. This is the new record row where a new record can be entered. The total number of records, shown in
the status bar, will increase as you add data.
Double-click on
under Tables in the Navigation pane to open the table in Datasheet mode – this mode provides
access to the actual data
Click the New button in the Records control group on the HOME tab
The cursor will jump down to the end of the table and put the cursor in the first field
Type your new record, but remember that you don’t need to type anything in the ID field as the
AutoNumber function will choose the next number in the sequence for you. Enter the following
Move off the new record to a previous record, or hold the Shift key and press Enter
Surname Walsh
First Name Robert
Date of Birth 05/09/1960
Sex Male
Address Line 1 100 London Road
Post Code EN58
Telephone 020 8509 6659
Email [email protected]
31
Deleting records
Think of a database table as a long list of entries. To delete a record the database must pull the record out of
the list, move all of the records below it up one line in the table, and then renumber the list. Fortunately, all
of this happens behind the scenes. Once a record is deleted, the only way for that record to be brought back
again is for it to be entered as a new record.
Try this for yourself:
Place the cursor over the record selector of the record you would like to delete. The cursor will
change to a solid black arrow
Single click on the record selector
Press the Delete key on the keyboard or click the delete button in the Records control
group on the HOME tab.
You will be shown a warning prompt, click Yes to delete the record
32
Changing records
Changing records in Access is very similar to changing data in an Excel workbook. The important thing to
note is that Access only asks you to save design changes such as moving or adding fields, or changing the
sort order. Changes made to records are committed when you leave the record you are editing such as by
clicking, or you can hold the Shift key and press Enter - you don’t need to click the save icon when
making data changes to records, just move to another record
Try this for yourself:
In the Navigation pane double-click the Patients table to open it in Datasheet view
Single click within any field and type your changes
Access indicates that there are pending changes to the current record by displaying a pencil icon in
the record selector
When you move to another record your changes are committed to the database and the pencil icon
will disappear.
33
Filtering
Access allows you to hide records in the table by setting a filter. When you set a filter you must provide
Access with criteria that it can use to work out which records to display and which to hide. The simplest
form of criteria allows you to choose an existing value from a field in the table. This value is then compared
to the values in the other records, and records that don’t match are hidden. Filters can be applied to Tables,
Queries, Forms, and Reports, but not to objects in print preview.
There are several ways to apply filters to your data:
Using the Sort & Filter control group on the HOME tab
Right-clicking on the field you wish to filter.
Clicking the arrow next to the right of the field name in datasheet view
Using the right-click method is particularly fast and convenient. Simply click the right mouse button in field
you want to filter. To show only records for Patients who live in the EN56 post cost, right-click on any
records with the EN56 post code and choose Equals “EN56” from the list. All records with the EN56 post
code will be displayed, records with other post codes will be hidden
You can remove and reapply the filter instantly, using the
Toggle Filter button in the Sort & Filter control group on the
HOME tab
Filters can be stacked up one after another. For example you
could apply a filter to show only those with the EN56 post code,
then apply an additional filter to show only female patients
You can even use filters to match parts of your data such as ‘surnames beginning with the letters Pr’, by
selecting the target data with the mouse.
34
Select the first two letters of Irma Price’s surname (Select “Pr” using the mouse)
Then right-click and choose Begins With “Pr”
All records will be hidden except those whose surnames being with “Pr”
To see all records click the Toggle filter button
35
Find and Replace
Sometimes you will have a need to make the same change to several records. Rather than making these
changes manually and possibly making a mistake, you can use the Find & Replace tool to search for text and
replace it automatically. Use the replace options with care as it may not be possible to undo the changes you
make using this tool. The Find and the Replace tool are tabs on the same control, so if you click the Find
button but wanted the Replace tool simply change to the other tab
Double-click on under Tables in the Navigation pane to open the table in
Datasheet mode
On the HOME tab, in the Find control group, click the
Replace tool
In the Find What box enter the search term Quis
In the Replace With box enter the word Quiet
Click the Replace All button
You will be shown a warning dialogue, click Yes to replace all instances of the word Quis with
Quiet
36
A second or two later the text replacement will be complete. At the bottom-left of the screen you can see how many instances were replaced
37
Queries
38
Querying data
Now that we have populated our three tables we can use the Access query builder to look at snapshots of
our data. We will be focusing on a type of query called a Select query. A select query is like a filter that you
place on your data so that you see only the information that is relevant to you. Select queries can be used, for
example, to produce a list of patients from a particular age range, or list all treatments carried out over the
last six months that cost more than £50. Select queries are so named because they select records according
to your query design. Select queries are created using the CREATE tab of the ribbon, and are run and
modified as a Query object in the Navigation Pane. A query can be based on one or more tables or even other
queries
Try this for yourself:
Click the CREATE tab at the top of the screen
Click Query Design in the Queries control group near the top-left of the screen.
When you open the Query Designer to create a new query you will be prompted to add one or more
tables or queries. Single click the Patients table in the list, click Add, then click Close
39
The Query Designer
Query types.
a. Select is used to display data.
b. Make Table will create a new table based upon the data that the query displays – this could
be a new table based on the results of a query joining two other tables together.
c. Append will take the set of data displayed by the query and add it to the end of a table of
your choice.
d. Update is used to update multiple records – you can use criteria to affect a subset of records,
or leave the criteria blank to affect all records.
e. Crosstab is used to create a query much like a pivot table in Excel, taking a column of data
and turning into row headings and aggregating data.
f. Delete queries can delete multiple records so use with caution.
The table we are querying. More complex queries will use multiple tables and
The fields that will be used in the query.
a. Sorting. It is possible to sort any and all fields, but the sort always occurs from left-to-right
(the leftmost field is sorted first, the rightmost field sorted last). However, you can add
fields multiple time to achieve sort orders that differ from the display order of the fields.
b. Show. Leave the box ticked to show the column, un-tick the box to hide it
c. Criteria. Criteria boxes are used to filter the results. For example, you could filter results by
date range, looking for dates of birth Between #30/06/1965# And #31/12/1980#
2
3
1
40
Adding fields to the query
There are three methods for adding fields to a query
Double-click a single field in a table or query at the top of the screen to add it to the field list in the
lower half of the screen
Select one or more fields from a table or query box at the top of the screen, you can use the CTRL
key to select multiple fields, then click and hold the mouse button, and drag the selected fields on to
the field list in the lower half of the screen.
Click within a blank field box in the lower half of the screen and select a field from the list.
1
2
3
41
Running the query
When you want to view the results of your select query you can use either the View or the Run button to
see your data. Notice that the View icon looks like a datasheet as that is the view that will be displayed.
To return to the query designer, click the View icon at the top-left of the screen. Practice switching between
Datasheet and Design views as you will be doing this lots. The Access query builder allows you to build very
complex queries so it’s important to check often that your query returns the results you are expecting.
42
Removing fields from the query
Immediately above each field name in the field list is a short, wide button that is easily overlooked. Clicking
on that button will select the field. The mouse cursor will change to a black arrow pointing down when you
have the cursor over the button. You can click and drag across multiple field names to select more than one
field.
Here you can see that the First Name and Surname fields have been selected:
Simply press the Delete key on the keyboard to remove the selected fields from the query
43
Sorting
Access query fields are sorted in the column order they appear on the screen from left to right. You can
choose either ascending, descending, or no sorting for each field. This sorting method takes place before the
data is drawn to the screen.
In this example three fields will be display when the query is run, but only the Surname field will be sorted
in Ascending (alphabetical order),
Remembering that it is only possible to sort fields listed left to right, if we want to show the First Name,
Surname, and Date of Birth fields, but sort by Surname then First Name we would need to add a copy of the
First Name field to the list after the Surname field. The duplicate First Name field could then be sorted
ascending, but the ‘Show’ box is left un-ticked
In tables, queries, and forms you can also dynamically sort the data on-screen using the Sort & Filter group
of controls on the HOME tab, or using the arrow in the column header to sort a field.
44
Selection criteria
As we have seen previously, it is possible to pick and choose which fields (columns) your query displays.
The Access query builder also allows you to apply selection criteria to your query to restrict the records
returned.
Select criteria is entered into the Criteria box(es) below the field you would like to limit. For example, to
return only patients whose surname is Rose, simply type “Rose” into the Criteria box. You can even let
Access add the double quotes for you and type Rose. It is important to note that tables in Access are not case
sensitive to case, so ROSE and Rose and RoSE are all equal.
When you view the query results only one person is returned:
You can multiple criteria under each field as per the example below. This query will return patients with
surnames exactly equal to “Rose” OR equal to “Allison”
If you place criteria on the same row you are attempting to select records that meet multiple conditions at
the same time. In the example below records will only be returned if a patient’s surname is Kent and the first
name is Robert – both conditions must be true for the record(s) to be displayed
45
Wildcards
Use wildcards when you need to return records that begin, end, or contain particular values. The wildcard
characters can be used in both the query designer as part of selection criteria and also in the Find/Replace
dialogue when searching for records.
Character Description Example
* Matches any number of characters. You can use the
asterisk anywhere in a character string.
wh* finds what, white, and why, but
not awhile or watch.
? Matches any single alphabetic character. B?ll finds ball, bell, and bill
[ ] Matches any single character within the brackets. B[ae]ll finds ball and bell but not bill
! Matches any character not in the brackets. b[!ae]ll finds bill and bull but not ball or
bell
-
Matches any one of a range of characters. You must
specify the range in ascending order (A to Z, not Z to
A).
b[a-c]d finds bad, bbd, and bcd
# Matches any single numeric character. 1#3 finds 103, 113, 123
46
Querying Ranges
There are two methods to return records between ranges of values
Either use keywords:
Between _______ And _______
For example:
Between 23 And 99
Or you can use relational operators:
>=_______ And <= _______
For example:
>= 23 And <= 99
(Greater than or equal to 23 and less than or equal to 99)
47
Querying with boolean operators – AND, OR, NOT
You can use the Boolean operators And, Or, and Not in your criteria. Remember that the And operator
should be used cautiously within a single criteria box as unless you are using a wildcard it is unlikely that a
single field will meet both conditions (you will return zero results in most cases). In most cases you will
need the Or operator. For example:
A search for Duncan Or Jensen will yield results
But a search for Duncan And Jensen will return nothing, since a surname cannot be exactly equal to Duncan
and Jenson at the same time, no records will meet the criteria and the result set will be zero.
Patients in our database have one of three post codes; EN56, EN57, EN58. Use the Not operator to exclude a
post code from the results:
48
Calculations
The Access query designer makes it easy to run calculations on your data. The calculations are performed
the instant the query is displayed, which is particularly useful when performing date based calculations
such as working out ages from dates of birth, or summing the costs of treatments.
Some of our field and table names contain spaces, so we will need to surround the names with square
brackets [ and ] when referring to those fields in calculations. Calculations are performed on each record
that is returned by the query and since we can use fields from any of our tables or queries it is important to
be clear exactly which table and field you are referring to in your calculations.
The syntax to use a field in a calculation is:
[Table Name].[Field name]
For example:
[Patients].[Date of Birth]
We can also use functions such as Date( ) which returns the current date, or Now( ) which returns the
current date and time. Unfortunately, the complete list of functions available is very long, but Microsoft
provides documentation online: http://msdn.microsoft.com/en-us/library/office/ff823033.aspx
To work out a person’s age we first need to find how many days they have been alive:
Date( )-[Patients].[Date of Birth]
We can then divide the result by 365.25 to work out how many years they have been alive. The .25 is to
account for leap years:
(Date()-[Patients].[Date of Birth])/365.25
Type the formula in the query designer and notice what happens when you leave the field by pressing Enter,
or Tab, or by clicking elsewhere on the screen.
Access will prefix your calculated field with Expr1:
49
This is simply the query designer providing a name for the calculated field as none had been specified yet.
You can rename the field from Expr1 to Age
You can rename any field in this manner and the new name does not have to be surrounded by square
brackets
New Name: [Table Name].[Field Name]
For example:
Email Address: [Patients].[Email]
Jumping back to our age calculation, you will notice when you run the query that it returns ages with lots of
numbers after the decimal (unless it is that person’s birthday today).
Since we often refer to ages by whole numbers
only (unless you’re very young, then it’s okay to
age by fractions), we should return the whole
number only. The name for whole numbers is
integers and we can use another function Int( )
as part of our age calculation to return just the
whole number of the age. We place our age
calculation inside the brackets of the Int
function which will then remove all numbers
after the decimal place.
So our final version of the age calculation will
look like this:
Age: Int((Date()-[Patients].[Date of Birth])/365.25)
Multi-table queries
50
A trade-off with a database design that separates data into multiple tables is that we are often required to
build queries that fetch results from many different tables at the same time. In our Patients and Treatments
database we have three tables – Patients, Patient Treatments, and Treatments. In order to see which
treatments have been which to each patient and what the financial costs were will need to build a query
that fetches records from all three tables at the same time, by exploiting the data relationship between the
three tables.
First we will need to add all three tables to our query by clicking the Show Tables button at the top of the
screen
Hold down the Ctrl key and select the tables that are not already part of your query, click Add, then click
Close
Your query designer will now show all three tables and allow you to add fields from any of them
There is an important limitation to be aware of. The default join type between the three tables is called the
intersection. Using the default join, results will only be returned for a) Patients who have one or more
51
records in the Patients Treatments tables, b) Treatments that have been used one or more times in the
Patients Treatments table.
If you would like to return a list of patients, even those without treatment records, but also return the
treatment records where present, you will need to alter the join type. You do this by double-clicking on the
black line joining the Patients table to the Patient Treatments table and choosing option 2, then clicking OK
You will also need to alter the join between the Patient Treatments and Treatments tables, but this time
choose options 3.
You will see that the line joining the tables has been altered and now has an arrow pointing away from the
Patients table (the arrow should always point away from the table which you want to return all results).
52
You will see that the line joining the tables has been altered and now has an arrow pointing away from the
Patients table (the arrow should always point away from the table which you want to return all results. If
none of our patients had treatment records then we would return just a list of names, but because of the
relational nature of our data, we will see all of the treatment records for each patient, even if that causes
multiple rows to be shown such as for Karina Dickson and Xena Dotson in the query below:
53
Grouping results, summing, counting
Following on from the multi-table queries of the previous section we can use the fact that some queries will
return multiple rows of data per person to carry out a sum of the cost of treating each person. The term for
summarising data in this way is aggregation, and in Access you switch on aggregation using the Totals icon,
which is on the DESIGN tab, which can only be found query design view:
To build a multi-table query that sums the patient costs, start by building a select query and remember to
change the default join types so the arrows point away from the Patients table,
Click the Totals button at the top of the screen
54
Switching on Totals will create new row in the lower part of the screen, and by default all fields will say
“Group By”. Just like when sorting data, the group by behaviour works from the leftmost field to the
rightmost field. Group by will remove duplicate rows of data and show just a single row instead of many,
but since it is possible for people to have the same name we need to group by ID, otherwise the totals for
two different people with the same name would be merged together. Grouping by ID will prevent this in our
database thanks to the AutoNumber making sure that each patient has a unique number. We can still show
the Surname and First Name fields since the ID field is leftmost in the list and will be grouped first.
Change the Cost field total from Group By to Sum
When you run the query, patients with multiple rows of data in the Patients
Treatments table will only appear once in the query and their treatment costs
will be summed
You can even add the Cost field multiple times and carry out a different
total on each copy, such as the Maximum, Count, and Average (Mean)
cost:
55
Forms
56
Create a single item form
Access comes with a powerful form builder that will build a form in seconds, using all the fields on a table or
query of your choice. When you use the form tool, all the fields from the underlying data source are added to
the form. You can start to use the new form immediately, or you can modify it in Layout view or Design view
to better suit your needs, by removing fields or changing the layout, for example.
To use the form tool, in the Navigation Pane, click the table or query that contains the data that you want to
see on the form, such as the Patients table.
On the CREATE tab, in the Forms group, click the Form button
Access creates the form and displays it in Layout view. In Layout view, you can make design changes to the
form while it is displaying data. For example, you can adjust the size of the text boxes to fit the data.
To begin using the form, switch to Form view:
On the HOME tab, in the Views group, click the View button
Automatic subdatasheet creation
If Access finds a table that has a one-to-many relationship with the table or query that you used to create the
form, Access adds a Subdatasheet to the form that is based on the related table or query. Creating a simple
form that is based on the Patients table, there is a one-to-many relationship defined between the Patients
table and Patient Treatments table, the Subdatasheet displays all the records in the Patient Treatments table
that pertain to the current Patient record. If you decide that you do not want the Subdatasheet on the form,
you can delete the Subdatasheet by switching to Layout view, selecting the datasheet, and then pressing
DELETE.
If there is more than one table with a one-to-many relationship to the table that you used to create the form,
Access does not add any datasheets to the form.
57
Create a split form
A split form gives you two views of the data at the same time — a Form view and a Datasheet view.
Working with split forms gives you the benefits of both types of forms in a single form. For example, you
can use the datasheet portion of the form to quickly locate a record, and then use the form portion to view or
edit the record. The two views are connected to the same data source and are synchronized with each other
at all times.
To create a new split form, in the Navigation Pane, click the table or query that contains the data that you
want to see on the form, such as the Patients table
Next, click the CREATE tab, click More Forms, and then click Split Form.
Access creates the form and you can then make design changes. For example, you can adjust the size of the
text boxes to fit the data, if necessary.
58
Create a multiple item form
At first glance a multiple item form is like the datasheet view for tables and queries, but you have full control
over the appearance and behaviour of every field and can even trigger events using a programming language
built into Access called Visual Basic for Applications.
To create a new multiple items form, in the Navigation Pane, click the table or query that contains the data
that you want to see on the form, such as the Patients table
Access creates the form and you can then make design changes. For example, you can adjust the size of the
text boxes to fit the data or remove unwanted columns, if necessary.
59
Moving fields in form layout view
Place the cursor over the field you would like to move. The pointer should change to this
Single click on the field to select it. If you also want to move the label you should hold down the
CTRL key and also click the label. The selected field and label will be highlighted orange
Click and hold the mouse button and drag the fields to the new position in the layout.
60
Deleting fields from a form
Place the cursor over the field you would like to move. The pointer should change to this
Single click on the field to select it. You don’t need to select the label separately.
Press the Delete key on the keyboard.
By default Access leaves behind a placeholder in the space of the deleted field. You can delete the
placeholder using the same technique – single click on it, then press Delete on the keyboard
61
Adding fields to a form
Adding existing fields to a form can be done in either Layout or Design view.
Click the DESIGN tab.
Click the Add Existing Fields button
A new pane will appear on the right side of the window that will list the available fields.
Click a field in the list (you can hold down the CTRL key and click multiple field names).
Click and drag the selected field(s) onto the form, then release the mouse button.
62
Reports
63
Reports overview
Reports in Access provide a way of presenting data from either tables or queries. In essence, reports are used
to present raw data in a format that is more readable, understandable, and better to look at and print.
Reports have traditionally been produced as printed documents but they can also be viewed on the screen or
published to the Web. Before creating a report, it is advisable to understand how they work and what they
can actually do for you. Like forms, reports don’t contain data but act as placeholders or templates for data
stored in your tables or queries.
Access provides several methods for building reports all of which can be found on the CREATE tab in the
Ribbon. The methods of creating a report vary in difficulty:
A basic report using the Report tool – these reports appear almost instantly and require very little
additional work.
More intricate reports using the Report Wizard tool – the Report Wizard takes you through a
series of questions, after which the result is a report.
Design from scratch using either the Blank Report tool or the Report Design tool. These options
present you with a blank report canvas and you are required to do all of the work to lay out what
you want, where you want it, and how it should look.
There is no right or wrong way of creating reports – choose the method that achieves the results using the
least amount of time and effort. The beauty of the reporting tools in Access is that even after you have
created a report using any of the techniques mentioned above, the report can still be modified and
customised to suit specifically what you are after. Even if the basic report doesn’t quite provide you with
what you want or the Report Wizard hasn’t quite done all it should, you can still change the report design
yourself. Many Access users create their reports using the Report tool or the Report Wizard tool and then
fine-tune the layout or the design to suit their needs. Where possible try to keep your reports simple – it’s
often better to present individual reports which have a single focus, than to present one report that holds
too much information.
64
Creating a report
The easiest and simplest way to create a basic report in Access is to use the Report tool which is located on
the CREATE tab of the Ribbon. Select the table or the query in the Navigation pane as the basis for the
report, then click the Report button.
To use the report tool, in the Navigation Pane, click the table or query that contains the data that you want
to see on the form, such as the Patients table.
On the CREATE tab, in the Reports group, click the Report button
Access creates the report and displays it in Layout view. In Layout view, you can make design changes to the
report while it is displaying data. For example, you can adjust the size of the text boxes to fit the data, or
add/remove fields.
65
Viewing a report
To see your report in all its glory double click its name in the Navigation pane, or if you have just created a
report using the Report tool, switch to either Report View or Print Preview. Report View and Print Preview
are very similar, but print preview shows the page boundaries whereas report view shows a continuous grid
of data, much like a multiple-items form.
Report View Print Preview
66
Using the report wizard
On the CREATE tab, click the Report Wizard icon
Add the Patient and Treatments fields from the Patient
Treatments table, then add the Cost field from the Treatments
table.
Click Next >
Leave the report on view ‘by Patient Treatments.
Click Next >
Add a grouping level for Patient, then click Next >
67
Click the Summary Options button
Tick Sum and Avg to show the sum and mean costs of
treatments for each person, then click OK
Leave the sorting, click Next >
68
Change the layout to Block, leave the Orientation as
Portrait, click Next >
Choose a title for your report or leave it as the default,
then click Finish
Your report will be launched in Print Preview a few seconds later showing a list of treatments for each
patient and the sum and mean cost of each patient’s treatments