Vous êtes sur la page 1sur 13

MS ACCESS 2007 - Examples of expressions

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.

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 ="N/A" =[FirstName] & " " & [LastName] =Left([ProductName], 1) Result Displays N/A. Displays the values of the FirstName and LastName fields, separated by a space. Uses the Left function to display the first character of the value of the ProductName control.

=Right([AssetCode], 2) =Trim([Address])

Uses the Right function to display the last 2 characters of the value of the AssetCode control. 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 and PostalCode controls if the value in the [PostalCode], [City] & " " & [Region] Region control is null; otherwise, it displays the values of the City, Region, and PostalCode & " " & [PostalCode]) controls, separated by spaces. =[City] & (" " + [Region]) & " " & [PostalCode] Uses the + operator and null propagation to display the 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 =[Page] ="Page " & [Page] ="Page " & [Page] & " of " & [Pages] =[Page] & " of " & [Pages] & " Pages" =[Page] & "/" & [Pages] & " Pages" =[Country] & " - " & [Page] =Format([Page], "000") ="Printed on: " & Date() 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 =[Subtotal]+[Freight] =[RequiredDate]-[ShippedDate] =[Price]*1.06 =[Quantity]*[Price] =[EmployeeTotal]/[CountryTotal] Result The sum of the values of the Subtotal and Freight controls. The difference between the values of the RequiredDate and ShippedDate controls. The product of the value of the Price control and 1.06 (adds 6 percent to the Price value). The product of the values of the Quantity and Price controls. The quotient of the values of the EmployeeTotal and CountryTotal controls. Result 1 Page 1 Page 1 of 3 1 of 3 Pages 1/3 Pages UK - 1 001 Printed on: 12/31/04

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 =Forms![Orders]![OrderID] =Forms![Orders]![Orders Subform].Form![OrderSubtotal] =Forms![Orders]![Orders Subform]![ProductID].Column(2) Result The value of the OrderID control on the Orders form. The value of the OrderSubtotal control on the Orders subform on the Orders form. The value of the third column in ProductID, a multiple-column list box on the Orders subform on the Orders form. (0 refers to the first column, 1 refers to the second column, and so on.)

=Forms![Orders]![Orders Subform]![Price] * The product of the value of the Price control on the Orders subform on the Orders form 1.06 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 =Reports![Invoice]![OrderID] =Reports![Summary]![Summary Subreport]![SalesTotal] =Parent![OrderID] Result The value of the OrderID control on the Invoice report. The value of the SalesTotal control on the Summary subreport on the Summary report. 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 =Avg([Freight]) =Count([OrderID]) =Sum([Sales]) Description Uses the Avg function to display the average of the values of the Freight control. Uses the Count function to display the number of records in the OrderID control. Uses the Sum function to display the sum of the values of the Sales control.

=Sum([Quantity]*[Price]) Uses the Sum function to display the sum of the product of the values of the Quantity and Price controls. =[Sales]/Sum([Sales])*100Displays the percentage of sales, determined by dividing the 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]", "[SupplierID] = " & Uses the DLookup function to return the value of the ContactName field in the Suppliers table where the value of the SupplierID field in the table Forms("Suppliers")("[SupplierID]")) matches the value of the SupplierID control on the Suppliers form. =DLookup("[ContactName]", "[Suppliers]", "[SupplierID] = " & Uses the DLookup function to return the value of the ContactName field in the Suppliers table where the value of the SupplierID field in the table Forms![New Suppliers]![SupplierID]) matches the value of the SupplierID control on the New Suppliers form. =DSum("[OrderAmount]", "[Orders]", "[CustomerID] = 'RATTC'") =DCount("[Retired]","[Assets]","[Retired]=Yes") 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 =Date() =Format(Now(), "ww") =DatePart("yyyy", [OrderDate]) =DateAdd("y", -10, [PromisedDate]) Description 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). Uses the Format function to display the week number of the year for the current date, where ww represents weeks 1 through 53. Uses the DatePart function to display the four-digit year of the value of the OrderDate control. Uses the DateAdd function to display a date that is 10 days before the value of the PromisedDate control. Uses the DSum function to return the sum total of the values in the OrderAmount field in the Orders table where the CustomerID is RATTC. Uses the DCount function to return the number of Yes values in the Retired field (a Yes/No field) in the Assets table.

=DateDiff("d", [OrderDate], Uses the DateDiff function to display the number of days' difference between the values of the [ShippedDate]) 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.

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 Confirmed", "Order Uses the IIf function to display the message "Order Confirmed" if the value of the Confirmed control is Yes; otherwise, it displays the message "Order Not Not Confirmed") Confirmed."

=IIf(IsNull([Country]), " ", [Country]) =IIf(IsNull([Region]), [City] & " " & [PostalCode], [City] & " " & [Region] & " " & [PostalCode])

Uses the IIf function to display an empty string if the value of the Country control is null; otherwise, it displays the value of the Country control. Uses the IIf function to 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 controls.

=IIf(IsNull([RequiredDate]) Or IsNull([ShippedDate]), Uses the IIf function to display the message "Check for a missing date" if the "Check for a missing date", [RequiredDate] result of subtracting ShippedDate from RequiredDate is null; otherwise, it displays the difference between the values of the RequiredDate and ShippedDate [ShippedDate]) controls.

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] & " " & [LastName] Displays the value of the FirstName and LastName fields, separated by a space, in the FullName field.

Address2: [City] & " " & [Region] & " " & Displays the value of the City, Region, and PostalCode fields, separated by spaces, in the [PostalCode] Address2 field. ProductInitial: Left([ProductName], 1) TypeCode: Right([AssetCode], 2) AreaCode: Mid([Phone],2,3) Uses the Left function to display, in the ProductInitial field, the first character of the value in the ProductName field. Uses the Right function to display, in the TypeCode field, the last two characters of the value in the AssetCode field. Uses the Mid function to display, in the AreaCode field, 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 PrimeFreight: [Freight] * 1.1

Description Displays freight charges plus 10 percent in the PrimeFreight field.

OrderAmount: [Quantity] * [UnitPrice] Displays the product of the values in the Quantity and UnitPrice fields in the OrderAmount field. LeadTime: [RequiredDate] [ShippedDate] TotalStock: [UnitsInStock]+[UnitsOnOrder] FreightPercentage: Sum([Freight])/Sum([Subtotal]) *100 Displays the difference between the values in the RequiredDate and ShippedDate fields in the LeadTime field. Displays the sum of the values in the UnitsInStock and UnitsOnOrder fields in the TotalStock field. Displays, in the FreightPercentage field, 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 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 LagTime: DateDiff("d", [OrderDate], [ShippedDate]) YearHired: DatePart("yyyy",[HireDate]) MinusThirty: Date( )- 30 Description Uses the DateDiff function to display in the LagTime field the number of days between the order date and ship date. Uses the DatePart function to display in the YearHired field the year each employee was hired. 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 RowCount:Count(*) Description Uses the Count function to count the number of records in the query, including records with null (blank) fields.

FreightPercentage: Sum([Freight])/Sum([Subtotal]) *100

Displays, in the FreightPercentage field, 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 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: DAvg("[Freight]", "[Orders]")

Uses the DAvg function to display, in the 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: IIf(IsNull([Country]), " ", [Country]) Uses the IIf and IsNull functions to display an empty string in the CurrentCountry field if the Country field is null; otherwise, it displays the contents of the Country field. LeadTime: IIf(IsNull([RequiredDate] - [ShippedDate]), Uses the IIf and IsNull functions to display, in the LeadTime field, the message "Check for a missing date", [RequiredDate] "Check for a missing date" if the value of either the RequiredDate field or the [ShippedDate]) ShippedDate field is null; otherwise, it displays the difference. SixMonthSales: Nz([Qtr1Sales]) + Nz([Qtr2Sales]) Displays, in the SixMonthSales field, the total of 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 Cat: (SELECT [CategoryName] FROM [Categories] WHERE [Products].[CategoryID]=[Categories].[CategoryID]) 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. Description Displays the CategoryName, if the CategoryID from the Categories table is the same as the CategoryID from the Products table.

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 ShipCity ShipCity ShipCountry ShipCountry Expression "London" "London" Or "Hedge End" In("Canada", "UK") Not "USA" Description Displays orders shipped to London. Uses the Or operator to display orders shipped to London or Hedge End. Uses the In operator to display orders shipped to Canada or the UK. Uses the Not operator to display orders shipped to countries other than the USA. Uses the Not operator and the * wildcard character to display products whose names do not begin with C. Displays orders shipped to companies whose names start with the letters N through Z.

ProductName Not Like "C*" CompanyName>="N" ProductCode ShipName

Right([ProductCode], 2)="99" Uses the Right function to display orders with ProductCode values that end in 99. 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 Displays orders shipped on February 2, 2000. Displays orders shipped today. Uses the Between...And operator and the DateAdd and Date functions to display orders required between today's date and three months from today's date. Uses the Date function to display orders more than 30 days old. Uses the Year function to display orders with order dates in 2005.

ShippedDate #2/2/2000# ShippedDate Date() RequiredDateBetween Date( ) And DateAdd("m", 3, Date( ))

OrderDate OrderDate

< Date( ) - 30 Year([OrderDate])=2005

OrderDate DatePart("q", [OrderDate])=4

Uses the DatePart function to display orders for the fourth calendar quarter.
Uses the DateSerial, Year, and Month functions to display orders for the last day of each month. Uses the Year and Month functions and the And operator to display orders for the current year and month. Uses the Between...And operator to display orders shipped no earlier than 5-Jan-2005 and no later than 10-Jan-2005. Uses the Between...And operator to display orders required between

OrderDate OrderDate

DateSerial(Year ([OrderDate]), Month([OrderDate])+1, 1)-1 Year([OrderDate])= Year(Now()) And Month([OrderDate])= Month(Now())

ShippedDate Between #1/5/2005# And #1/10/2005# RequiredDateBetween Date( ) And DateAdd("M", 3, Date( ))

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. Field Expression Description Displays orders for customers whose ShipRegion field is null (missing).

ShipRegionIs Null

ShipRegionIs Not Null Displays orders for customers whose 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 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 Orders shipped to customers whose names start with the letter S. Orders shipped to customers whose names end with the word "Imports". Orders shipped to customers whose names start with A through D. Orders shipped to customers whose names include the letter sequence "ar". Orders shipped to the customer with "Maison" as the 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. Orders shipped to customers whose names do not start with the letter A.

ShipNameLike "S*" ShipNameLike "*Imports" Orders shipped to customers ShipNameLike "[A-D]*" ShipNameLike "*ar*" ShipNameLike "Maison Dewe?" ShipNameNot Like "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 Uses the DAvg and DStDev functions to display all orders for which the freight cost

Freight > (DStDev("[Freight]", "Orders") +

DAvg("[Freight]", "Orders")) Quantity> DAvg("[Quantity]", "[Order Details]")

rose above the mean plus the standard deviation for freight cost. Uses the DAvg function to display products 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 UnitPrice UnitPrice Salary Expression (SELECT [UnitPrice] FROM [Products] WHERE [ProductName] = "Aniseed Syrup") >(SELECT AVG([UnitPrice]) FROM [Products]) > ALL (SELECT [Salary] FROM [Employees] WHERE ([Title] LIKE "*Manager*") OR ([Title] LIKE "*Vice President*")) > (SELECT AVG([UnitPrice] * [Quantity]) FROM [Order Details]) Displays Products whose price is the same as the price of Aniseed Syrup. Products that have a unit price above the average. Salary of every sales representative whose salary is higher than that of all employees with "Manager" or "Vice President" in their titles. Orders with totals that are higher than the average order value.

OrderTotal: [UnitPrice] * [Quantity]

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 Title ProjectStart Retired PartNumber Expression "Salesperson" #8/10/99# Yes "PN" & [PartNumber] Result Changes a text value to Salesperson. Changes a date value to 10-Aug-99. Changes a No value in a Yes/No field to Yes. Adds PN to the beginning of each specified part number. Calculates the product of UnitPrice and Quantity. Increases freight charges by 50 percent.

LineItemTotal [UnitPrice] * [Quantity] Freight Sales [Freight] * 1.5

DSum("[Quantity] * Where the ProductID values in the current table match the ProductID values in the [UnitPrice]", Order Details table, updates sales totals based on the product of Quantity and UnitPrice. "Order Details", "[ProductID]=" & [ProductID]) Truncates the leftmost characters, leaving the five rightmost characters. 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 a Null value.) value to a zero (0) in the UnitPrice field.

ShipPostalCodeRight([ShipPostalCode], 5) UnitPrice Nz([UnitPrice])

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 [Employees] WHERE Displays the values in the FirstName and LastName fields for employees [LastName]="Davolio" whose last name is Davolio. SELECT [ProductID],[ProductName] FROM [Products] WHERE Displays the values in the ProductID and ProductName fields in the Products table for records in which the CategoryID value matches the [CategoryID]=Forms![New Products]![CategoryID]; CategoryID value specified in an open New Products form. SELECT Avg([ExtendedPrice]) AS [Average Extended Price] FROM [Order Details Extended] WHERE [ExtendedPrice]>1000; SELECT [CategoryID], Count([ProductID]) AS [CountOfProductID] FROM [Products] GROUP BY [CategoryID] HAVING Count([ProductID])>10; Calculates the average extended price for orders for which the value in the ExtendedPrice field is more than 1000, and displays it in a field named Average Extended Price. In a field named CountOfProductID, displays the total number of products for categories with more than 10 products.

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 Builder. to the right of the property box to create an expression by using the Expression

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 Quantity Region Region Fax Expression 1 "MT" Default field value 1 MT

"New York, N.Y." New York, N.Y. (Note that you must enclose the value in quotation marks if it includes punctuation.) "" A zero-length string to indicate that by default this field should be empty instead of a null value Today's date The date 60 days forward from today

Order Date Date( ) DueDate Date() + 60

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 Builder. to the right of the property box to create an expression by using the Expression

Note Do not precede the expression with the = operator when you create a validation rule. ValidationRule property <> 0 0 Or > 100 Like "K???" < #1/1/2005# >= #1/1/2005# And < #1/1/2006# ValidationText property Please enter a nonzero value. Value must be either 0 or more than 100. Value must be four characters beginning with the letter K. Enter a date prior to 1/1/2005. Date must be in 2005.

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 [City]="Paris" DCount("[OrderID]", "Orders") > 35 DCount("*", "[Order Details]", "[OrderID]=" & Forms![Orders]![OrderID]) > 3 To carry out the action if Paris is the City value in the field on the form from which the macro was run. There are more than 35 entries in the OrderID field of the Orders table. There are more than three entries in the Order Details table for which the OrderID field of the table matches the OrderID field on the Orders form.

[ShippedDate] Between #2-Feb-2005# And #2-Mar- The value of the ShippedDate field on the form from which the macro is run is no

2005# Forms![Products]![UnitsInStock] < 5 IsNull([FirstName])

earlier than 2-Feb-1995 and no later than 2-Mar-1995. The value of the UnitsInStock field on the Products form is less than 5. 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![SalesTotals]![TotalOrds] The value in the Country field on the form from which the macro is run is UK, and > 100 the value of the TotalOrds field on the SalesTotals form is greater than 100. [Country] In ("France", "Italy", "Spain") And Len([PostalCode])<>5 MsgBox("Confirm changes?",1)=1 The value in the Country field on the form from which the macro is run is either France, Italy, or Spain, and the postal code is not 5 characters long. 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.

Vous aimerez peut-être aussi