Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 92

Forms and reports

The tables in this section provide examples of expressions that calculate a value in
a control located on a form or report. To create a calculated control, you enter an
expression in the ControlSource property of the control, instead of in a table field
or query.

Note You can also use expressions in a form or report when you Highlight data
with conditional formatting.

Text operations
The expressions in the following table use the & (ampersand) and the + (plus)
operators to combine text strings, built-in functions to manipulate a text string, or
otherwise operate on text to create a calculated control.
Expression Result

="N/A" Displays N/A.

=[FirstName] & " " & Displays the values that


[LastName] reside in table fields called
FirstName and LastName.
In this example,
the & operator is used to
combine the FirstName
field, a space character
(enclosed in quotation
marks), and the LastName
field.

=Left([ProductName], 1) Uses the Left function to


Expression Result

display the first character


of the value of a field or
control called
ProductName.

=Right([AssetCode], 2) Uses the Right function to


display the last 2 characters
of the value in a field or
control called AssetCode.

=Trim([Address]) Uses the Trim function to


display the value of the
Address control, removing
any leading or trailing
Expression Result

spaces.

=IIf(IsNull([Region]), Uses the IIf function to


[City] & " " & display the values of the
[PostalCode], [City] & " "
City and PostalCode
& [Region] & " " &
[PostalCode]) controls if the value in the
Region control is null;
otherwise, it displays the
values of the City, Region,
and PostalCode controls,
separated by spaces.

=[City] & (" " + [Region]) Uses the + operator and


& " " & [PostalCode] null propagation to display
Expression Result

the values of the City and


PostalCode controls if the
value in the Region field or
control is null; otherwise, it
displays the values of the
City, Region, and
PostalCode fields or
controls, separated by
spaces.

Null propagation means


that if any component of
an expression is null, the
entire expression is also
null. The + operator
Expression Result

supports null propagation;


the & operator does not.

Top of Page

Headers and footers


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 do not appear on the property sheet for the form or
report. Typically, you use these properties by placing a text box in the header or
footer section of the form or report, and then using an expression, such as the
ones shown in the following table.
For more information about using headers and footers in forms and reports, see
the article Insert page numbers into a form or report.

Expression Result

=[Page] 1

="Page " & [Page] Page 1

="Page " & [Page] & " of " & Page 1 of 3


[Pages]

=[Page] & " of " & [Pages] & " 1 of 3 Pages


Pages"

=[Page] & "/" & [Pages] & " Pages" 1/3 Pages
Expression Result

=[Country/region] & " - " & [Page] UK - 1

=Format([Page], "000") 001

="Printed on: " & Date() Printed on:


12/31/17

Top of Page

Arithmetic operations
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, suppose you have a Date/Time table field
named RequiredDate. In the field, or in a control bound to the field, the
expression =[RequiredDate] - 2 returns a date/time value equal to two days
before the current values in the RequiredDate field.

Expression Result

=[Subtotal]+[Freight] The sum of the


values of the
Subtotal and
Freight fields or
controls.

=[RequiredDate]-[ShippedDate] The interval


Expression Result

between the date


values of the
RequiredDate and
ShippedDate
fields or controls.

=[Price]*1.06 The product of


the value of the
Price field or
control and 1.06
(adds 6 percent to
the Price value).

=[Quantity]*[Price] The product of


Expression Result

the values of the


Quantity and
Price fields or
controls.

=[EmployeeTotal]/ The quotient of


[CountryRegionTotal] the values of the
EmployeeTotal
and
CountryRegionTot
al fields or
controls.
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 — this is known as Null propagation. If any records in one of
the controls that you use in the expression might have a null value, you can avoid
Null propagation by converting the null value to zero by using the Nz function —
for example, =Nz([Subtotal])+Nz([Freight]).

Top of Page

Values in other controls


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

=Forms![Orders]![OrderID] The value of the


OrderID control on
the Orders form.

=Forms![Orders]![Orders The value of the


Subform].Form![OrderSubtotal] OrderSubtotal control
on the subform
named Orders
Subform on the
Orders form.

=Forms![Orders]![Orders The value of the third


Subform]![ProductID].Column(2) column in ProductID,
a multiple-column list
Expression Result

box on the subform


named Orders
Subform on the
Orders form. (Note
that 0 refers to the
first column, 1 refers
to the second column,
and so on.)

=Forms![Orders]![Orders The product of the


Subform]![Price] * 1.06 value of the Price
control on the
subform named
Orders Subform on
Expression Result

the Orders form and


1.06 (adds 6 percent
to the value of the
Price control).

=Parent![OrderID] The value of the


OrderID control on
the main or parent
form of the current
subform.

The expressions in the following table show some ways to use calculated controls
on reports. The expressions reference the Report Property.
Expression Result

=Report![Invoice]![OrderID] The value of a control


called "OrderID" in a
report called "Invoice."

=Report![Summary]![Summary The value of the


Subreport]![SalesTotal] SalesTotal control on
the subreport named
Summary Subreport on
the Summary report.

=Parent![OrderID] The value of the


OrderID control on the
main or parent report
of the current
Expression Result

subreport.

Top of Page

Count, sum, and average values


You can use a type of function called an aggregate function to calculate values for
one or more fields or controls. For example, you can calculate a group total for the
group footer in a report, or an order subtotal for line items on a form. You can also
count the number of items in one or more fields or calculate an average value.

The expressions in the following table show some of the ways to use functions
such as Avg, Count, and Sum.
Expression Description

=Avg([Freight]) Uses the Avg function to


display the average of the
values of a table field or
control named "Freight."

=Count([OrderID]) Uses the Count function to


display the number of records
in the OrderID control.

=Sum([Sales]) Uses the Sum function to


display the sum of the values
of the Sales control.
Expression Description

=Sum([Quantity]*[Price]) Uses the Sum function to


display the sum of the product
of the values of the Quantity
and the Price controls.

=[Sales]/Sum([Sales])*100 Displays the percentage of


sales, determined by dividing
the value of the Sales control
by the sum of all the values of
the Sales control.

If you set the Format property


of the control to Percent, do
not include *100 in the
Expression Description

expression.

For more information about using aggregate functions and totaling the values in
field and columns, see the articles Sum data by using a query, Count data by using
a query, Display column totals in a datasheet using a Totals row, and Display
column totals in a datasheet.

Top of Page

SQL aggregate functions


You use a type of function called an SQL or domain aggregate function when you
need to sum or count values selectively. A "domain" consists of one or more fields
in one or more tables, or one or more controls on one or more forms or reports.
For example, you can match the values in a table field with the values in a control
on a form.

Expression Description

=DLookup("[ContactName]", Uses the


"[Suppliers]", "[SupplierID] = " & DLookup
Forms("Suppliers")("[SupplierID]"))
function to
return the
value of
the
ContactNa
me field in
the
Suppliers
table
where the
Expression Description

value of
the
SupplierID
field in the
table
matches
the value
of the
SupplierID
control on
the
Suppliers
form.
Expression Description

=DLookup("[ContactName]", Uses the


"[Suppliers]", "[SupplierID] = " & DLookup
Forms![New Suppliers]![SupplierID])
function to
return the
value of
the
ContactNa
me field in
the
Suppliers
table
where the
value of
the
Expression Description

SupplierID
field in the
table
matches
the value
of the
SupplierID
control on
the New
Suppliers
form.

=DSum("[OrderAmount]", "[Orders]", Uses the


"[CustomerID] = 'RATTC'") DSum
Expression Description

function to
return the
sum total
of the
values in
the
OrderAmo
unt field in
the Orders
table
where the
CustomerI
D is RATTC.
Expression Description

=DCount("[Retired]","[Assets]","[Retire Uses the


d]=Yes") DCount
function to
return the
number of
Yes values
in the
Retired
field (a
Yes/No
field) in the
Assets
table.
Top of Page

Date operations
Tracking dates and times is a fundamental database activity. 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
Expression Description

year (1980 through 2099).

=Format(Now(), Uses the Format function to display


"ww") the week number of the year for the
current date, where ww represents
weeks 1 through 53.

=DatePart("yyyy", Uses the DatePart function to display


[OrderDate]) the four-digit year of the value of the
OrderDate control.

=DateAdd("y", -10, Uses the DateAdd function to display


[PromisedDate]) a date that is 10 days before the value
Expression Description

of the PromisedDate control.

=DateDiff("d", Uses the DateDiff function to display


[OrderDate], the number of days' difference
[ShippedDate])
between the values of the OrderDate
and ShippedDate controls.

=[InvoiceDate] + 30 Uses arithmetic operations on dates


to calculate the date 30 days after the
date in the InvoiceDate field or
control.

Top of Page
Conditions of only two values
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 Falsevalue. 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


Confirmed", "Order Not (Immediate If)
Confirmed")
function to display
the message "Order
Confirmed" if the
value of the
Confirmed control
Expression Description

is Yes; otherwise, it
displays the
message "Order
Not Confirmed."

=IIf(IsNull([Country/region]), " Uses the IIf and


", [Country]) IsNull functions to
display an empty
string if the value of
the Country/region
control is null;
otherwise, it displays
the value of the
Country/region
Expression Description

control.

=IIf(IsNull([Region]), [City] & Uses the IIf and


" " & [PostalCode], [City] & " " IsNull functions to
& [Region] & " " & [PostalCode])
display the values of
the City and
PostalCode controls
if the value in the
Region control is
null; otherwise, it
displays the values of
the City, Region, and
PostalCode fields or
Expression Description

controls.

=IIf(IsNull([RequiredDate]) Or Uses the IIf and


IsNull([ShippedDate]), "Check IsNull functions to
for a missing date",
display the message
[RequiredDate] - [ShippedDate])
"Check for a missing
date" if the result of
subtracting
ShippedDate from
RequiredDate is null;
otherwise, it displays
the interval between
the date values of
the RequiredDate
Expression Description

and ShippedDate
controls.

Top of Page

Queries and filters


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, combine text values such as first and last names, 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 Betweenoperator to supply a starting and ending date and limit the
results of your query to orders that were shipped between those dates.

The following provide examples of expressions for use in queries.

Text operations
The expressions in the following table use the & and + 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] & " Creates a field called


" & [LastName] FullName that displays the
values in the FirstName and
Expression Description

LastName fields, separated


by a space.

Address2: [City] & " " & Creates a field called


[Region] & " " & Address2 that displays the
[PostalCode]
values in the City, Region,
and PostalCode fields,
separated by spaces.

ProductInitial: Creates a field called


Left([ProductName], 1) ProductInitial, and then uses
the Left function to display,
in the ProductInitial field,
the first character of the
Expression Description

value in the ProductName


field.

TypeCode: Creates a field called


Right([AssetCode], 2) TypeCode, and then uses
the Right function to display
the last two characters of
the values in the AssetCode
field.

AreaCode: Mid([Phone],2,3) Creates a field called


AreaCode, and then uses
the Mid function to display
the three characters starting
Expression Description

with the second character of


the value in the Phone field.

ExtendedPrice: CCur([Order Names the calculated field


Details].[Unit ExtendedPrice, and uses the
Price]*[Quantity]*(1-
[Discount])/100)*100 CCur function to calculate
the line item totals with an
applied discount.

Top of Page

Arithmetic operations
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, suppose you have a Date/Time field called RequiredDate. The
expression =[RequiredDate] - 2 returns a Date/Time value equal to two days
before the value in the RequiredDate field.

Expression Description

PrimeFreight: [Freight] * 1.1 Creates a field called


PrimeFreight, and then
displays freight charges
plus 10 percent in the
field.

OrderAmount: [Quantity] * Creates a field called


[UnitPrice] OrderAmount, and
Expression Description

then displays the


product of the values in
the Quantity and
UnitPrice fields.

LeadTime: [RequiredDate] - Creates a field called


[ShippedDate] LeadTime, and then
displays the difference
between the values in
the RequiredDate and
ShippedDate fields.

TotalStock: [UnitsInStock]+ Creates a field called


[UnitsOnOrder] TotalStock, and then
Expression Description

displays the sum of the


values in the
UnitsInStock and
UnitsOnOrder fields.

FreightPercentage: Creates a field called


Sum([Freight])/Sum([Subtotal]) FreightPercentage, and
*100
then displays the
percentage of freight
charges in each
subtotal. This
expression uses the
Sum function to total
the values in the
Expression Description

Freight field, and then


divides those totals by
the sum of the values
in the Subtotal field.

To use this expression,


you must convert your
select query into a
Totals query because
you need to use
the Total row in the
design grid, and you
must set the Total cell
for this field
Expression Description

to Expression.

For more information


about creating a Totals
query, see the
article Sum data by
using a query.

If you set
the Format property of
the field to Percent, do
not include *100.

For more information about using aggregate functions and totaling the values in
field and columns, see the articles Sum data by using a query, Count data by using
a query, Display column totals in a datasheet using a Totals row, and Display
column totals in a datasheet.

Top of Page

Date operations
Nearly all databases store and track dates and times. You work with dates and
times in Access by setting the date and time fields in your tables to 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.

Expression Description

LagTime: DateDiff("d", Creates a field called


[OrderDate], [ShippedDate]) LagTime, and then uses
Expression Description

the DateDiff function to


display the number of
days between the order
date and ship date.

YearHired: DatePart("yyyy", Creates a field called


[HireDate]) YearHired, and then uses
the DatePart function to
display the year each
employee was hired.

MinusThirty: Date( )- 30 Creates a field called


MinusThirty, and then
uses the Date function
Expression Description

to display the date 30


days prior to the current
date.

Top of Page

SQL aggregate functions


The expressions in the following table use SQL (Structured Query Language)
functions that aggregate or summarize data. You often see these functions (for
example, Sum, Count, and Avg) referred to as aggregate functions.

In addition to aggregate functions, Access also provides "domain" aggregate


functions that you use to sum or count values selectively. For example, you can
count only the values within a certain range or look up a value from another table.
The set of domain aggregate functions includes the DSum Function, the DCount
Function, and the DAvg Function.

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

RowCount: Count(*) Creates a field called


RowCount, and then
uses the Count
function to count the
number of records in
the query, including
records with null
Expression Description

(blank) fields.

FreightPercentage: Creates a field called


Sum([Freight])/Sum([Subtotal]) FreightPercentage, and
*100
then calculates the
percentage of freight
charges in each
subtotal by dividing the
sum of the values in
the Freight field by the
sum of the values in
the Subtotal field. (This
example uses the Sum
Expression Description

function.)

You must use this


expression with a
Totals query. If you set
the Format property of
the field to Percent, do
not include *100.

For more information


about creating a Totals
query, see the
article Sum data by
using a query.
Expression Description

AverageFreight: Creates a field called


DAvg("[Freight]", "[Orders]") AverageFreight, and
then uses the DAvg
function to calculate
the average freight on
all orders combined in
a Totals query.

Top of Page

Fields with missing data


The expressions shown here work with fields with potentially missing information,
such as those containing null (unknown or undefined) values. You frequently
encounter null values, such as an unknown price for a new product or a value that
a coworker forgot to add to an order. The ability to find and process null values
can be a critical part of database operations, and the expressions in the following
table demonstrate some common ways to deal with null values.

Expression Description

CurrentCountryRegion: Creates a field called


IIf(IsNull([CountryRegion]), CurrentCountryRegion,
" ", [CountryRegion])
and then uses the IIf and
IsNull functions to
display an empty string
in that field when the
CountryRegion field
contains a null value;
otherwise, it displays the
contents of the
Expression Description

CountryRegion field.

LeadTime: Creates a field called


IIf(IsNull([RequiredDate] - LeadTime, and then uses
[ShippedDate]), "Check for a
the IIf and IsNull
missing date", [RequiredDate]
- [ShippedDate]) functions to display the
message "Check for a
missing date" if the value
in either the
RequiredDate field or the
ShippedDate field is null;
otherwise, it displays the
date difference.
Expression Description

SixMonthSales: Creates a field called


Nz([Qtr1Sales]) + SixMonthSales, and then
Nz([Qtr2Sales])
displays the total of the
values in the Qtr1Sales
and Qtr2Sales fields by
first using the Nz
function to convert any
null values to zero.

Top of Page

Calculated fields with subqueries


You can use a nested query, also called a subquery, to create a calculated field. The
expression in the following table is one example of a calculated field that results
from a subquery.

Expression Description

Cat: (SELECT [CategoryName] FROM Creates a


[Categories] WHERE [Products]. field called
[CategoryID]=[Categories].[CategoryID])
Cat, and
then
displays the
CategoryN
ame, if the
CategoryID
from the
Categories
table is the
Expression Description

same as the
CategoryID
from the
Products
table.

Top of Page

Match text values


The sample expressions in this table demonstrate criteria that match whole or
partial text values.
Field Expression Description

ShipCity "London" Displays orders


shipped to
London.

ShipCity "London" Or "Hedge Uses


End" the Or operator
to display orders
shipped to
London or Hedge
End.

ShipCountryRegio In("Canada", "UK") Uses


n the In operator
Field Expression Description

to display orders
shipped to
Canada or the UK.

ShipCountryRegio Not "USA" Uses


n the Not operator
to display orders
shipped to
countries/regions
other than USA.

ProductName Not Like "C*" Uses


the Not operator
and
Field Expression Description

the * wildcard
character to
display products
whose names do
not begin with C.

CompanyName >="N" Displays orders


shipped to
companies whose
names start with
the
letters N through
Z.
Field Expression Description

ProductCode Right([ProductCode] Uses the Right


, 2)="99" function to display
orders with
ProductCode
values that end
in 99.

ShipName Like "S*" Displays orders


shipped to
customers whose
names start with
the letter S.

Top of Page
Match date criteria
The expressions in the following table demonstrate the use of dates and related
functions in criteria expressions. For more information about entering and using
date values, see the article Format a date and time field.

Field Expression Description

Shipped #2/2/2017# Displays orders


Date shipped on February
2, 2017.

Shipped Date() Displays orders


Date shipped today.

Required Between Date( ) And Uses


Field Expression Description

Date DateAdd("m", 3, the Between...And


Date( )) operator and the
DateAdd and Date
functions to display
orders required
between today's date
and three months
from today's date.

OrderDat < Date( ) - 30 Uses the Date


e function to display
orders more than 30
days old.
Field Expression Description

OrderDat Year([OrderDate])=2017 Uses the Year function


e to display orders with
order dates in 2017.

OrderDat DatePart("q", Uses the DatePart


e [OrderDate])=4 function to display
orders for the fourth
calendar quarter.

OrderDat DateSerial(Year Uses the DateSerial,


e ([OrderDate]), Year, and Month
Month([OrderDate])+1,
functions to display
1)-1
orders for the last day
Field Expression Description

of each month.

OrderDat Year([OrderDate])= Uses the Year and


e Year(Now()) And Month functions and
Month([OrderDate])=
the And operator to
Month(Now())
display orders for the
current year and
month.

Shipped Between #1/5/2017# And Uses


Date #1/10/2017# the Between...And
operator to display
orders shipped no
earlier than 5-Jan-
Field Expression Description

2017 and no later


than 10-Jan-2017.

Required Between Date( ) And Uses


Date DateAdd("M", 3, the Between...And
Date( ))
operator to display
orders required
between today's date
and three months
from today's date.

BirthDate Month([BirthDate])=Mon Uses the Month and


th(Date()) Date functions to
display employees
Field Expression Description

who have birthdays


this month.

Top of Page

Find missing data


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.

Field Expression Description

ShipRegio Is Null Displays orders for customers whose


n ShipRegion field is null (missing).

ShipRegio Is Not Displays orders for customers whose


n Null ShipRegion field 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
Field Expression Description

instead of a null (missing) value.

Top of Page

Match record patterns with Like


The Like operator provides a great deal of flexibility when you are trying to match
rows that follow a pattern, because you can use Like with wildcard characters and
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. For example, you use the expression Like
"S*" to find all names that begin with the letter S. For more information, see the
article Like Operator.
Field Expression Description

ShipNam Like "S*" Finds all records in the ShipName


e field that start with the letter S.

ShipNam Like Finds all records in the ShipName


e "*Imports" field that end with the word
"Imports".

ShipNam Like "[A- Finds all records in the ShipName


e D]*" field that begin with the letters A, B,
C, or D.

ShipNam Like Finds all records in the ShipName


e "*ar*" field that include the letter sequence
Field Expression Description

"ar".

ShipNam Like "Maison Finds all records in the ShipName


e Dewe?" field that include "Maison" in the first
part of the value and a five-letter
string in which the first four letters are
"Dewe" and the last letter is unknown.

ShipNam Not Like Finds all records in the ShipName


e "A*" field that do not start with the letter
A.

Top of Page
Match rows with SQL aggregates
You use an SQL or domain aggregate function when you need to sum, count, or
average values selectively. For example, you might want to count only those values
that fall 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. 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.

FIELD EXPRESSION DESCRIPTION

Freight > (DStDev("[Freight]", Uses the DStDev and


"Orders") + DAvg functions to
DAvg("[Freight]",
"Orders")) display all orders for
which the freight cost
rose above the mean
FIELD EXPRESSION DESCRIPTION

plus the standard


deviation for freight
cost.

Quantity > DAvg("[Quantity]", Uses the DAvg function


"[Order Details]") to display products
ordered in quantities
above the average
order quantity.

Top of Page

Match fields with subqueries


You use a subquery, also called a nested query, to calculate a value for use as a
criterion. The sample expressions in the following table match rows based on the
results returned by a subquery.

Field Expression Displays

UnitPrice (SELECT [UnitPrice] Products whose


FROM [Products] WHERE price is the same as
[ProductName] =
the price of Aniseed
"Aniseed Syrup")
Syrup.

UnitPrice >(SELECT Products that have a


AVG([UnitPrice]) FROM unit price above the
[Products])
average.

Salary > ALL (SELECT Salary of every sales


Field Expression Displays

[Salary] FROM representative whose


[Employees] WHERE salary is higher than
([Title] LIKE
"*Manager*") OR that of all employees
([Title] LIKE "*Vice with "Manager" or
President*")) "Vice President" in
their titles.

OrderTotal: > (SELECT Orders with totals


[UnitPrice] * AVG([UnitPrice] * that are higher than
[Quantity]) FROM
[Quantity] [Order Details]) the average order
value.

Top of Page
Update queries
You use an update query to modify the data in one or more existing fields in a
database. For example, you can replace values or delete them entirely. This table
demonstrates some ways to use expressions in update queries. You use these
expressions in the Update To row in the query design grid for the field that you
want to update.

For more information about creating update queries, see the article Create and run
an update query.

Field Expression Result

Title "Salesperson" Changes a text


value to
Salesperson.
Field Expression Result

ProjectStart #8/10/17# Changes a


date value to
10-Aug-17.

Retired Yes Changes a No


value in a
Yes/No field to
Yes.

PartNumber "PN" & [PartNumber] Adds PN to


the beginning
of each
specified part
Field Expression Result

number.

LineItemTotal [UnitPrice] * Calculates the


[Quantity] product of
UnitPrice and
Quantity.

Freight [Freight] * 1.5 Increases


freight charges
by 50 percent.

Sales DSum("[Quantity] * Where the


[UnitPrice]", "Order ProductID
Details",
Field Expression Result

"[ProductID]=" & values in the


[ProductID]) current table
match the
ProductID
values in the
Order Details
table, updates
sales totals
based on the
product of
Quantity and
UnitPrice.

ShipPostalCod Right([ShipPostalCode], Truncates the


Field Expression Result

e 5) leftmost
characters,
leaving the
five rightmost
characters.

UnitPrice Nz([UnitPrice]) Changes a null


(undefined or
unknown)
value to a zero
(0) in the
UnitPrice field.

Top of Page
SQL statements
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 statement for any query, click SQL View on the View menu. The
following table shows sample SQL statements that employ an expression.

SQL statement that uses an expression Result

SELECT [FirstName],[LastName] Displays the values in the


FROM [Employees] WHERE FirstName and LastName
[LastName]="Danseglio";
fields for employees
whose last name is
Danseglio.

SELECT [ProductID], Displays the values in the


[ProductName] FROM [Products]
SQL statement that uses an expression Result

WHERE [CategoryID]=Forms![New ProductID and


Products]![CategoryID]; ProductName fields in
the Products table for
records in which the
CategoryID value
matches the CategoryID
value specified in an
open New Products form.

SELECT Avg([ExtendedPrice]) Calculates the average


AS [Average Extended Price] extended price for orders
FROM [Order Details Extended]
WHERE [ExtendedPrice]>1000; for which the value in the
ExtendedPrice field is
more than 1000, and
SQL statement that uses an expression Result

displays it in a field
named Average
Extended Price.

SELECT [CategoryID], In a field named


Count([ProductID]) AS CountOfProductID,
[CountOfProductID] FROM
displays the total number
[Products] GROUP BY
[CategoryID] HAVING of products for
Count([ProductID])>10; categories with more
than 10 products.

Top of Page
Table expressions
The two most common ways to use expressions in tables are to assign a default
value and to create a validation rule.

Field default values


When you design a database, you might want to assign a default value to a field or
control. Access then supplies the default value when a new record containing the
field is created or when an object that contains the control is created. The
expressions in the following table represent the sample default values for a field or
control. 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.
Field Expression Default field value

Quantity 1 1

Region "MT" MT

Region "New York, New York, N.Y. (Note that you must
N.Y." enclose the value in quotation marks if
it includes punctuation.)

Fax "" A zero-length string to indicate that, by


default, this field should be empty
instead of containing a null value

Order Date( ) Today's date


Field Expression Default field value

Date

DueDate Date() + The date 60 days forward from today


60

Top of Page

Field validation rules


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.

ValidationRule property ValidationText property

<> 0 Please enter a nonzero value.

0 Or > 100 Value must be either 0 or more than


100.

Like "K???" Value must be four characters,


beginning with the letter K.
ValidationRule property ValidationText property

< #1/1/2017# Enter a date prior to 1/1/2017.

>= #1/1/2017# And < Date must occur in 2017.


#1/1/2008#

For more information about validating data, see the article Create a validation rule
to validate data in a field.

Top of Page

Macro expressions
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

As with the ValidationRule property, the Condition column expression is a


conditional expression. It must resolve to either a True or False value. The action
takes place only when the condition is true.

Tip To force Access to temporarily ignore an action, type False as a condition.


This can be helpful when you are trying to find problems in a macro.

Use this expression to carry out the action If

[City]="Paris" Paris is the City


value in the field on
the form from which
the macro was run.
Use this expression to carry out the action If

DCount("[OrderID]", "Orders") > There are more than


35 35 entries in the
OrderID field of the
Orders table.

DCount("*", "[Order Details]", There are more than


"[OrderID]=" & Forms![Orders]! three entries in the
[OrderID]) > 3
Order Details table
for which the
OrderID field of the
table matches the
OrderID field on the
Orders form.
Use this expression to carry out the action If

[ShippedDate] Between #2-Feb- The value of the


2017# And #2-Mar-2017# ShippedDate field
on the form from
which the macro is
run is no earlier than
2-Feb-2017 and no
later than 2-Mar-
2017.

Forms![Products]![UnitsInStock] The value of the


< 5 UnitsInStock field on
the Products form is
less than 5.
Use this expression to carry out the action If

IsNull([FirstName]) The FirstName value


on the form from
which the macro is
run is null (has no
value). This
expression is
equivalent to
[FirstName] Is Null.

[CountryRegion]="UK" And Forms! The value in the


[SalesTotals]![TotalOrds] > 100 CountryRegion field
on the form from
which the macro is
run is UK, and the
Use this expression to carry out the action If

value of the
TotalOrds field on
the SalesTotals form
is greater than 100.

[CountryRegion] In ("France", The value in the


"Italy", "Spain") And CountryRegion field
Len([PostalCode])<>5
on the form from
which the macro is
run is either France,
Italy, or Spain, and
the postal code is
not 5 characters
Use this expression to carry out the action If

long.

MsgBox("Confirm changes?",1)=1 You click OK in a


dialog box that the
MsgBox function
displays. If you
click Cancel in the
dialog box, Access
ignores the action.

Top of Page

You might also like