Anda di halaman 1dari 23

In this article

Introduction

Examples of expressions used in forms and reports

Examples of expressions used in queries and filters

Examples of default value expressions

Examples of field validation rule expressions

Examples of macro condition expressions

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.

In Access, the term expression is synonymous with formula. An expression consists


of a number of possible elements that are used, alone or in combination, to produce
a result. These elements include identifiers (the names of fields, controls, or
properties), operators such as + (plus) or - (minus), functions, constants, and
values. You use an expression to perform a calculation, retrieve the value of a
control, supply criteria to a query, define rules, create calculated controls and
calculated fields, and define a group level for a report.

For more information about how and where to use expressions, see the article
Create an expression.

Examples of expressions used in forms and reports

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.

To enter an expression in a control (for this example, a text box control)

In the Database window, under Objects, click Forms or Reports.

Click the form or report, and then click Design in the Database window.

Click the text box to select it.

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.

Close the property sheet.

Expressions that combine or manipulate text

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

="N/A" Displays N/A.

=[FirstName] & " " & Displays the values of the FirstName and LastName
[LastName] fields, separated by a space.

=Left([ProductName], 1) Uses the Left function to display the first character of


the value of the ProductName control.

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


of the value of the AssetCode control.

=Trim([Address]) Uses the Trim function to display the value of the


Address control, removing any leading or trailing
spaces.

=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.

Expressions for 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 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

="Page " & [Page] Page 1

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


[Pages]

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


Pages"

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


Pages"

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

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

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


12/31/04

Expressions that perform 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, 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

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


controls.

=[RequiredDate]- The difference between the values of the


[ShippedDate] RequiredDate and ShippedDate controls.

=[Price]*1.06 The product of the value of the Price control and 1.06
(adds 6 percent to the Price value).

=[Quantity]*[Price] The product of the values of the Quantity and Price


controls.

=[EmployeeTotal]/ The quotient of the values of the EmployeeTotal and


[CountryTotal] CountryTotal 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. 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.

Expressions that refer to values in 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 OrderSubtotal control on the


Subform].Form![OrderSubtotal] Orders subform on the Orders form.
=Forms![Orders]![Orders The value of the third column in ProductID, a
Subform]! multiple-column list box on the Orders subform
[ProductID].Column(2) on the Orders form. (0 refers to the first column,
1 refers to the second column, and so on.)

=Forms![Orders]![Orders The product of the value of the Price control on


Subform]![Price] * 1.06 the Orders subform on 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 following table lists examples of expressions that you can use in calculated
controls on reports.

Expression Result

=Reports![Invoice]![OrderID] The value of the OrderID control on the


Invoice report.

=Reports![Summary]![Summary The value of the SalesTotal control on the


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

=Parent![OrderID] The value of the OrderID control on the main


or parent report of the current subreport.

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.

=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.

=Sum([Quantity]*[Pri Uses the Sum function to display the sum of the product of
ce]) the values of the Quantity and Price controls.

=[Sales]/Sum([Sales] Displays the percentage of sales, determined by dividing the


)*100 value of the Sales control by the sum of all the values of the
Sales control.

Note If the Format property of the control is set to Percent,


do not include *100 in the expression.

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

=DLookup("[ContactName]", "[Suppliers]", Uses the DLookup function to return


"[SupplierID] = " & Forms("Suppliers") the value of the ContactName field in
("[SupplierID]")) the Suppliers table where the value
of the SupplierID field in the table
matches the value of the SupplierID
control on the Suppliers form.

=DLookup("[ContactName]", "[Suppliers]", Uses the DLookup function to return


"[SupplierID] = " & Forms![New Suppliers]! the value of the ContactName field in
[SupplierID]) the Suppliers table where the value
of the SupplierID field in the table
matches the value of the SupplierID
control on the New Suppliers form.

=DSum("[OrderAmount]", "[Orders]", Uses the DSum function to return the


"[CustomerID] = 'RATTC'") sum total of the values in the
OrderAmount field in the Orders
table where the CustomerID is
RATTC.

=DCount("[Retired]","[Assets]","[Retired]=Y Uses the DCount function to return


es") the number of Yes values in the
Retired field (a Yes/No field) in the
Assets table.

Expressions that manipulate and calculate dates

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.

=DatePart("yyyy", Uses the DatePart function to display the four-digit year of


[OrderDate]) the value of the OrderDate control.

=DateAdd("y", -10, Uses the DateAdd function to display a date that is 10 days
[PromisedDate]) before the value of the PromisedDate control.

=DateDiff("d", Uses the DateDiff function to display the number of days'


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

=[InvoiceDate] + 30 Uses arithmetic operations on dates to calculate the date 30


days after the date in the InvoiceDate field or control.

Conditional expressions that return one of two possible 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 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.

=IIf(IsNull([RequiredDate]) Or Uses the IIf function to display the message


IsNull([ShippedDate]), "Check for "Check for a missing date" if the result of
a missing date", [RequiredDate] - subtracting ShippedDate from RequiredDate is
[ShippedDate]) null; otherwise, it displays the difference
between the values of the RequiredDate and
ShippedDate controls.

< Back to top >

Examples of expressions used in 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 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.

Expressions that create a calculated field (perform calculations on or manipulate


field values)

The example expressions in the following list can be used to create a calculated
field in a query.

To enter a calculated field in query Design view


In the Database window, under Objects, click Queries.

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.

Expressions that manipulate text in a query or filter

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]

ProductInitial: Uses the Left function to display, in the ProductInitial


Left([ProductName], 1) field, the first character of the value in the
ProductName field.

TypeCode: Uses the Right function to display, in the TypeCode


Right([AssetCode], 2) field, the last two characters of the value in the
AssetCode field.

AreaCode: Uses the Mid function to display, in the AreaCode field,


Mid([Phone],2,3) the three characters starting with the second
character of the value in the Phone field.

Expressions that perform arithmetic operations in calculated fields

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

PrimeFreight: [Freight] * 1.1 Displays freight charges plus 10 percent in the


PrimeFreight field.

OrderAmount: [Quantity] * Displays the product of the values in the Quantity


[UnitPrice] and UnitPrice fields in the OrderAmount field.

LeadTime: [RequiredDate] - Displays the difference between the values in the


[ShippedDate] RequiredDate and ShippedDate fields in the
LeadTime field.

TotalStock: [UnitsInStock]+ Displays the sum of the values in the UnitsInStock


[UnitsOnOrder] and UnitsOnOrder fields in the TotalStock field.

FreightPercentage: Displays, in the FreightPercentage field, the


Sum([Freight])/Sum([Subtotal percentage of freight charges in each subtotal, by
]) *100 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 function.)

The Total row in the design grid must be displayed,


and the Total cell for this field must be set to
Expression.

If the Format property of the field is set to Percent,


do not include *100.

Expressions that manipulate and calculate with dates in calculated fields

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

LagTime: DateDiff("d", Uses the DateDiff function to display in the


[OrderDate], [ShippedDate]) LagTime field the number of days between the
order date and ship date.
YearHired: DatePart("yyyy", Uses the DatePart function to display in the
[HireDate]) YearHired field the year each employee was hired.

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

RowCount:Count(*) Uses the Count function to count the number of


records in the query, including records with null
(blank) fields.

FreightPercentage: Displays, in the FreightPercentage field, the


Sum([Freight])/Sum([Subtotal percentage of freight charges in each subtotal by
]) *100 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 function.)

The Total row in the design grid must be displayed,


and the Total cell for this field must be set to
Expression.

If the Format property of the field is set to Percent,


do not include *100.

AverageFreight: Uses the DAvg function to display, in the


DAvg("[Freight]", "[Orders]") AverageDiscount field, the average discount given
on all orders combined in a totals query.

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

CurrentCountry: Uses the IIf and IsNull functions to display an


IIf(IsNull([Country]), " ", [Country]) empty string in the CurrentCountry field if the
Country field is null; otherwise, it displays the
contents of the Country field.

LeadTime: Uses the IIf and IsNull functions to display, in


IIf(IsNull([RequiredDate] - the LeadTime field, the message "Check for a
[ShippedDate]), "Check for a missing date" if the value of either the
missing date", [RequiredDate] - RequiredDate field or the ShippedDate field is
[ShippedDate]) null; otherwise, it displays the difference.

SixMonthSales: Nz([Qtr1Sales]) + Displays, in the SixMonthSales field, the total of


Nz([Qtr2Sales]) the values in the first-quarter and second-
quarter sales fields combined, by first using the
Nz function to convert the null values to zero.

Expression that uses a subquery to create a calculated field

Sometimes a nested query, also called a subquery, can be used to create a


calculated field. A subquery is expressed by using Structured Query Language
(SQL) — the query language that Access uses. The expression in the following table
is one example of a calculated field that results from a subquery.

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.

To enter criteria in the query design grid

In the Database window, under Objects, click Queries.

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.

Note Do not precede the criteria expression with the = operator.

If you want a larger area in which to type an expression, press SHIFT+F2 to display
the Zoom box.

Expressions that match whole or partial text values

The sample expressions in the Expression column of the following table define the
criteria that match whole or partial text values.

Field Expression Description

ShipCity "London" Displays orders shipped to London.

ShipCity "London" Or "Hedge Uses the Or operator to display orders shipped


End" to London or Hedge End.

ShipCountry In("Canada", "UK") Uses the In operator to display orders shipped


to Canada or the UK.
ShipCountry Not "USA" Uses the Not operator to display orders
shipped to countries other than the USA.

ProductNam Not Like "C*" Uses the Not operator and the * wildcard
e character to display products whose names do
not begin with C.

CompanyNa >="N" Displays orders shipped to companies whose


me names start with the letters N through Z.

ProductCode Right([ProductCode], Uses the Right function to display orders with


2)="99" ProductCode values that end in 99.

ShipName Like "S*" Displays orders shipped to customers whose


names start with the letter S.

Expressions that use dates in matching criteria

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.

Field Expression Description

ShippedDa #2/2/2000# Displays orders shipped on


te February 2, 2000.

ShippedDa Date() Displays orders shipped today.


te

RequiredD Between Date( ) And DateAdd("m", Uses the Between...And operator


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

OrderDate < Date( ) - 30 Uses the Date function to display


orders more than 30 days old.

OrderDate Year([OrderDate])=2005 Uses the Year function to display


orders with order dates in 2005.

OrderDate DatePart("q", [OrderDate])=4 Uses the DatePart function to


display orders for the fourth
calendar quarter.

OrderDate DateSerial(Year ([OrderDate]), Uses the DateSerial, Year, and


Month([OrderDate])+1, 1)-1 Month functions to display orders
for the last day of each month.

OrderDate Year([OrderDate])= Year(Now()) Uses the Year and Month


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

ShippedDa Between #1/5/2005# And Uses the Between...And operator


te #1/10/2005# to display orders shipped no
earlier than 5-Jan-2005 and no
later than 10-Jan-2005.

RequiredD Between Date( ) And DateAdd("M", Uses the Between...And operator


ate 3, Date( )) to display orders required
between today's date and three
months from today's date.

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


functions to display employees
who have birthdays this month.

Expressions that match a missing value (null) or a zero-length string

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.

Expressions that use patterns to match records

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.

Field Expression Description

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 "*ar*" Orders shipped to customers whose names include


me the letter sequence "ar".

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.

Field Expression Description

Freight > (DStDev("[Freight]", Uses the DAvg and DStDev functions to


"Orders") + display all orders for which the freight cost
DAvg("[Freight]", "Orders")) rose above the mean plus the standard
deviation for freight cost.

Quantit > DAvg("[Quantity]", Uses the DAvg function to display products


y "[Order Details]") ordered in quantities above the average
order quantity.

Expressions that match based on the results of subqueries

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.

Field Expression Displays

UnitPrice (SELECT [UnitPrice] FROM Products whose price is the same


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

UnitPrice >(SELECT AVG([UnitPrice]) Products that have a unit price


FROM [Products]) above the average.

Salary > ALL (SELECT [Salary] FROM Salary of every sales


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

OrderTotal: > (SELECT AVG([UnitPrice] * Orders with totals that are higher
[UnitPrice] * [Quantity]) FROM [Order
[Quantity] Details]) than the average order value.

Expressions used to update the data in an update query

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.

Field Expression Result

Title "Salesperson" Changes a text value to Salesperson.

ProjectStart #8/10/99# Changes a date value to 10-Aug-99.

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 number.

LineItemTot [UnitPrice] * [Quantity] Calculates the product of UnitPrice and


al Quantity.

Freight [Freight] * 1.5 Increases freight charges by 50 percent.

Sales DSum("[Quantity] * Where the ProductID values in the current


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

ShipPostalC Right([ShipPostalCode], Truncates the leftmost characters, leaving the


ode 5) five rightmost characters.

UnitPrice Nz([UnitPrice]) Changes a null (Null: A value you can enter in


a field or use in expressions or queries to
indicate missing or unknown data. In Visual
Basic, the Null keyword indicates a Null value.
Some fields, such as primary key fields, can't
contain Null.) value to a zero (0) in the
UnitPrice field.

Expressions used in 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 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] FROM Displays the values in the FirstName and


[Employees] WHERE LastName fields for employees whose last
[LastName]="Davolio" name is Davolio.

SELECT [ProductID],[ProductName] Displays the values in the ProductID and


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

SELECT Avg([ExtendedPrice]) AS Calculates the average extended price for


[Average Extended Price] FROM [Order orders for which the value in the
Details Extended] WHERE ExtendedPrice field is more than 1000, and
[ExtendedPrice]>1000; displays it in a field named Average
Extended Price.

SELECT [CategoryID], In a field named CountOfProductID, displays


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

< Back to top >

Examples of default value expressions

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.

To enter a default value for a field in a table

In the Database window, under Objects, click Tables.


Click the table, and then click Design in the Database window.

Click the field name for the field that you want.

Click the Default Value property box.

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.

Field Expression Default field value

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.)

Fax "" A zero-length string to indicate that by default this field


should be empty instead of a null value

Order Date( ) Today's date


Date

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

< Back to top >

Examples of field validation rule expressions

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.

To enter a validation rule for a field in a table

In the Database window, under Objects, click Tables.


Click the table, and then click Design in the Database window.

Click the field name for the field that you want.

Click the Validation Rule property box.

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.

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.

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

>= #1/1/2005# And < Date must be in 2005.


#1/1/2006#

< Back to top >

Examples of macro condition 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.

To enter a condition for a macro action

In the Database window, under Objects, click Macros.

Click the macro, and then click Design in the Database window.

Click the Condition cell for the macro action.

If the Condition column is not visible, on the View menu, click Conditions.

Type a conditional expression.


Close the macro.

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.

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.

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.

Forms![Products]![UnitsInStock] < 5 The value of the UnitsInStock field on the


Products form is less than 5.

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.

[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.

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.
Note To force Access to temporarily ignore an action, enter False as a condition.
Forcing Access to temporarily ignore an action can be helpful when you are trying to
find problems in a macro

Anda mungkin juga menyukai