You are on page 1of 13

Build an expression Page 1 of 13

Build an expression
To build an expression,selectthe objectorproperty w here you w antto use an expression,and then press Ctrl+F2 –
this opens the Expression Builder,a toolw ith lots ofpartially-builtexpressions to save you tim e,and built-in help to
save you trouble.You can use expressions to do allkinds ofthings w ith yourdata – forexam ple,determ ining how
m any days have passed since an orderw as shipped,orcom bining a FirstN am e and a LastN am e into a FullN am e.If
you’re an Excelperson,think ofexpressions as the Access version ofform ulas.

Som e expressions don’tw ork the sam e w ay in Access apps and in desktop databases.Everything in this article
applies to both apps and databases,exceptw here otherw ise noted.Form ore inform ation aboutAccess apps,see
the article Create an Access app.

Form ore inform ation aboutexpressions – w hen to use them ,how to build them – read on.

In this article
O verview ofexpressions
Using the Expression Builder
Calculate values forcontrols in form s and reports
Use expressions as query criteria
Create a calculated field in a query
Create a calculated field in a table
Add a validation rule to a table field orrecord
Add a validation rule to a control
Setdefaultvalues fora table field
Setdefaultvalues forcontrols
Controlw hich m acro actions are run
Group and sortdata in reports

O verview ofexpressions
Rem em berequations from m ath class? Letx2+z = (2y-1)/7, solve for x,thatkind ofstuff? M aybe you also rem em ber
thatequations are the foundation ofm odern engineering – ifyou w antto build som ething solid,you use equations
to answ erspecific questions like “how thick do the bolts holding up the stairw ellneed to be?” That’s w hat
expressions are about– butinstead ofx,y and z,think [Unit Price],[Discount] and [Quantity].And expressions don’t
justdo m ath – you can do allkinds ofthings w ith textdata too.

Things you can do w ith expressions

The follow ing are justa few com m on exam ples outofthe m any things you can do w ith expressions.

Calculate age

Putfirstand lastnam es together

M ark a changed record w ith the date and tim e thatitchanged

Specify a pattern data inputm ustm atch

http://support.office.microsoft.com/client/Build-an-expression-20c385ee-accd-4306-bc7b-... 2/25/2015
Build an expression Page 2 of 13

Crop characters offeitherside ofa line oftext

Technicaloverview

N O TE   This section isn’trequired reading to be able build expressions,butitm ay give you a betterunderstanding
ofhow expressions w ork,and ituses technicalterm s thatm ay help you find related inform ation on m ore technical
sites,such as M SD N .

An expression is a com bination ofsom e orallofthe follow ing:built-in oruser-defined functions,identifiers,


operators,and constants.An expression evaluates to a single value.

Forexam ple,the follow ing expression contains allfourofthese elem ents:

=Sum([Purchase Price])*0.08

In this exam ple,Sum() is a built-in function,[Purchase Price] is an identifier,* is a m athem aticaloperator,and 0.08
is a constant.This expression can be used in a textbox in a form footerorreportfooterto calculate sales tax fora
group ofitem s.

Expressions can be m uch m ore com plex orm uch sim plerthan this exam ple.Forexam ple,this Boolean expression
(an expression thatevaluates to eitherTrue orFalse)consists ofonly an operatorand a constant:

>0

This expression returns True w hen itis com pared to a num berthatis greaterthan 0,and returns False w hen itis
com pared to a num berthatis less than orequalto 0.You m ightuse this expression in the Validation Rule property
ofa controlortable field to ensure thatonly values greaterthan 0 are entered.

In Access,expressions are used in m any places to perform calculations,m anipulate characters,ortestdata.Tables,


queries,form s,reports,and m acros allhave properties thatcan acceptan expression.Forexam ple,you can use
expressions in the Control Source and Default Value properties fora control.In addition,w hen you w rite M icrosoft
VisualBasic forApplications (VBA)code foran eventprocedure orfora m odule,you often use expressions that
resem ble those thatyou use in an Access object,such as a table orquery.

Top ofPage

Using the Expression Builder

http://support.office.microsoft.com/client/Build-an-expression-20c385ee-accd-4306-bc7b-... 2/25/2015
Build an expression Page 3 of 13

The Expression Builderhas the follow ing benefits:

You can easily look up and insertfunctions,operators,constants,and identifiers (forexam ple,the nam es of
fields,tables,form s,and queries),saving tim e and reducing errors.

The Expression Builderlim its the available expression parts based on the contextofthe expression.

You can choose from a variety ofready-m ade expressions,such as page num bers,the currentdate,orthe
currentdate and tim e.

IntelliSense is available in the Expression Builder– so you don’thave to rem em berallthe argum ents an
expression needs.

H elp is atyourfingertips in the Expression Builder– justclick the links thatappearin the Q uick Info tool.

Start the Expression Builder :

The keyboard shortcutforlaunching the Expression Builderis Ctrl+ F2.The firsttim e you use this shortcutit
launches the Choose Builder dialog box – justdouble-click Expression Builder in the dialog box to proceed.

See m ore detailed inform ation abouthow to use the Expression Builder.

The nesting lim itforexpressions in an app orin a w eb database is 65

Expressions nested m ore than 65 levels deep w on’tw ork in the brow ser,so you shouldn’tuse any such expressions
in an Access app ora w eb database.You w on’tgetany errorm essages – the expression justw on’tw ork.

IM PO RTAN T   The use ofthe &,AND,and OR operators can create additionalnesting levels on the serverthataren't
reflected in the Access client.Forexam ple the expression "a" & "b" & "c" is notnested in the Expression Builder,but
in SharePointitbecom es concatenate.D b("a",concatenate.D b("b","c")).This translation creates one levelofnesting.
Using m any consecutive &,AND,orOR operators in a single expression can cause you to exceed the server's
nesting lim itof65,atw hich pointthe expression w on’tw ork in the brow ser.

Top ofPage

Calculate values forcontrols in form s and reports


W hen you use an expression as the data source fora control,you create a calculated control.Forexam ple,suppose
thatyou have a reportthatdisplays m ultiple inventory records,and you w antto create a totalin the reportfooter
thatsum s allthe line item s on the report.

http://support.office.microsoft.com/client/Build-an-expression-20c385ee-accd-4306-bc7b-... 2/25/2015
Build an expression Page 4 of 13

To calculate the total,place a textbox controlin the reportfooter,and then setthe ControlSource property ofthe
textbox to the follow ing expression:

=Sum([ table_field ])

In this case,table_field is the nam e ofthe field thatcontains yoursubtotalvalues.Thatfield can com e from a table
ora query.The Sum function calculates the totalforallthe values oftable_field.

The follow ing procedure show s how to enteran expression in a textbox control.

Enteran expression in a textbox control

1. In the N avigation Pane,right-click the form thatyou w antto change,and then click Layout View orDesign
View on the shortcutm enu.

2. Selectthe controlinto w hich you w antto enteran expression.

3. Ifthe Property Sheetis notalready displayed,press F4 to display it.

4. To m anually create an expression,on the Data tab in the property sheet,click the ControlSource property of
the textbox,and then type = follow ed by the restofyourexpression.Forexam ple,to calculate the subtotal
show n above,type =Sum([table_field]),m aking sure thatyou substitute the nam e ofyourfield for
table_field.

5. To create an expression by using the Expression Builder,click the Build button in the property box.

Aftercom pleting yourexpression,the property sheetw illlook like this:

Top ofPage

Use expressions as query criteria


You use criteria in a query to narrow dow n query results.You enterthe criteria as an expression,and Access returns
only those row s thatm atch the expression.To see an extensive setofexam ples,see the article Exam ples ofquery
criteria.

Forexam ple,suppose thatyou w antto see allthe orders w hose shipped date occurred in the firstthree m onths of
the year2010.To enterthe criteria,you type the follow ing expression in the Criteria cellforthe D ate/Tim e colum n
in yourquery.This exam ple uses a D ate/Tim e colum n called ShippedDate.To define a date range,enteryour
criteria in this m anner:

Between #1/1/2010# And #3/31/2010#

The ShippedDate colum n w illresem ble the follow ing.

http://support.office.microsoft.com/client/Build-an-expression-20c385ee-accd-4306-bc7b-... 2/25/2015
Build an expression Page 5 of 13

Foreach record in the O rders table,ifthe value in the ShippedD ate colum n falls in the date range thatyou specify,
the record is included in the query output.N ote thatin the expression,you enclose the dates w ith pound signs (#).
Access treats a value enclosed in pound signs as a D ate/Tim e data type.Treating those values as date/tim e data
enables you to perform calculations on those values,such as subtracting one date from another.

Entercriteria in the query design grid

1. In the N avigation Pane,right-click the query thatyou w antto change,and then click Design View on the
shortcutm enu.

2. Click in the Criteria cellin the colum n forw hich you w antto enteryourcriteria.

3. To m anually create yourexpression,type yourcriteria expression.

N O TE   D o notprecede the criteria expression w ith the = operator.

4. To create yourexpression by using the Expression Builder,on the ribbon,click Design,and then in the Query
Setup group,click Builder .

TIP   Ifyou w anta largerarea in w hich to editthe expression,place the cursorin the Criteria celland then
press SH IFT+F2 to display the Zoom box:

Top ofPage

Create a calculated field in a query


Suppose you’re designing a query,and you w antto display the results ofa calculation using otherfields in the
query.To create the calculated field,you enteran expression in a blank cellin the Field row in yourquery.For
exam ple,ifyou have a query thatcontains a Quantity field and a Unit Price field,you can m ultiply the tw o to create
a calculated field forExtended Price by entering the follow ing expression in the Field row ofthe query:

http://support.office.microsoft.com/client/Build-an-expression-20c385ee-accd-4306-bc7b-... 2/25/2015
Build an expression Page 6 of 13

Extended Price: [Quantity] * [Unit Price]

Prefacing the expression w ith the textExtended Price: nam es the new colum n Extended Price.This nam e is often
called an alias.Ifyou do notsupply an alias,Access w illcreate one,such as Expr1.

W hen you run the query,Access perform s the calculation on each row ,as show n in the follow ing illustration:

Create a calculated field in query D esign view

1. In the N avigation Pane,right-click the query thatyou w antto change,and then click Design View on the
shortcutm enu.

2. Click the Field cellin the colum n w here you w antto create the calculated field.

3. To m anually create yourexpression,type yourexpression.

N O TE   D o notprecede the criteria expression w ith the = operator;instead,begin the expression w ith a
descriptive labelfollow ed by a colon.Forexam ple,type Extended Price: to provide the labelforan
expression thatcreates a calculated field called Extended Price.Then,enterthe criteria foryourexpression
afterthe colon.

4. To create yourexpression by using the Expression Builder,on the ribbon,click Design,and then in the Query
Setup group,click Builder.

Top ofPage

Create a calculated field in a table


In Access,you can create a calculated field in a table.This elim inates the need fora separate query to do
calculations.Forexam ple,ifyou have a table thatlists the quantity,price and tax rate foreach item in an order,you
could add a calculated field thatshow s the totalprice,like so:

[Q uantity]*([UnitPrice]+([UnitPrice]*[TaxRate]))

N O TE

http://support.office.microsoft.com/client/Build-an-expression-20c385ee-accd-4306-bc7b-... 2/25/2015
Build an expression Page 7 of 13

The calculation cannotinclude fields from othertables orqueries.

The results ofthe calculation are read-only.

To create the calculated field:

1. O pen the table by double-clicking itin the N avigation Pane.

2. Scrollhorizontally to the rightm ostcolum n in the table,and click the Click to Add colum n heading.

3. In the listthatappears,click Calculated Field,and then click the data type thatyou w antforthe result.

Access displays the Expression Builder.

4. Enterthe calculation thatyou w antforthis field,forexam ple:

[Quantity] * [Unit Price]

N O TE   Fora calculated field,you don’tstartthe expression w ith an equalsign (=).

5. Click OK.

Access adds the calculated field,and then highlights the field headerso thatyou can type a field nam e.

6. Type a nam e forthe calculated field,and then press EN TER.

Top ofPage

Add a validation rule to a table field orrecord


Expressions are very usefulforvalidating data as itis entered into the database – keeping bad data out.In tables,
there are tw o kinds ofvalidation rules:Field validation rules (w hich preventusers from entering bad data in a single
field),and record validation rules (w hich preventusers from creating records thatdon'tm eetthe validation rule).You
use expressions forboth kinds ofvalidation rules.

Forexam ple,suppose thatyou have a table nam ed Inventory w ith a field thatis nam ed Units O n H and,and you
w antto seta rule thatforces users to entera value greaterthan orequalto zero.In otherw ords,inventory can never
be a negative num ber.You can do this by using the follow ing expression as a field validation rule in the Units O n
H and field:

>=0

Entera validation rule

Use the follow ing procedure to entereithera field validation rule ora record validation rule:

1. In the N avigation Pane,double-click the table thatyou w antto change.

Access opens the table in D atasheetview .

2. Fora field validation rule,selectthe field thatyou w antto change.

3. O n the ribbon,click Fields,then in the Field Validation group click Validation,and then click Field
Validation Rule orRecord Validation Rule.

Access displays the Expression Builder.

http://support.office.microsoft.com/client/Build-an-expression-20c385ee-accd-4306-bc7b-... 2/25/2015
Build an expression Page 8 of 13

4. Begin typing the criteria thatyou w ant.Forexam ple,fora field validation rule thatrequires thatallvalues are
greaterthan orequalto zero,type the follow ing:

>=0

N O TE   D o notprecede the expression w ith an equalsign (=).

Validation rule expressions are Boolean,w hich m eans thatthey are eitherTrue orFalse forany given inputvalue.A
validation rule m ustbe True forthe value orAccess doesn’tsave the inputand displays a validation m essage
indicating the error.In this exam ple,ifyou entera value forthe Units O n H and field thatis less than zero,the
validation rule is False,and Access does notacceptthe value.Ifyou haven'tentered a validation m essage as
described in the follow ing section,Access displays its ow n m essage to indicate thatthe value you entered is
prohibited by the validation rule forthe field.

Enter a validation m essage

To m ake yourdatabase easierto use,you can entercustom validation m essages.These replace the generic
m essages thatAccess displays w hen data does notm atch a validation rule.You can use custom validation m essage
to provide specific inform ation thathelps the userenterthe correctdata,forexam ple,"The Units O n H and value
cannotbe a negative num ber." Use the follow ing procedure to create a validation m essage:

1. In the N avigation Pane,double-click the table thatyou w antto change.

Access opens the table in D atasheetview .

2. Fora field validation m essage,selectthe field to w hich you added the validation rule.

3. O n the ribbon,click Fields,then in the Field Validation group click Validation,and then click Field
Validation Message orRecord Validation Message.

4. In the Enter Validation Message dialog box,type the m essage thatyou w antto appearw hen data does not
m atch the validation rule,and then click OK.

Top ofPage

Add a validation rule to a control


N O TE   Validation rules are notavailable forcontrols in Access apps orw eb databases.Use field orrecord validation
rules instead,as described in the preceding section.

In addition to table fields and records,controls also have a Validation Rule property thatcan acceptan expression.
Forexam ple,suppose thatyou use a form to enterthe date range fora report,and you w antto ensure thatthe
beginning date isn'tearlierthan 1/1/2010.You can setthe Validation Rule and ValidationText properties forthe
textbox w here you enterthe beginning date to the follow ing:

Property Setting

Validation Rule >=#1/1/2010#

Validation Text You cannotentera date earlierthan 1/1/2010.

http://support.office.microsoft.com/client/Build-an-expression-20c385ee-accd-4306-bc7b-... 2/25/2015
Build an expression Page 9 of 13

Ifyou try to entera date earlierthan 1/1/2010,a m essage appears,and displays the textin the ValidationText
property.Ifno textw as entered in the ValidationText property box,Access displays a generic m essage.Afteryou
click OK,Access returns you to the textbox.

TIP   Setting a validation rule fora table field enforces the rule throughoutthe database,w hereverthatfield is
m odified.Alternatively,setting a validation rule fora controlon a form enforces the rule only w hen thatform is
being used.Setting validation rules separately fortable fields and forcontrols on form s can be usefulifyou w antto
establish differentvalidation rules fordifferentusers.

Entera validation rule fora control

1. In the N avigation Pane,right-click the form orreportthatyou w antto change,and then click Design View or
Layout View on the shortcutm enu.

2. Right-click the controlthatyou w antto change,and then click Properties on the shortcutm enu.

Access displays the property sheetforthe control.

3. Click the All tab,and then click the Validation Rule property box.

4. Type the expression,orclick the Build button in the property box to create an expression by using the
Expression Builder.

N O TE   D o notprecede the expression w ith the = operator.

5. To custom ize the textthatappears ifa userenters data thatdoes notm atch the validation rule,type the text
thatyou w antin the Validation Text property.

Top ofPage

Setdefaultvalues fora table field


You can use an expression to specify a defaultvalue fora field in a table – a value thatAccess uses fornew records
unless anothervalue is provided.Forexam ple,suppose thatyou w antto autom atically insertthe date and tim e into
a field called O rderDate w heneversom eone adds a new record.To do this,you m ightuse the follow ing expression:

Now()

Specify a defaultvalue fora field in a table

1. In the N avigation Pane,double-click the table thatyou w antto change.

Access opens the table in D atasheetview .

2. Selectthe field thatyou w antto change.

3. O n the ribbon,click Fields,and in the Properties group,click Default Value.

Access displays the Expression Builderdialog box.

4. Type yourexpression in the box,m aking sure to begin the expression w ith an equalsign (=).

N O TE   Ifyou bind a controlto a table field and both the controland table field have defaultvalues,the control's
defaultvalue takes precedence overthe table field.

Top ofPage

http://support.office.microsoft.com/client/Build-an-expression-20c385ee-accd-4306-bc7b-... 2/25/2015
Build an expression Page 10 of 13

Setdefaultvalues forcontrols
Anothercom m on place to use an expression is in the Default Value property ofa control.The Default Value
property ofa controlis like the Default Value property ofa field in a table.Forexam ple,to use the currentdate as
the defaultvalue fora textbox,you can use the follow ing expression:

Date()

This expression uses the Date function to return the currentdate,butnotthe tim e.Ifyou bind the textbox to a
table field,and the field has a defaultvalue,the control's defaultvalue takes precedence overthe table field.Itoften
m akes bettersense to setthe Default Value property forthe field in the table.Thatw ay,ifyou base severalcontrols
fordifferentform s on the sam e table field,the sam e defaultvalue w illapply to each control,helping ensure
consistentdata entry on each form .

Entera defaultvalue fora control

1. In the N avigation Pane,right-click the form orreportthatyou w antto change,and then click Design View or
Layout View on the shortcutm enu.

2. Selectthe controlthatyou w antto change.

3. Ifthe property sheetis notalready displayed,press F4 to display it.

4. Click the All tab on the property sheet,and then click the Default Value property box.

5. Type the expression,orclick the Build button in the property box to create an expression by using the
Expression Builder.

Top ofPage

Controlw hich m acro actions are run


In som e cases,you m ightw antto carry outan action orseries ofactions in a m acro only ifa particularcondition is
true.Forexam ple,suppose thatyou w anta m acro action to run only w hen the value in a textbox is greaterthan or
equalto 10.To setthis rule,you use an expression in an If block in the m acro to define the condition in the m acro.

In this exam ple,assum e the textbox is nam ed "Item s." Yourexpression thatsets the condition is [Items]>=10.

Enteran expression in an Ifblock in a m acro

1. In the N avigation Pane,right-click the m acro thatyou w antto change,and then click Design View on the
shortcutm enu.

2. Click the If block thatyou w antto m odify,oradd an If block from the Action Catalog pane.

http://support.office.microsoft.com/client/Build-an-expression-20c385ee-accd-4306-bc7b-... 2/25/2015
Build an expression Page 11 of 13

3. Click the top line ofthe If block.

4. Type yourconditionalexpression in the box,orclick the Build button nextto the expression box to launch
the Expression Builder.

N O TE   The expression you type m ustbe Boolean,m eaning itis eitherTrue orFalse.The m acro actions w ithin the If
block run only w hen the condition is True.

Top ofPage

Group and sortdata in reports


You use the Group, Sort, and Total pane to define grouping levels and sorting orders forthe data in a report.M ost
typically,you group orsorton a field thatyou selectfrom a list.H ow ever,ifyou w antto group orsorton a
calculated value,you can enteran expression instead.

Grouping is the process ofcom bining colum ns thatcontain duplicate values.Forexam ple,suppose thatyour
database contains sales inform ation foroffices in differentcities,and thatone ofthe reports in yourdatabase is
nam ed "Sales by City." The query thatprovides the data forthatreportgroups the data by yourcity values.This type
ofgrouping can m ake yourinform ation easierto read and understand.

In contrast,sorting is the process ofim posing a sortorderon the row s (the records)in yourquery results.For
exam ple,you can sortrecords by theirprim ary key values (oranothersetofvalues in anotherfield)in either
ascending ordescending order,oryou can sortthe records by one orm ore characters in a specified order,such as
alphabeticalorder.

Add grouping and sorting to a report

1. In the N avigation Pane,right-click the reportthatyou w antto change,and then click Layout View orDesign
View on the shortcutm enu.

2. O n the ribbon,click Design,and in the Grouping & Totals group,click Group & Sort.

The Group, Sort, and Total pane appears below the report.

3. To add a grouping levelto the report,click Add a group.

4. To add a sortorderto the report,click Add a sort.

A new group levelorsortorderappears in the pane,plus a listofthe fields thatprovide data forthe report.
This figure show s a typicalnew group level(grouping on Category)and sortorder(sorting on M anufacturer),
plus a listthatcontains the available fields forgrouping and sorting:

http://support.office.microsoft.com/client/Build-an-expression-20c385ee-accd-4306-bc7b-... 2/25/2015
Build an expression Page 12 of 13

5. Underthe listofavailable fields,click expression to startthe Expression Builder.

6. Enterthe expression you w antto use in the expression box (the upperbox)ofthe Expression Builder.M ake
sure thatyou begin the expression w ith the equal(=)operator.

Add an expression to an existing group orsort

1. In the N avigation Pane,right-click the reportthatyou w antto change,and then click Layout View orDesign
View on the shortcutm enu.

2. Click the group levelorsortorderthatyou w antto change.

3. Click the dow n arrow nextto Group on (forgrouping levels)orSort by (forsortorders).

A listthatcontains the available fields appears.

4. Atthe bottom ofthe listthatcontains the fields,click expression to startthe Expression Builder.

5. Type yourexpression in the expression box (the upperbox)ofthe Expression Builder.M ake sure thatyou
begin yourexpression w ith the equal(=)operator.

Top ofPage

Applies To:Access 2013

W as this inform ation helpful? YES NO

H ow can w e im prove it? 255 characters rem aining

http://support.office.microsoft.com/client/Build-an-expression-20c385ee-accd-4306-bc7b-... 2/25/2015
Build an expression Page 13 of 13

To protectyourprivacy,please do notinclude contactinform ation in yourfeedback.Review ourprivacy policy.

Send

http://support.office.microsoft.com/client/Build-an-expression-20c385ee-accd-4306-bc7b-... 2/25/2015

You might also like