Introduction
Introduction
Often you need information that isn't directly available in a field in your database.
For example, you might need to calculate sales tax on an order. At other times, you
need to supply a query or a filter with criteria — information that determines which
records you work with. Perhaps you want to set a default value for a field or control,
or a validation rule for a field or table. In all of these cases, you use an expression.
This article provides examples of expressions. The examples are organized first by
where you would employ them, such as in a form or report, or as a default value.
Then they're organized by what they do, such as manipulate text or calculate
arithmetic values. The examples are designed to work in databases that use the
default ANSI SQL query mode, which is ANSI-89.
For more information about how and where to use expressions, see the article
Create an expression.
This section contains examples of expressions that you can use to create a
calculated control in a form or report. A calculated control is a control whose
ControlSource property is an expression, instead of a field. Calculated controls are
easy to spot, because they always start with the = (equal sign) operator. You use
the ControlSource property to tell Access where to get the data for the control.
Click the form or report, and then click Design in the Database window.
On the View menu, click Properties to display the property sheet for the text box.
Change the value in the Control Source property box of the text box to the
expression. For example, insert an expression from the Expression column in the
table in the following section.
The expressions in the following table use the & (ampersand) and the + (plus)
operators to combine text strings, or use built-in functions to operate on a text
string, or otherwise operate on text to create a calculated control.
Expression Result
=[FirstName] & " " & Displays the values of the FirstName and LastName
[LastName] fields, separated by a space.
=IIf(IsNull([Region]), [City] Uses the IIf function to display the values of the City
& " " & [PostalCode], and PostalCode controls if the value in the Region
[City] & " " & [Region] & " control is null; otherwise, it displays the values of the
" & [PostalCode]) City, Region, and PostalCode controls, separated by
spaces.
=[City] & (" " + [Region]) Uses the + operator and null propagation to display the
& " " & [PostalCode] values of the City and PostalCode controls if Region is
null; otherwise, it displays the values of the City,
Region, and PostalCode controls, separated by spaces.
Null propagation means that if any component of an
expression is null, the entire expression is also null.
The + operator supports null propagation; the &
operator does not.
You use the Page and the Pages properties to display or print page numbers in
forms or reports. The Page and Pages properties are available only during printing
or print preview, so they are not listed on the property sheet. Most often, you place
expressions such as these in a text box control in the header or footer section of
your form or report.
Expression Result
=[Page] 1
You can use expressions to add, subtract, multiply, and divide the values in two or
more fields or controls. You can also use expressions to perform arithmetic
operations on dates. For example, if RequiredDate is a Date/Time data type field or
control, the expression =[RequiredDate] - 2 returns a Date/Time value equal to two
days before RequiredDate.
Expression Result
=[Price]*1.06 The product of the value of the Price control and 1.06
(adds 6 percent to the Price value).
Note When you use an arithmetic operator (+, -, *, and /) in an expression, and the
value of one of the controls in the expression is null, the result of the entire
expression will be null. If some records in one of the controls that you used in the
expression might have a null value, you can convert the null value to zero by using
the Nz function, for example, =Nz([Subtotal])+Nz([Freight]). See the article Nz
function for more information.
Sometimes you need a value that exists somewhere else, such as in a field or
control on another form or report. You can use an expression to return the value
from another field or control.
The following table lists examples of expressions that you can use in calculated
controls on forms.
Expression Result
The following table lists examples of expressions that you can use in calculated
controls on reports.
Expression Result
Expressions that count, sum, and average values by using aggregate functions
Often you need to calculate a sum of the values that are stored in a group of
records. For example, you might want to calculate a group total for the group footer
in a report, or an order subtotal for line items on a form. At other times, you need to
count the number of items rather than to sum them; or you need to calculate the
average value. The expressions in the following table use functions that are
designed to aggregate or summarize data. You will often see these functions (for
example, Sum, Count, and Avg) referred to as aggregate functions.
Expression Description
=Avg([Freight]) Uses the Avg function to display the average of the values
of the Freight control.
=Sum([Sales]) Uses the Sum function to display the sum of the values of
the Sales control.
=Sum([Quantity]*[Pri Uses the Sum function to display the sum of the product of
ce]) the values of the Quantity and Price controls.
Expressions that selectively count, sum, and look up values by using domain
aggregate functions
Sometimes you need to sum or count values selectively. For example, you might
want to count only those values that are within a certain range or that evaluate to
Yes. At other times you might need to look up a value from another table for
display. Access supports a series of functions that can be used for this sort of task.
They are called the domain aggregate functions.
Expression Description
Certain things are fundamental to a database application, among them, the need to
track dates and times. You work with dates and times in Access by using the
Date/Time data type. Access can perform arithmetic calculations on dates; for
example, you can calculate how many days have elapsed since the invoice date to
age your accounts receivable. You can format dates and times in numerous ways,
as shown in the following table.
Expression Description
=Date() Uses the Date function to display the current date in the
form of mm-dd-yy, where mm is the month (1 through 12),
dd is the day (1 through 31), and yy is the last two digits of
the year (1980 through 2099).
=Format(Now(), Uses the Format function to display the week number of the
"ww") year for the current date, where ww represents weeks 1
through 53.
=DateAdd("y", -10, Uses the DateAdd function to display a date that is 10 days
[PromisedDate]) before the value of the PromisedDate control.
The example expressions in the following table use the IIf function to return one of
two possible values. You pass the IIf function three arguments: The first argument is
an expression that must return a True or False value. The second argument is the
value to return if the expression is true, and the third argument is the value to
return if the expression is false.
Expression Description
=IIf([Confirmed] = "Yes", "Order Uses the IIf function to display the message
Confirmed", "Order Not "Order Confirmed" if the value of the
Confirmed") Confirmed control is Yes; otherwise, it displays
the message "Order Not Confirmed."
=IIf(IsNull([Country]), " ", Uses the IIf function to display an empty string
[Country]) if the value of the Country control is null;
otherwise, it displays the value of the Country
control.
=IIf(IsNull([Region]), [City] & " " & Uses the IIf function to display the values of the
[PostalCode], [City] & " " & City and PostalCode controls if the value in the
[Region] & " " & [PostalCode]) Region control is null; otherwise, it displays the
values of the City, Region, and PostalCode
controls.
This section contains examples of expressions that you can use to create a
calculated field in a query or to supply criteria to a query. A calculated field is a
column in a query that results from an expression. For example, you can calculate a
value or format a portion of a date. You use criteria in a query to limit the records
that you work with. For example, you can use the Between operator to supply a
date range for the ShippedDate field in order to limit the query result to orders that
were shipped between those dates.
The example expressions in the following list can be used to create a calculated
field in a query.
Click the query, and then click Design in the Database window.
Click the field cell in the column where you want to create the calculated field.
Type the expression, or click the Build button on the toolbar to create an
expression by using the Expression Builder. You should start the expression with a
name followed by a colon; for example, type ExtendedPrice: to start a calculated
field called ExtendedPrice.
The expressions in the following table use the & and the + operators to combine
text strings, use built-in functions to operate on a text string, or otherwise operate
on text to create a calculated field.
Expression Description
FullName: [FirstName] & " Displays the value of the FirstName and LastName
" & [LastName] fields, separated by a space, in the FullName field.
Address2: [City] & " " & Displays the value of the City, Region, and PostalCode
[Region] & " " & fields, separated by spaces, in the Address2 field.
[PostalCode]
You can use expressions to add, subtract, multiply, and divide the values in two or
more fields or controls. You can also perform arithmetic operations on dates. For
example, if RequiredDate is a Date/Time data type field or control, the expression
=[RequiredDate] - 2 will return a Date/Time value equal to two days before
RequiredDate.
Expression Description
Certain things are fundamental to a database application, among them, the need to
track dates and times. You work with dates and times in Access by using the
Date/Time data type. Access can perform arithmetic calculations on dates; for
example, you can calculate how many days have elapsed since the invoice date to
age your accounts receivable. As the following table shows, you can format dates
and times numerous ways.
Expression Description
MinusThirty: Date( )- 30 Uses the Date function to display the date 30 days
prior to the current date.
Expressions that count, sum, and average values by using SQL aggregate or domain
aggregate functions
Often you need to calculate a sum of the values that are stored in a group of
records. For example, you might need to calculate a group total for the group footer
in a report, or an order subtotal for line items on a form. At other times, you need to
count the number of items rather than to sum them, or you want to calculate the
average value. The expressions in the following table use functions that are
designed to aggregate or summarize data. You will often see these functions (for
example, Sum, Count, and Avg) referred to as aggregate functions.
Sometimes you need to sum or count values selectively. For example, you might
want to count only those values that are within a certain range, or those that
evaluate to Yes. At other times, you need to look up a value from another table so
that you can display it. Access supports a series of functions that can be used for
this sort of task. These functions are called the domain aggregate functions (for
example, DSum, DCount, and DAvg).
To calculate totals, you will often need to create a totals query. For example, to
summarize by group, you need to use a totals query. To enable a totals query from
the query design grid, click Totals on the View menu.
Expression Description
Expressions for working with fields with missing information (fields with null values)
The expressions shown here work with fields with potentially missing information —
those that might have a null value. A null value represents the absence of
information; it does not represent zero, or any value at all. Access supports this idea
of missing information because the concept is vital to the integrity of a database. In
the real world, information is often missing, even if only temporarily (for example,
the as-yet undetermined price for a new product). Therefore, a database that
models a real world entity, such as a business, must be able to record information
as missing. You can use the IsNull function to determine if a field or control contains
a null value, and you can use the Nz function to convert a null value to zero.
Expression Description
Expression Description
Cat: (SELECT [CategoryName] FROM [Categories] Displays the CategoryName, if
WHERE [Products].[CategoryID]=[Categories]. the CategoryID from the
[CategoryID]) Categories table is the same as
the CategoryID from the
Products table.
Expressions used as matching criteria to limit the records you work with
You can use an expression to define the criteria for matching rows in a query.
Access then returns only those rows that match the criteria. In the list that follows,
you will find sample expressions that you can use to define criteria. To define
criteria, you open a query and then click Design, which opens the query design grid.
Then you locate the field for which you want to enter the criteria. Each column in
the query design grid represents a field. Finally, you click in the Criteria cell for that
field and type your criteria.
Click the query, and then click Design in the Database window.
Click in the criteria cell in the column for which you want to enter matching criteria.
Type the criteria expression or click the Build button on the toolbar to create an
expression by using the Expression Builder.
If you want a larger area in which to type an expression, press SHIFT+F2 to display
the Zoom box.
The sample expressions in the Expression column of the following table define the
criteria that match whole or partial text values.
ProductNam Not Like "C*" Uses the Not operator and the * wildcard
e character to display products whose names do
not begin with C.
Access can perform arithmetic calculations on dates; for example, you can use the
OrderDate field to display orders more than 30 days old (see the following table).
You can also use a variety of built-in functions to extract and manipulate portions of
dates or to place a date within calendar periods (for example, to determine what
calendar quarter a date is in). The sample expressions that follow demonstrate the
use of dates and related functions in criteria expressions.
The expressions in the following table work with fields that have potentially missing
information — those that might contain a null value or a zero-length string. A null
value represents the absence of information; it does not represent a zero or any
value at all. Access supports this idea of missing information because the concept is
vital to the integrity of a database. In the real world, information is often missing,
even if only temporarily (for example, the as-yet undetermined price for a new
product). Therefore, a database that models a real world entity, such as a business,
must be able to record information as missing. You can use the IsNull function to
determine if a field or control contains a null value, and you can use the Nz function
to convert a null value to zero.
Expressio
Field n Description
ShipRegi Is Null Displays orders for customers whose ShipRegion field is null
on (missing).
ShipRegi Is Not Null Displays orders for customers whose ShipRegion field
on contains a value.
Fax "" Displays orders for customers who don't have a fax machine,
indicated by a zero-length string value in the Fax field instead
of a null (missing) value.
The Like operator provides a great deal of flexibility when you are trying to match
rows that follow a pattern. That is because Like can be used with special characters
called wildcard characters that let you define patterns for Access to match. For
example, the * (asterisk) wildcard character matches a sequence of characters of
any type, and makes it easy to find all names that begin with a letter. You use the
expression Like "S*" to find all names that begin with the letter S, for example. For
more information, see the article Like operator.
ShipNa Like "S*" Orders shipped to customers whose names start with
me the letter S.
ShipNa Like "*Imports" Orders shipped to customers whose names end with
me Orders shipped to the word "Imports".
customers
ShipNa Like "[A-D]*" Orders shipped to customers whose names start with
me A through D.
ShipNa Like "Maison Orders shipped to the customer with "Maison" as the
me Dewe?" first part of its name and a five-letter second name in
which the first four letters are "Dewe" and the last
letter is unknown.
ShipNa Not Like "A*" Orders shipped to customers whose names do not
me start with the letter A.
Expressions that match rows based on the result of a domain aggregate function
Sometimes you need to sum or count values selectively. For example, you might
want to count only those values that are within a certain range, or that evaluate to
Yes. At other times you might need to look up a value from another table so that
you can display it. Access supports a series of functions called the domain
aggregate functions (for example, DSum, DCount, and DAvg) that can be used for
this sort of task. The sample expressions in the following table use the domain
aggregate functions to perform a calculation on a set of values, and use the result
as the query criteria.
Sometimes a nested query, also called a subquery, can be used to calculate a value
to be used as the criteria. A subquery is expressed by using Structured Query
Language (SQL) — the query language that Access uses. The sample expressions in
the following table match rows based on the results from a subquery.
OrderTotal: > (SELECT AVG([UnitPrice] * Orders with totals that are higher
[UnitPrice] * [Quantity]) FROM [Order
[Quantity] Details]) than the average order value.
Often you need to modify the values in a column in your database. One of the ways
that you can do this is by using an update query. With an update query, you can tell
Access which records to update and how to compute the new values for the fields
that you want to update. When you create an update query to update a field, you
provide the expression that supplies the replacement value. The expressions in the
following table represent example expressions that supply a replacement value.
Use expressions such as the following in the Update To cell in the query design grid
for the field that you want to update.
Structured Query Language, or SQL, is the query language that Access uses. Every
query that you create in query Design view can also be expressed by using SQL. To
see the SQL for any query, click SQL View on the View menu. The following table
shows sample SQL statements that employ an expression.
It is often useful to give a field or control a default value. That way, Access supplies
the default value when a new record with the field is created or when the object
that contains the control is created. The expressions in the following table represent
the sample default values for a field or control.
Click the field name for the field that you want.
Type the expression, or click the Build button to the right of the property box to
create an expression by using the Expression Builder.
If a control is bound to a field in a table, and the field has a default value, the
default value of the control takes precedence.
Quantity 1 1
Region "MT" MT
Region "New York, New York, N.Y. (Note that you must enclose the value in
N.Y." quotation marks if it includes punctuation.)
You can create a validation rule for a field or control by using an expression. Access
then enforces the rule when data is entered into the field or control. To create a
validation rule, you modify the ValidationRule property of the field or control. You
should also consider setting the ValidationText property, which holds the text that
Access displays when the validation rule is violated. If you don't set the
ValidationText property, Access displays a default error message.
The examples in the following table demonstrate the validation rule expressions for
the ValidationRule property and the associated text for the ValidationText property.
Click the field name for the field that you want.
Type the expression, or click the Build button to the right of the property box to
create an expression by using the Expression Builder.
Note Do not precede the expression with the = operator when you create a
validation rule.
In some cases, you might want to carry out an action or series of actions in a macro
only if a particular condition is true. For example, suppose you want an action to run
only when the value of the Counter text box is 10. You use an expression to define
the condition in the Condition column of the macro: [Counter]=10.
Click the macro, and then click Design in the Database window.
If the Condition column is not visible, on the View menu, click Conditions.
DCount("[OrderID]", "Orders") > 35 There are more than 35 entries in the OrderID
field of the Orders table.
DCount("*", "[Order Details]", There are more than three entries in the Order
"[OrderID]=" & Forms![Orders]! Details table for which the OrderID field of the
[OrderID]) > 3 table matches the OrderID field on the Orders
form.
[ShippedDate] Between #2-Feb- The value of the ShippedDate field on the form
2005# And #2-Mar-2005# from which the macro is run is no earlier than
2-Feb-1995 and no later than 2-Mar-1995.
[Country]="UK" And Forms! The value in the Country field on the form from
[SalesTotals]![TotalOrds] > 100 which the macro is run is UK, and the value of
the TotalOrds field on the SalesTotals form is
greater than 100.
[Country] In ("France", "Italy", The value in the Country field on the form from
"Spain") And Len([PostalCode])<>5 which the macro is run is either France, Italy,
or Spain, and the postal code is not 5
characters long.