Chapter 16

Express Yourself with Formulas

In This Chapter

arrow Developing an expression

arrow Performing complex calculations

arrow Calculating text fields

arrow Using Expression Builder

Efficient database design requires that tables contain only necessary fields. Too many fields can cause a table to load slowly — you won’t notice the difference with a few hundred records, but you certainly will with a few hundred thousand. So what fields are often added unnecessarily to a table’s design? The short answer: fields that could be generated from calculations on data stored in other fields.

For example, suppose you have a Commitment table with a DonationCommitment field and a Donation table with a DonationAmount field. You may be tempted to add an AmountOwed field to your Donation table that stores the result of subtracting DonationAmount from DonationCommitment. This is unnecessary because Access can perform these calculations on the fly — in what’s called a calculated field.

A calculated field takes information from another field or fields in the database and performs some arithmetic to come up with new information. Access calls the arithmetic formula used to perform the calculation an expression. In fact, a calculated field can take data from more than one field and combine information to create an entirely new field if that’s what you want. You can perform simple arithmetic (such as addition and multiplication) or use Access’s built-in functions, such as DSum and DAvg (average), for more difficult calculations.

In this chapter, you build all kinds of calculations into your queries. From simple sums to complex equations, the information you need is right here.

tip Although the examples in this chapter deal with calculated fields in queries, the same concept applies to calculated fields in forms and reports.

A Simple Calculation

The first step in creating a calculated field in a query is to include the tables that contain the fields you need for your calculation. In the preceding example, the commitment amount was in the Commitment table; the donation amount was in the Donation table. Therefore, a query to calculate donation amount from commitment amount must include information from both the Commitment and Donation tables. Access can’t pull the numbers out of thin air for the calculation; you must make sure the fields that contain the numbers you need are present in your query.

Access uses a special syntax for building calculated fields. Here’s how to create a calculated field:

  1. Click an empty column in the Field row of the query grid.

    The good old cursor will blink in the row. Access puts the results of the calculation in the same grid position as the calculation itself, so if the calculation sits in the third column of your query grid, the calculation’s result will be in the third column, too.

  2. Enter a name for your calculation followed by a colon (:).

    Access will refer to this calculation from now on by whatever name you enter before the colon (known as an alias). Keep it short and sweet (say, AmountOwed or Tax) so it’s easier to refer to later on. If you don’t name your calculation, Access will put the generic Expr (followed by a number) as its name. It has to be called something, so why not Expr1 or Expr2, right?

  3. Enter your calculation, substituting field names for the actual numbers where necessary.

    My AmountOwed calculated field would look something like (well, exactly like) the calculation in Figure 16-1.

image

Figure 16-1: The AmountOwed calculation.

You don’t have to use only field names in your calculations. You can also enter formulas with numbers, like this:

NewCommitment: DonationCommitment *1.05

tip If a field name contains more than one word, put square brackets around it. Access treats anything else it finds in the calculation as a constant (which is the math term for it is what it is and it never changes). If the field name contains no spaces, Access will put the square brackets in for you after you enter the field name. That’s why I always use one-word field names — so I don’t have to type those irritating square brackets.

tip When you create formulas, keep these general guidelines in mind:

  • You must type the field names and constants into your formula. You can’t just drag and drop stuff from the table list.
  • Don’t worry if your calculation grows past the edge of the Field box. Access still remembers everything in your formula, even if it doesn’t appear onscreen.

    tip To make the query column wider, aim the mouse pointer at the line on the right side of the thin bar above the calculation entry. Keep trying until you see a vertical line with a horizontal double arrow through it. When that happens, click and drag the mouse to the right. As you do, the column expands according to your movements. To fit the width to just the right size, position the mouse to size the column as described earlier — and then double-click! Isn’t Access a gem?

  • If it’s a super-duper long calculation, press Shift+F2 while the cursor is somewhere on the calculation.

    This opens the Zoom dialog box so you can easily see and edit everything in a pop-up window.

When you run a query containing a calculation, Access

  • Produces a datasheet showing the fields you specified.
  • Adds a new column for each calculated field.

In Figure 16-2, the datasheet shows the VolunteerID, FirstName, LastName, DonationCommitment, DonationAmount, and the calculated field AmountOwed for each volunteer.

image

Figure 16-2: The results of the amount owed calculation in Datasheet view.

Complex Calculations

After getting the hang of simple calculations, you can easily expand your repertoire into more powerful operations, such as using multiple calculations and building expressions that use values from other calculations in the same query. This stuff really adds to the flexibility and power of queries.

Calculate ’til you drop!

Access makes it easy to put multiple separate calculations into a single query. After building the first calculation, just repeat the process in the next empty Field box. Keep inserting calculations across the query grid until you’ve calculated everything you need.

tip You can use the same field in several calculations. Access doesn’t mind at all.

Using one calculation in another

One of the most powerful calculated-field tricks involves using the solution from one calculated field as part of another calculation in the same query. This is sometimes called a nested calculation, and it can do two useful tricks:

  • It creates a field in the query results.
  • It supplies data to other calculations in the same query, just as if it were a real field in the table.

Figure 16-3 shows an example of a nested calculation in Design view.

image

Figure 16-3: The AmountOwed calculated column is referred to in the NextDonation column.

Figure 16-4 shows the actual results of the calculations.

image

Figure 16-4: The results of the AmountOwed and NextDonation columns.

warning Although this technique seems simple, be careful. A small error in one calculation can quickly trickle down to other calculations that are based on it, compounding a simple error into a huge mistake. Yikes!

To use the results from one calculation as part of another, just use the name of the first calculation as if it were a field name. In short, treat the first calculation like a field in your table.

Using parameter queries to ask for help

At times, you may want to include a value in a formula that doesn’t exist anywhere in your database (for example, the number .25 for a 25-percent next donation rate in the calculation example earlier in this chapter). If you know the value, you can type it directly into the formula.

But what if the number changes all the time? You don’t want to constantly alter a query; that’s a big waste of time and effort. Instead of building the ever-changing number into your formula, why not make Access ask you for the number (called a parameter) when you run the query? This is an easy one:

  1. Think of an appropriate name for the value (such as Tax Rate, Last Price, or NextDonatePercent).

    tip When choosing a name for your parameter, don’t use the name of an existing field in your table — Access will ignore the parameter if you do. Instead, go with something that describes the number or value itself. As you can see in the query grid shown in Figure 16-5, entering something like [Enter next donation percentage as decimal] makes it very clear what is required from the user. When you look at this query months (or even years) from now, you can easily recognize that something called [Enter next donation percentage as decimal] probably is a value that Access asks for when the query runs, not a normal field.

  2. Use the name in your formula as if it were a regular field.

    Put square brackets around it and place it into your calculation, just as you did with the other fields.

  3. Run the query.

    Access displays a dialog box like the one shown in Figure 16-6.

  4. Enter the prompted information.

    For this example, just enter the value of your next donation percentage (as a decimal value). Access does the rest.

image

Figure 16-5: The next donation percentage parameter in the NextDonation calculated field.

image

Figure 16-6: Access asks for a next donation percentage.

tip This option means you can use the same query with different values to see how changing that value affects your results.

“Adding” words with text formulas

Number fields aren’t the only fields you can use in formulas. Access can also use the words stored in text fields.

tip A classic formula comes from working with names. If you have a Volunteers table with FirstName and LastName fields, you will at some point want to string those names together on a form or report. A text formula can do this for you. It can add the first name to the last name; the result is the person’s full name in one column.

The syntax for text-field formulas is similar to the syntax for number-field formulas — the field name is still surrounded by square brackets and must be carefully entered by hand. Include literal text in the formula (such as spaces or punctuation) by surrounding it with quotation marks (for example, you’d type “,” to insert a comma).

You connect text fields with the ampersand character (&). Microsoft calls the ampersand the concatenation operator, which is a fancy way to say that it connects things.

Figure 16-7 shows a text-field formula. This example solves the problem I describe earlier in this section: making one name out of the pieces in two separate fields. The formula shown in the figure combines the FirstName and LastName fields into a single full name, ready to appear on a mailing label, report, or some other useful purpose you dream up.

image

Figure 16-7: Turning two names into a single calculated field.

This formula consists of the FirstName field, an ampersand (&), a single space inside quotation marks, followed by another ampersand, and then the LastName field. Here’s what it looks like:

[FirstName]&“ ”&[LastName]

When you run this query, Access takes the information from the two fields and puts them together, inserting the space between them so they don’t run straight into each other. Figure 16-8 shows the results of this query.

image

Figure 16-8: First and last names are combined to the single field, FullName.

Hooray for Expression Builder

Creating calculated fields presents you with two basic challenges:

  • Figuring out what the formula should say
  • Entering the formula in a way that Access recognizes

Although Access can’t help you with the first problem, it tries hard to offer some assistance with the second. When all else fails, and you just can’t assemble a calculated field in query design exactly the way Access wants it, click the Builder button on the Design tab of the Ribbon to open Expression Builder (see Figure 16-9).

image

Figure 16-9: The Builder button launches Expression Builder.

Expression Builder has several parts, as shown in Figure 16-10.

image

Figure 16-10: Expression Builder, proud as a peacock.

  • You create the expression in the large window at the top.
  • The lower half of the dialog box contains three lists that work as a team:
    • The Expression Elements list provides a navigational tree containing all the items that are at your disposal to build an expression such as tables, queries, forms, reports, constants, functions, and operators.

      tip You’ll find the tables, queries, forms, and report objects within your database under an Expression Element with the same name as the name of your database. For example, if you want to select a Volunteers table field and you’re in a database named Access 2016 Dummies.accdb, you’ll see an item with that name on the Expression Elements list. Expand that item by clicking the plus sign (+) next to it to see the Tables item. Expand the Tables item to see the list of tables. Click the Volunteers table to see the fields in the Expression Categories list. Double-click the desired field to add it to the expression.

    • When you click something in the Expression Elements list (such as Operators), the Expression Categories list populates with the categories within the selected element.
    • When you click a category in the Expression Categories list (such as Comparison), the Expression Values list populates with the items within the selected category that finally (whew!) you can use in your expression.
  • technicalstuff Near the bottom of the Expression Elements list, Access also includes a few items for the Truly Technical Person — including these:

    • Constants (values that never change, such as true and false).
    • Operators that are available for comparisons and formulas:

      The Arithmetic category contains operators for addition, subtraction, division, and multiplication.

      The Comparison category contains operators such as =, >, <, <>

      tip Use comparisons to develop expressions for the Criteria section of your queries, when you need a response of true or false.

      The Logical category contains logical operators such as and, or, and not.

      The String category contains the Ampersand (&) operator that is used to combine two text fields.

    • A folder called Common Expressions that contains stuff that’s common only if you’re creating reports or working with dates.

Expression Builder works like a big calculator crossed with a word processor:

  • At the bottom, double-click items in the Expression Categories or the Expression Values list (depending on the situation) to include them in your expression at the top.
  • Click anywhere in the big pane on top; then type whatever you need to type.

tip Expression Builder can refer to controls on a form in your query so you can easily control the criteria used to run the query. Figure 16-11, for example, shows a simple form called Order Report with one combo box called Customer that lists all customers in the Customers table.

image

Figure 16-11: The Donation Report form with the Volunteer combo box.

Figure 16-12 shows how Expression Builder finds and uses the combo box on the form.

image

Figure 16-12: Expression Builder is used to select the Volunteer combo box from the Donation Report form.

Finally, Figure 16-13 shows the expression in the Criteria row of the Donor Totals Report query. So how does all this work? Open the form and select a volunteer. Run the query, and the query will be limited to just the donations for the volunteer selected on the form. Cool, huh?

image

Figure 16-13: The expression as it appears in the Criteria row of the Donor Totals Report query.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset