3 s2.0 B9780123746238500074 Main

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

5

Decision Functions
This chapter deals with making decisions or having a cell display
a value that is conditional upon what is in one or more other cells.
We begin with the logical comparison operators and Boolean
functions. We examine the IF function and show how to use
SUMIF, SUMIFS, and SUMPRODUCT. Then we examine the table
lookup functions LOOKUP, VLOOKUP andHLOOKUP. The chapter
concludes with some notes on conditional formatting.

Logical Comparison
Operators

The logical comparison operators are used to make tests. We will


concentrate on numerical comparisons such as is the value in Al
greater than 4?

You may know these operators


as relational operators if you
have studied computer
programming.

The comparison operators are:


=
equal to
>
greater than
>=
greater than or equal to
<
less than
<=
less than or equal to
<>
not equal to
LetAl hold the value 10, and Bl the formula =Al>10. Since this is
untrue, the formula returns the Boolean value FALSE. Ifwe make
the formula =Al >=10 then the result will be TRUE.

In computer science, the


implicit change of data type is
called coercion.

In the formula =Al>=10, the Al>=10 part is called a logical


expression. Logical expressions evaluate to either TRUE or FALSE
in Excel. A logical expression has the form:
Expression-l Logical-operator Expression-2
It can be useful to have logical expressions evaluated to 1 or O.
Excel treats the Boolean values as 1 and 0 when combined with
mathematical operations. Following the example above, the
formula =(Al>10)*1 will return the value 0 while =(Al>=10)*1
returns the value 1. Using two negation operators is a very
efficient method to coerce Boolean values to numeric values; we
may use a formula such as =--(Al>=10). When a Boolean value is
expected, Excel will accept any nonzero numeric value as TRUE
and a zero value as FALSE.

70 A Guide to Microsoft Exce/2007for Scientists and Engineers

Exercise 1: Boolean
Functions

The functions AND and ORmay be used to testtwo or more logical


expressions, while the NOT function is used to reverse the truth
value of a logical expression.
(a) On Sheetl of a new workbook, enter the values in Al :B4 of
Figure 5.1. Use the information in columns D and F to enter
formulas in columns C and E.
(b)

Save the workbook as Chap5.xlsx.

Figure 5.1
By default, Excel aligns Boolean values (TRUE and FALSE)
centered horizontally in their cells.
Note that ifin this worksheet you entered the formula =A2>5,
the result would be TRUE. Excel would compare the letter a (a
text data type) with the literal 5 (also a text data type): the
ASCII value for a is 97, and that for 5 is 53.
There are some common combinations that are useful to know.
In the following table, Aand Bmay be expressions or references
to cells containing the values TRUE or FALSE. You may wish to
experiment with these nested formulas on Sheetl.

Logic
NAND
NOR
XOR

Exercise 2: Practical
Example

Formula

TRUE

=NOT(AND(A,B))
=NOT(OR(A,B))
=OR(AND(A, NOT(B)),AND(B, NOT(A)))

returned if
Not both true
Neither is true
Only one is true

Scenario for this Exercise: In a manufacturing plant, 10 items are


tested every hour. For each item, two quantities (P and Q) are
measured; the P value must meet a certain value, while the Qvalue
must not exceed a certain value. Figure 5.2 shows the worksheet
we need to find what percentage of our product is up to
specification.

Decision Functions 71
(a) On Sheet2 of Chap5.xlsx, enter the text and numbers shown
inAl:B16, C2:C3, and C5:E5 of Figure 5.2.
(b) Name C2:C3 as pmin and qtnax, respectively.

Figure 5.2
(c) The formula in C6 is =- -(A6>=pmin) and this is copied down
the column; if you remember the shortcut method of double
clicking the fill handle, you will need to delete C16.
(d) In D6 we need the formula =- -(B5<=qmax); and in E6
=- -AND(A6>pmin,B6>=qmax). These are to be copied down to
row 15. Can you think of a simpler formula in E6?
(e) Row 16 summarizes the results giving the percentage that
passed the tests. We might be tempted to use
=SUM(C6:C15)jCOUNT(C6:C15) in C16 to get the fraction
that passed the P-test. But this is just an average, so why not
use =AVERAGE(C6:C15) here and corresponding formulas in
D16 and E16?
(f)

The IF Function

Save the workbook.

The simple, unnested IF function can be thought oflike this: If my


test is true then return this-value else return that-value. The
function returns one of two possible values depending on the
outcome of a logical expression-the test. The syntax is:
=IF(logical- test, true-value, false-value)

72 A Guide to Microsoft Excel 2007for Scientists and Engineers


The logical test is generally a logical expression we looked at
above; for example Al>10. In Help, we are told the logical test
must return either TRUE or FALSE. An example of a simple IF is
=IF(Al>=10, "OK", "Too small").
Nesting is permitted to 64
levels in Excel 2007, but
getting the logic correct with
anything this complex is a
major achievement! Generally,
it is better to look for a
solution using one of the
lookup functions.

However, Excel also allows simple arithmetic expressions in an IF


test. Consider the expression Al-l 0; if this evaluates to a nonzero
value, Excel treats it as TRUE, only zero is taken as FALSE. The
formula =IF(Al=O,"Zero", "Not zero") could be coded as =IF(Al,
"Not Zero", "Zero"). But do not try to be too clever with this
approach since others may not follow the logic.
For more complicated formulas, we can nest IF statements. We
can replace either or both of true-value andfalse-value by another
IF statement. Some examples are shown below.
(i)

The IFERROR function is new


to Excel 2007. The first
argument is the expression
you wish to evaluate, and the
second argument is the value
to be returned when the first
expression results inan error.

(ii)

(iii)

(iv)

(v)

(vi)

=IF(A2<0, "Negative","Positive")
Returns the text "Negative" if A2 has a value less than 0;
otherwise it returns "Positive."
=IF(B5<>0, A5/B5, "") or =IF(B5<>0, A5/B5, NA())
Here is a way of preventing the #DIVO! error. These formulas
will return a blank or #Nj A when the divisor is zero,
otherwise the division result is returned.
An alternative formula is =IFERROR(A5/B5, "").
=IF(ABS(AlO- BlO)<=EPSILON, "Equal","Unequal")
A cell called EPSILON contains a value such as 1.0E-6. Rather
than doing a direct comparison of two values, we test if they
differ by more than this value.
=IF(ABS(AlO-BlO)<= 0.001,1,0)
Returns 1 if ABS(Al0- Bl0) is less than or equal to 0.001,
otherwise it returns O. We could also use the simpler formula
=- -(AlO-BlO<=O.OOl).
=IF(SUM(A12:A200, SUM(A12:A20), "Error")
If the sum of the range is greater than a, that value is
returned, otherwise the text "Error" is displayed.
=IF(Al, TRUE, FALSE) or =IF(Al<>O, TRUE, FALSE)
These will return the value TRUE if Al contains a nonzero
value, a formula giving a nonzero value, or the TRUE value. If
Al is empty or has the value a, the FALSE is returned. A
simpler formula would be =Al<>O, and this would be easier to
understand.

Decision Functions 73

Next we look at some examples of nesting.


The logical operators may not
be used in array formulas.

(i)

=IF(A1>1O, IF(A1>50, "Big","Medium"), "Small")

It is clear that if the condition A1 > 10 is false then the outer


IF returns "Small". What happens if the condition is true? The
inner IF comes into play. When A1 >50, the inner IF returns
'Big', otherwise it returns "Medium."
(ii) =IF(A1>1O, IF(A1>50, "Big","Medium"), IF(A1<0, "Negative",
"Small"))

Here both the true-value and the false-value of the outer IF


are themselves IF functions. What results when A1 is O?
The logical functions AND(), OR(), and NOT() may be used within
an IF formula.
(i)

=IF(AND(A2>0, A2<11), A2, NA())

The value A2 is returned if A2 is greater than 0 and less than


11. Otherwise, the function NA() returns the error value
#N/A.
(ii) =IF(OR(A2>0, B2>A2/2), 3 ,6)

Returns the value of3 if either A2 > 0 or B2 > A2/2. Ifneither


condition is true, the value 6 is returned.
(iii) =IF(NOT(A2=0), TRUE, FALSE)
This is the same as IF(A2=O, FALSE, TRUE).
(iv) =IF(NOT(OR(A1=1, A2=1)), 1,0)
This is a somewhatcontrived example. It returns 1 only when
both A1 and A2 have a value that is not 1.

Exercise 3: Resistors
Revisited

In Exercise 5 of Chapter 2, we developed a worksheet that


computed the effective resistance offour resistors in parallel. We
had to invent a workaround to allow us to use the worksheet with
fewer than four resistors. With the information in this chapter we
can improve our work.
(a) Open Chap2.xlsx, select A1:E6 and click the Copy command
on the Clipboard group of the Home tab (or use the [Ctrl]+C
shortcut). Open ChapS.xlsx and move to Sheet3. With A1 as
the active cell, use [Ctrt] V to paste the copied material.
(b) Select D6:E6 and then click the eraser icon on the Editing
group of the Home tab; select Erase All to remove both cell
entries and formats.

74 A Guide to Microsoft Exce/2007for Scientists and Engineers


Now we need to change some of the formulas to give us a
worksheet as shown in Figure 5.3.
(c) In B4 replace =1/B3 by =IFERROR(l/B3,""). Copy this across
to E4. Place a zero value in E4 to see that the new formula no
longer gives #DIVO! but an apparently empty cell when the
divisor is zero.
(d) We will find the reciprocal of all sums of the four l/R values
with one formula. At the same time we will round the result
to the nearest 10. What we need in B6 is
=ROUND(l/5UM(B4:E4),-1).

(e) Select B6:C6 and use the Merge and Center tool. Open the
Formatting dialog and give this cell the custom format
o"ohms." Test your worksheet.
(f)

Save the workbook.

Figure 5.3
(g) If this were a worksheet in the workplace, the user would
have no need to see row 4. Furthermore we would want to
ensure that the user could not inadvertently change any
formulas in that row. Right click the row header 4 and select
Hide. Later we will learn how to protect cell B6.

Exercise 4: Quadratic
Equation Solver

In this Exercise we design a worksheet to solve a quadratic


equation in the form ax' + bx + c = 0 using the quadratic formula:

- b .J b 2 - 4ac
x=-----2a
The quantity b2 - 4ac is called the discriminant; its value
determines the number (0,1, or 2) of real roots of the equation.

Decision Functions 75

When this Exercise is completed, the worksheet will resemble that


in Figure 5.4.

Figure 5.4
(a) Open Chap5.xlsx. On Sheet4 enter the values and text shown
in Al:C4. Select A3:C4 and horizontally center the entries
with the button in the Home / Alignment group.
(b) With A3:C4 still selected, use the command Formulas /
Defined Names / Create from Selection to give the cells A4:C4
the names in the cells above them.

For information on imaginary


roots see the workbook
IMAGROOTS.XLSX on the
companion website.

(c) Type disc (short for discriminant) in E3. Enter the formula
=b*b - 4*a*c_ in E4. Center E3:E4 and create the name disc
for the cell E4.
(d) Temporarily ignore the entries in row 6.
(e) Type the text shown in A7 and C7. Enter these formulas
B7:
=(- b + SQRT(disc) )/(2*a)
D7: =(- b - SQRT(disc) )/(2*a)
(f)

Save the workbook Chap5.xlsx.

You now have an operational worksheet. Test it with quadratic


equations whose roots you know. What happens if the value of the
discriminant is negative? Try the values 1, 3, and 6 for a, band c,
respectively. Cells B7 and D7 show the error value #NUM! since it
is impossible to evaluate the square root of a negative number
without entering the realm of imaginary numbers.
The next steps will improve the behavior of the worksheet when
the discriminant is negative and present some additional
information.

76 A Guide to Microsoft Exce/2007 for Scientists and Engineers

(g) Enter the text in A6 and center this over A6:B6. In C6 enter
the formula =IF(disc<O, 0, IF(disc=O, 1, 2)). This returns 0
when the discriminant is negative, 1 when it is zero, and 2 in
all other cases.
(h) Replace the text in A7 with =IF(C6=0,"",IF(C6=1,"Double
Root","Root 1")). If there is one root, this returns the text
"Double Root," if there are two identical roots, it returns
"Root I." When there are no real roots, it returns an empty
test string.
(i)

We require the formula in B7 to return a root when the


discriminant has a zero or positive value, and an empty text
string otherwise. We can achieve this by modifying it to read:
=IF(disc>=O,(-b+SQRT(disc))/(2*a), "").

(j)

Replace the text in C7 by =IF(C6=2, "Root 2", "


to return
the text "Root 2" only when the discriminant has a positive
nonzero value.
II

(k) Modify D7 to =IF(disc>O,(-b-SQRT(disc))/(2*a), "") to return


the value of the second root only when the discriminant has
a positive nonzero value. Note that in B7 we tested to see if
disc> =0 while in D7 we tested if disc>0; this prevents a double
root appearing twice.
(I)

Make up some simple quadratics whose roots you know; for


example (x - 4)(x + 3)=0 gives x2 -x-12 = 0 and the roots are
clearly 4 and -3. Test that x2 - 9 = 0 reports a "double root"
Make any required adjustments.

(m) Save the workbook.

Exercise 5: Protecting
a Worksheet
Do not use this type of
protection for supersensitive
information. Many websites
offer password breakers.

Imagine that you have developed a worksheet for use by yourself


or others to solve real-world problems. It would be wise to guard
against accidental changes being made to cells, especially those
with formulas. We will use the quadratic solver as an example. We
will arrange things such that the user can visit only the cells
needed to define the problem: A4:C4.
There are two steps to the process: (i) specify which cells the user
may change by unlocking those cells (by default all cells on a new
worksheet are locked) and (ii) switch on worksheet protection.

Decision Functions 77

(a) Open Sheet4 of Chapt5.xlsx. Select A4:C4. Use the command


Home / Cells / Format to open the menu shown in Figure 5.s.
We could just click the Lock Cells item (last but one from the
bottom), which acts as a toggle to lock and unlock cells.
Alternatively we may use the last item Format Cell... and open
the Protection tab to reveal the dialog shown in Figure 5.6.
Here we will uncheck the Locked box and click the OK button.
(b) Use the command Home / Cells / Format / Protect Sheet to
open the dialog shown in Figure 5.7. Our objective is just to
prevent accidental changes so we will not use a password.
Note that we have the option of allowing the user to visit both
locked and unlocked cells. Ifwe did not wish the user to see
our formulas, we could deselect Locked in this dialog. We
shall leave all the other boxes unchecked.
(c) Testthe worksheetto see that only the unlocked cells (A4: C4)
can be changed. Save the workbook.

Figure 5.6

Figure 5.5

Figure 5.7

78 A Guide to Microsoft Excel 2007for Scientists and Engineers

Table Lookup
Functions

Table lookup functions have a range of uses. Whenever you find


yourselfcomposing a multinested IF function, you should consider
whether a lookup function would be more appropriate. Avertical
table has its headings in a row, while a horizontal one has them in
a column. There are no inherent advantages of one over the other.
The functions VLOOKUP and HLOOKUP have similar syntax:

column_index_n um,

VLO 0 KUP (lookup_ value,


range_lookup)

table_ array,

HLO 0 KUP (lookup_ value,


range_lookup)

table_array, column_in dex_n um,

Lookup_ value Is the value to be located in the first column of a


vertical table (or the first row of a horizontal
table). Lookupvalue may be either a numeric or
text value or a cell reference.
Table_array
Is the range reference or name of the table.
Column_index_num (row_index_num)
Is the column (or row) of the table from which the
value is to be returned.
Range_lookup Is a logical value (TRUE or FALSE) specifying
whether you want an approximate or an exact
match. If rangelookup is TRUE or omitted, and
there is no exact match, then the function returns
the next largest value that is less than the lookup
value. If FALSE and no exact match is found, the
function will return the error value #NjA If
lookupvalue is less than the lowest value in the
first column (first row with HLOOKUP), the
function returns the #Nj A error value.

There is also the LOOKUP function; see Exercise 8.


The MATCH function returns the relative position of a
lookup value in an array. Its syntax is: MATCH (lookup_value,
lookup_array, match_type). The first two arguments have the
same meaning as above. Use 1 for match_type when the table is
sorted in ascending order, and you wish to find the largest value
that is less than or equal to lookupvalue, Use a when you needed
an exact match; the table need not be sorted. Use -1 when the
table is sorted in descending order, and you wish to find the
smallestvalue that is greater than or equal to lookupvalue, When
lookup_value is nonnumeric, MATCH, VLOOKUP, and HLOOKUP
are not case sensitive. MATCH may also be used with wildcards.

Decision Functions 79
The INDEX function returns an element from an array and has two
forms. The syntax of the first form is INDEX(array, row_num,
column_num). Thus =INDEX(Al:Cl0, 2, 3) returns the value atthe
intersection of row 2 and column 3 of the table Al:Cl0. In this
example, it returns the value from cell C2.

Exercise 6: A Simple
Lookup

For the purpose of this exercise, a geologist wishes to grade some


ore samples based on their rare metal content. Ore with SO to 59
ppm is to be given a low grade: from 60 to 79 merits a medium
ranking, from 80 to 99 is considered high, and anything above that
is very high. Our completed worksheet will resemble Figure 5.8.

Figure 5.8

Cell C9, which displays #N/A,


has a small green triangle in
its upper left corner. When
the cell is selected, a warning
tip appears, which if opened
gives information on the error
value. One option is Ignore
Error; use this to hide the
triangle.

(a) Open Chap5.xlsx and start on SheetS. For convenience we will


enter the lookup on the same worksheet as the ore data. Type
the entries shown in El:F6.
(b) Enter the text and numbers shown inAl:Bl0 and C4.
(c) The formula in C5 is =VLOOKUP(B5,$E$3:$F$6,2,TRUE).
Since we do not want an exact match, we could have used
=VLOOKUP(B5,$E$3:$F$6,2). The $ symbols within the
references are, of course, needed to keep the reference to the
table unchanged as we copy the formula.
(d) Copy the formula down the column.
(e) Save the workbook.

80 A Guide to Microsoft Excel 2007for Scientists and Engineers


Here are some "experiments" you may wish to try. Between each
one, close the file without saving and reopen it.
(f)

Modify the formulas in column Cwith an IF function such that


when the B value is less than SO, the cell appears empty.

(g) Get the same effect by moving E3:F6 down one row and
adding new data in E3. You will need to modify the formulas.
(h) Cut the table and paste it on a new sheet. Note how the
formulas in column Cautomatically adjust.
(i)

Exercise 7: A TwoValued Lookup

Since the table is (i) sorted and (ii) only two columns wide,
the LOOKUP function could be used in place of VLOOKUP.
Read Help and make the change.

In this example our tables have more than two columns, so we


need some way of indicating in the VLOOKUP formula which one
to use. For this Exercise we shall use MATCH.
Scenario: A nutritionist enters a client's height, frame type, and
weight, and the worksheet gives the person's optimal weight and
a comment on his actual weight. To keep the Exercise to a
reasonable size, we limit ourselves to just male clients. Our final
product will resemble Figure 5.9.
(a) Begin by entering the table in E1:H16.
(b) Enter the text shown inA1:A12; and the values in B3:B5. Use
custom format # ??/12 in B3 so we can use feet and inches.
In B5 use custom format 0 "Ibs'' and apply this to Bll with
the Format Painter. We will treat B12 differently.
(c) Create the following names:
frame =F1:H1; height =E2:E16, and optimal = E2:H16.
(d) The formula in B8 is =MATCH(B4,frame,O)+1. Observe how
this works: The L in B4 corresponds to the third column in
frame; we add 1 since we are working with the table optimal.

Decision Functions 81

Figure 5.9

(e) In Bll we have =VLOOKUP(B3*12,optimal,B8). The value in


B3 times 12 gives 68; this value is found in the first column of
the optimal, and the function returns the correspondingvalue
in the fourth column since B8 evaluates to 4.
(f) The formulas in B12 and C12 are, respectively
=IF(B5=Bll,"OK",ABS(Bll-B5)&" Ibs")
=IF(B5=Bll,"" ,IF(Bll<B5,"over", "under"))

(g) Save the workbook.


Change the values in B3:BS, observe the results and ensure you
understand how the formulas work.
The A7:C8 entries are there for demonstration; we could have
combined the B8 and Bll formula as:
=VLOOKUP(B3*12, optimal, MATCH(B4,frame,O)+1)
Whatever can be done with a lookup function can also be done
with a combination of INDEX and MATCH. See Problem 2 at the
end of the chapter.

Exercise 8: Conditional The Excel functions SUMIF and COUNTIF may be used to
conditional sum or count a range of values. The values are
Summing
summed (or the entries are counted) subject to specified criteria
being satisfied. In the case of SUMIF,the range to be summed may
differ from the range to be tested.

82 A Guide to Microsoft Exce/2007for Scientists and Engineers

Excel 2007 has the new functions SUMIFS and COUNTIFS where
multiple criteria may be specified. In addition, Excel 2007 has
=AVERAGEIF and AVERAGEIFS.
Unit
A
B
A
B
C
C
C

Problem

P2
P4
Pi
P4
P3
P6
P6

Downtime
9

14
20
26
14
12
14

Figure 5.10

Figure 5.11

Figure 5.12
To get a real appreciation of these functions, one needs a
moderately sized data set Rather than have the user make up
data, a file called ConditionalSums.xlsx is available on the
companion website. The first few rows of this are shown in Figure
5.10. Each column is named by the label in the top row. Scenario:
Amanufacturer has three identical productions units (A, B,and C)
and has kept a record of the problems they have incurred in a
certain time period and how much downtime there was to make
each repair/adjustment Figure 5.11 shows an example of various
formulas that could be used to analyze the data.

Decision Functions 83

Pivot tables are very useful for summarizing data; see Exercise 4
in Chapter 6. A sample pivot table made from the data in
ConditionalSumx.xlsx is shown in Figure 5.12.

Exercise 9: Array
Formulas

In this Exercise we look at constructing array formulas from


functions that do not normally need to be treated as array
functions. For this we shall first make an array of 20 numbers
using the RAND BETWEEN function. We shall use a new method of
filling the 20 cells. In the next part of the exercise we will find the
sum of the largest five members of the array. In the second part
we sum the values regardless of sign. The completed worksheet
will have the entries shown in Figure 5.13 (without the text
versions of the formulas). The formulas with asterisks are array
formulas.

Figure 5.13

Figure 5.14
(a) On Sheet? of Chap5.xlsx, enter the text as in rows 1 and 3.
(b) SelectA4:A24, type =RANDBETWEEN(l,lOO) andcommitthe
formula with [Ctrll+[ .-J I (note there is no [0- ShiftI). This is an
alternative to typing the formula in one cell and then
dragging it down to row 24.

84 A Guide to Microsoft Excel 2007for Scientists and Engineers


(c) Select A4:A24 (or leave it selected from the previous step).
Type mydata into the name box to give our array a name.
We now have 20 random numbers, but these will keep changing
since Excel will recalculate the worksheet every time we make a
change. Let's turn the formulas into values.
(d) SelectA4:A24 and use [Ctrl]+C to copy it.. With the range still
selected, right click A4 and open the Paste Special dialog.
Check the Values box and click OK. The formulas are now
values. In preparation for the final partofthe exercise, change
the first value to something negative. Of course, your values
will not match those in the figure.
(e) In B4 enter the formula =LARGE(mydata,l). This will return
the largest value in mydata.
(f)

But this is unsatisfactory since it cannot be copied down the


column to generate =LARGE(mydata,2). Change the formula
to =LARGE(mydata,ROW(Al)). The result is unchanged
because ROW(Al) evaluates to 1.

(g) Copy B4 down to B8. Notice how the reference to Al changes


in such a way that we get the top five values in B4:B8.
(h) Use the AutoSum tool to getthe summation ofthese five in B9.
For those readers with
programming experience, an
array formula is akin to using
a loop structure.

Finally we are set to demonstrate an array formula. We will now


see how we could get the result showing in B9 in one simple
formula.
(i)

Enter the formula shown for Bll remembering to use


[Ctrl]+[ 0- Shift]+[ .-J I as we learned in Exercise 6 of the last
chapter. We get the same result as in B9.
Normally, the function LARGE returns one value as we have seen.
But when entered with [Ctrl]+[ 0- Shift]+[ .-J I it generates an array.
Within Bll's formula, the
{1,2,3,4,5} part shows how to
enter an array of constants.

(j)

SelectBll and use the command Formulas / Form ula Auditing


/ Evaluate Formula. As you use that dialog, you will see
something akin to Figure 5.14.

(k) An alternative formula is used in B12; it is also an array


formula.

Decision Functions 85

We have seen an example of an array formula using LARGE; now


we look at another with ABS.
(1)

Exercise 10:
Conditional
Formatting

Enter the simple formula in D5 and the array formula in D5.


Once again we have used a single-values function (ABS) to
generate an array; since this is wrapped in a SUM function,
we can add these members of the array.

This chapter has dealt with formulas that return values that
depend on a condition (tests, or criteria). In the last exercise we
look at conditional formatting: how to give cells a format that
depends on a criterion. We may wish values above (or below) a
certain value to be displayed in a different color or to be in cells
with an eye-catching background fill. Another use is to hide
certain values.
We will start by seeing how to hide specified formula values. In
Exercise 8 we had a cell that may return # Nj A. If we wished this
not to appear, we could change the formula in C5 from
=VLOOKUP(B5,$E$3:$F$6,2,TRUE) to the lengthy one: =IF
(ISERROR(VLOOKUP(B5,$E$3:$F$6,2,TRUE)),"",=VLOOKUP(B5,
$E$3:$F$6,2,TRUE)). But conditional formatting might be better.
(a) Select C5:Cl0 in SheetS. Use the command Home / Styles /
Conditional Formatting and in the resulting drop-down menu
select New Rules. In the next dialog box, click on Format cells
that contain. ... and select Errors (see Figure 5.15). Click the
Format button and on the Font tab set the color to match the
cell background color (most likely it will be white). Return to
the worksheet and the #NjA value is invisible.
(b) In the same worksheet, perhaps we would like a different
background color for the ppm depending on the value in the
corresponding C cell. Select B5:Bl0, open the Conditional
Formatting dialog, and select Use a formula to determine.....
Complete the resulting dialog as shown in Figure 5.16 and use
the Format button to select a background color. Repeat for
each possible value in Cusing different background colors.
Other conditional formatting examples are to be found in the file
ConditionalFormatxlsx on the companion website.

86 A Guide to Microsoft Exce/2007for Scientists and Engineers

Figure 5.15
Figure 5.16

Exercise 11:

SUMPRODUCT

The primary purpose ofthe SUMPRODUCT function is to compute


the sum of the products of the elements of two or more arrays.
Thus SUMPRODUCT (Al:A3,Bl:B3) evaluated Al *Bl + A2*B2 +
A3*B3.
Scenario: Aprocess engineer has taken 25 samples from a product
stream and analyzed them for an impurity. The results are
tabulated in rows 3 and 4 of Figure 5.17. He needs to compute the
average and standard deviation. When computing an average
where a measurement Xi occurs ni times, we speak of a weighted
average, and it is found with
avg = Ix;n;
In;

The numerator is exactly what SUMPRODUCTcomputes, while the


denominator is found with SUM.

Figure 5.17
(a) Construct a worksheet similar to that in Figure 5.17.
(b) In cell B6 use =5UMPRODUCT(B3:F3,B4:F4)/5UM(B4:F4).

Decision Functions 87

To see how the & operator


works, type app/ein Al and pie
in Bl. In Cl enter =Al &" " &
Bl.

(c) In E6 use =SQRT(SUMPRODUCT((B3:F3-$B$6)"2,B4:F4) I


(SUM(B4:F4)-1)) to get the standard deviation. Note how
SUMPRODUCT accepts the agreement (B3:F3-$B$6)A2
without requiring that we make it an array function. This is
a major strength of the function.
(d) To summarize the results in C8 we use =ROUND(B6,2) &
& ROUND(E6,2). Recall from Chapter 2 that is produced
with [A[] + 0177 on the numeric keypad. In this formula the
ampersand (&) is used as the concatenation operator-it
joins text together.
II

II

SUMPRODUCT is also used in ways that the developers may never


have considered. These involve counting and summing ranges
subject to multiple conditions that COUNTIF and SUMIF cannot
manage, being limited to one criterion. The introduction of the
Excel 2007 functions SUMIFS and COUNTIFS in Excel 2007 has
made some of these "tricks" redundant, but there are still times
when SUMPRODUCT outpaces these new functions. The primary
reason is that SUMPRODUCT allows you to perform operations on
the range being summed. Figure 5.18 gives an example.

Figure 5.18

The double negations in the


SUMPRODUCT formulas are
used to convert Boolean
FALSE/TRUE values to
numeric Oil values. It is
instructive to usethe Formula
Evaluation tool with the
formulas in G7:G9.

We can see that there are three cases with Test 1 = a and Test 2 =
x. The corresponding numbers in row 5 are 2, 3, and 5, which sum
to 10. The formulas are as follows.
Column F

7
8

=COUNTIFS(B3: H3, " a", B4:H4, " X" )


=SUM IFS(BS:HS, B3:H3, l a",B4: H4, " X" )
Column G

7
8
9

=SUMPRODUCT(--(B3:H3=lal),--(B4:H4=lx"))
=SUMPRODUCT(--(B3:H3=lal),--(B4:H4=l x"),BS:HS)
=SUMPRODUCT(--(B3:H3=la"),-(B4:H4=I X"),(BS: HS)A3)

88 A Guide to Microsoft Exce/2007for Scientists and Engineers


While COUNTIFS and SUMIFS in F7:F8 can replace the
SUMPRODUCT in G7:G8, there is no way SUMIFS can sum the
cubes of numbers that pass the test.
For a detailed discussion on SUMPRODUCT, see these websites:
Bob Phillips at
http://www.xldynamic.com/source/xld.SUMPRODUCT.html.
J.E McGimpsey at
http://mcgimpsey.com/exceljformulae/doubleneg.html.

Problems

1.

's.

Carnahan et aI., Applied


Numerical Methods, Wi ley,

In the hydraulic jump, 1 a liquid stream of depth DI flowing at


velocity VI' suddenly increases its depth to Dz. Figure 5.19
shows the equation that governs this effect. What formula
will you use in E5 that can be copied to H5?

New York, 1969 (page 203).

Figure 5.19
2.

*Refer to Figure 5.9 of Exercise 7. We saw that


=MATCH(B4 ,frame,O) tells us which column in the range
frame matches the frame type entered in B4. Write a formula
to find the row position in the range height to match the
client's height entered in B3. With the existing data in B3:B4,
our client's height and type place him in row 7 and column 3
of the table F2:H16. Write a formula beginning =INDEX that
will locate the optimal weight within this. Finally, combine
the INDEX formula and the two MATCH formulas into one.

3.

*The range Al :Al a in a worksheet contains both positive and


negative values, and you wish to sum only the positive ones.
Give a formula that will accomplish this.

4.

*The range Al :Al a in a worksheet contains both positive and


negative values, and you wish find the sum of the squares of
only the positive ones. Give a formula that will accomplish
this. Hint: try either of these:
(i) SUMPRODUCT, or
(ii) IF nested inside a SUMSQ as an array formula.

Decision Functions 89

5.

*With the same numbers as above, find the average of the


squares of the positive values.

6.

Construct a worksheet similar to that in Figure 5.20 to make


a simple molar mass calculator. Cell Cl0 uses a
SUMPRODUCT formula. Each cell in row 7 uses two IF
formulas joined with the concatenation operator &. The first
IF gets the symbol, and the next gets the number if it is
greater than 1. Then the row 7 cells are themselves
concatenated in Ala. Hiding rows 3 and 7 would make the
worksheet more interesting!

Figure 5.20
7.

Refer back to Problem 6 in Chapter 4. This time we will solve


the problem without the helper columns. Construct a
worksheet similar to Figure 5.21. The cells 111 and 112 each
contain formulas that use SUMIF. Alternatively, you may wish
to use SUMPRODUCT in your formulas.

Figure 5.21
Again we need to protect against having more than one X in
a column. Use the same approach as in Chapter 4's problem
but with COUNTA rather than COUNT.
8.

Rev. Dawn is a recycler; she finds 49 candle stubs and makes


exactly seven new candles. These in turn yield seven stubs,

90 A Guide to Microsoft Exce/2007for Scientists and Engineers


allowing her to make candle number eight from which she
later gets a stub. This is illustrated in A3:C7 of Figure 5.22
where we represent the process by 49-8R1.

Figure 5.22
(i)
(ii)

What formulas are used in F5, G5 and E6?


Show that 59-9R5, 67-11Rl, 79-13Rl, and 88
-14R4.
(iii) From this data, you might conclude that N stubs always
yield INT(N/6) candles. You might reason that this is so
because, although ittakes seven stubs to make a candle,
only six get consumed. Show that for N = 72 this is
incorrect; under what circumstance does it break
down? Algorithms must be fully tested!
(iv) What formulas are used in J5 and K5?

9.

In the left-hand part of Figure 5.23 we see the solution of a


system of equations, while in the right-hand part we see a
system with no solution. Refer to Exercise 8 of Chapter 4 and
tell what array formula is used in G4:G6.

Figure 5.23
10. In Bll Exercise 7 we ended up with
=VLOOKUP (B3*12,optimal,MATCH(B4,frame,O)+1)
(i) Modify it to return "l" if B3 is less than E2 or B4 has an
invalid value.
(ii) Make heights over E16 return "l]" and modifyB12:C12
to return nothing when Bll is "l" or "T!".

You might also like