Formulas and functions
Operators and precedence, the built-in function families, IF and nested IF, COUNTIF and SUMIF, VLOOKUP, and the error values and what each one means.
Module contents
Formulas
A formula is an instruction to calculate. It always begins with = — that is how Excel knows the entry is not text.
A formula may contain constants (, "Pass"), cell references (B2, Sheet2!A1), operators and functions.
Operators
| Type | Operators | Meaning |
|---|---|---|
| Arithmetic | + - * / % ^ | add, subtract, multiply, divide, percent, power |
| Comparison | = <> > < >= <= | produce TRUE or FALSE |
| Text | & | joins text: =A1&" "&B1 |
| Reference | : range, , union, space intersection | build ranges |
Order of precedence
Operators are not applied left to right. They are applied in this order:
Operators of equal precedence are evaluated left to right. Brackets override everything, and are worth adding whenever the reader might hesitate.
Functions
A function is a ready-made formula identified by name.
The arguments are the values it works on — numbers, text, cell references, ranges, or other functions. Some functions take none: =TODAY() still needs its brackets.
Statistical
| Function | Returns |
|---|---|
SUM(range) | Total |
AVERAGE(range) | Arithmetic mean |
MAX(range) / MIN(range) | Largest / smallest |
COUNT(range) | How many cells contain numbers |
COUNTA(range) | How many cells are not empty (text included) |
COUNTBLANK(range) | How many cells are empty |
MEDIAN, MODE, STDEV | Median, mode, standard deviation |
LARGE(range,k) / SMALL(range,k) | The -th largest / smallest |
RANK(value,range) | Position within the range |
COUNTcounts numbers;COUNTAcounts anything. In a column of namesCOUNTreturns — a favourite exam trap.
All of these ignore empty cells and text. But note the difference this makes: for five cells of which one is blank, SUM is unaffected while AVERAGE divides by 4, not 5. If the blank means zero, it must be entered as zero.
Mathematical
ROUND(number, digits), ROUNDUP, ROUNDDOWN, INT (truncate to integer), ABS, SQRT, POWER(x,n), MOD(a,b) (remainder), PRODUCT, SUMPRODUCT.
ROUND deserves emphasis: unlike a number format it changes the value, which is what makes a column of currency actually add up.
Text
LEFT(text,n), RIGHT(text,n), MID(text,start,n), LEN(text), UPPER, LOWER, PROPER, TRIM (removes extra spaces), CONCAT, FIND, SUBSTITUTE, TEXT(value,format).
TRIM is the routine fix for data pasted from elsewhere, where invisible trailing spaces stop lookups and comparisons from matching.
Date and time
TODAY(), NOW(), DAY, MONTH, YEAR, DATE(y,m,d), DATEDIF, WEEKDAY, NETWORKDAYS.
Because a date is stored as a number of days, =B2-A2 on two dates gives the number of days between them directly.
Logical
| Function | Returns |
|---|---|
IF(test, value_if_true, value_if_false) | One of two values |
AND(c1,c2,...) | TRUE only if all are true |
OR(c1,c2,...) | TRUE if any is true |
NOT(c) | Reverses |
IFERROR(formula, value) | The formula's result, or a substitute if it errors |
IFS(c1,v1,c2,v2,...) | The value for the first true condition |
Conditional aggregates
| Function | Returns |
|---|---|
COUNTIF(range, criteria) | How many cells meet one condition |
SUMIF(range, criteria, sum_range) | Total of cells whose row meets a condition |
AVERAGEIF(range, criteria, avg_range) | Mean of those cells |
COUNTIFS, SUMIFS | Several conditions at once |
Criteria may be a value, a reference, or a text expression: ">50", "BCA", "<>"&0.
Lookup
VLOOKUP(lookup_value, table_array, col_index_num, range_lookup)
Searches for the value in the first column of the table and returns the entry from the -th column of the matching row.
The fourth argument decides the kind of match:
FALSE(or ) — exact match. Almost always what is wanted. Returns#N/Aif not found.TRUE(or omitted) — approximate match, for banded lookups such as grade boundaries. The first column must be sorted ascending, or the answers will be silently wrong.
HLOOKUP is the same across a row. INDEX with MATCH, and the newer XLOOKUP, remove VLOOKUP's restriction that the lookup column must be the leftmost.
Error values
| Error | Cause | Usual fix |
|---|---|---|
#DIV/0! | Dividing by zero or by an empty cell | Guard with IFERROR or an IF test |
#VALUE! | Wrong type — arithmetic on text | Check for text in a numeric column |
#REF! | A referenced cell has been deleted | Rewrite the reference |
#NAME? | Misspelled function name, or unquoted text | Correct the spelling; quote text |
#N/A | A lookup found no match | Check the value exists and has no stray spaces |
#NUM! | An impossible number, e.g. SQRT(-4) | Check the argument |
#NULL! | An invalid range operator (a space instead of a colon) | Correct the range |
Errors propagate: any formula referring to an error cell shows an error too, so one bad cell can turn a whole report into hashes. This is why IFERROR is used on formulas exposed to imperfect data — though it should display a meaningful blank or message, never hide a genuine mistake.
Auditing
Trace Precedents and Trace Dependents draw arrows showing which cells feed a formula and which cells depend on it. Evaluate Formula steps through a long formula one operation at a time — the fastest way to find where a nested IF goes wrong. Show Formulas (Ctrl+grave accent) displays every formula instead of its result.
Worked examples
4 solvedEvery step is shown, in the order you would write it in an answer book.
Evaluating a formula by precedence
Question
Given A1 , A2 , A3 , evaluate (a) =A1+A2*A3 (b) =(A1+A2)*A3 (c) =A1+A2/A3^2 (d) =A1-A2-A3
Recall the order
with equal precedence evaluated left to right.
(a) =A1+A2*A3
Multiplication comes before addition:
Not .
(b) =(A1+A2)*A3
Brackets first:
(c) =A1+A2/A3^2
Power first, then division, then addition:
(d) =A1-A2-A3
Two subtractions have equal precedence, so left to right:
Right to left would give , which is wrong. This is why left-to-right matters for and , though not for and .
Answer
(a) (b) (c) (d)
NoteWhen in doubt, add brackets. They cost nothing and make the formula readable to whoever inherits the sheet.
Grading with a nested IF
Question
Marks are in B2. Write one formula giving A for , B for , C for , D for and F below that.
Understand how a nested IF is read
IF(test, value_if_true, value_if_false). To test more than one condition, the false slot holds another IF. Excel stops at the first test that is true, so the order of the tests does the work.Test from the highest boundary downwards
Note there is no need to write
AND(B2>=80,B2<90). If the formula reaches the second test at all, the first has already failed, so B2 is known to be below .Trace a value — B2 = 85
B2>=90? is FALSE → go to the false slotB2>=80? is TRUE → return "B" and stop
Nothing further is evaluated.
Trace a boundary value — B2 = 90
B2>=90? is TRUE → "A".Boundaries are where grading formulas go wrong. Using
>instead of>=would give a student with exactly a B. Always test the exact boundary values.See why the order cannot be reversed
Written from the bottom up:
a mark of satisfies the very first test, so it returns "D" and stops. Every mark above would be graded D. Descending order is not a style preference; it is required.
Note the alternatives
=IFS(B2>=90,"A",B2>=80,"B",B2>=70,"C",B2>=60,"D",TRUE,"F")is easier to read.For many bands, a lookup table with
VLOOKUPand approximate match is better still, because the boundaries then live in cells that can be changed without rewriting a formula.
Answer
=IF(B2>=90,"A",IF(B2>=80,"B",IF(B2>=70,"C",IF(B2>=60,"D","F"))))
NoteTest boundaries from the top down, and check each boundary value itself — 90, 80, 70, 60 — before trusting the formula.
Counting and totalling under a condition
Question
A sheet holds Department in column B, Marks in column C and Fee in column D, for rows 2 to 101. Write formulas for: (a) how many students are in BCA, (b) how many scored above 400, (c) the total fee from BCA students, (d) the average mark of BCA students, (e) how many BCA students scored above 400.
(a) Counting on a text condition
The criterion is quoted because it is text. It could equally be a cell reference —
=COUNTIF(B2:B101,F1)— which is better practice, since the department can then be changed without editing the formula.(b) Counting on a numeric comparison
The comparison is written inside quotation marks — the whole expression
">400"is the criterion.=COUNTIF(C2:C101,>400)is a syntax error.(c) Totalling a different column from the one tested
Read as: examine B, and where it says BCA, add the corresponding cell from D. The three arguments are where to look, what to look for, what to add — and the first and third ranges must be the same height, or the results silently misalign.
(d) Averaging under a condition
Note that AVERAGEIF ignores blank cells in the average range, so a missing mark reduces the divisor rather than counting as zero.
(e) Two conditions at once
One condition needs COUNTIF; two need COUNTIFS, in which the ranges and criteria alternate:
Only rows satisfying both are counted.
SUMIFSworks the same way, except that the range to be added comes first rather than last — the one inconsistency in this family, and worth remembering.A caution on matching text
COUNTIFis not case sensitive, so "BCA" and "bca" both match — usually convenient. But a trailing space in the data ("BCA ") will not match "BCA", and nothing on screen reveals the difference. Cleaning imported data withTRIMprevents an entire class of undercounting.
Answer
(a) =COUNTIF(B2:B101,"BCA") (b) =COUNTIF(C2:C101,">400") (c) =SUMIF(B2:B101,"BCA",D2:D101) (d) =AVERAGEIF(B2:B101,"BCA",C2:C101) (e) =COUNTIFS(B2:B101,"BCA",C2:C101,">400")
Looking up a price from a rate list
Question
A rate list occupies H2:J20 — item code, description, price. Cell B5 holds an item code. Write a formula that returns its price, and shows "Not listed" if the code is absent.
Check the leftmost-column requirement
VLOOKUPsearches only the first column of the table it is given. The item code is in column H, which is the first column ofH2:J20, so VLOOKUP can be used.Count the column to return
Columns are numbered within the table, not on the sheet:
The price is in J, so the column index is .
Write the lookup with an exact match
FALSEdemands an exact match. Omitting it defaults toTRUE, which performs an approximate match and can return the price of a completely different item without any warning — the most dangerous default in the whole application.Note why the table reference is absolute
$H$2:$J$20is locked so the formula can be filled down a column of item codes while the rate list stays put. Left relative, the table would drift downward and rows would fall off the bottom of it.Handle the missing code
An unmatched code returns
#N/A, which then propagates into any total. Wrap the lookup:If the lookup still fails on a code that is visibly present
Two usual causes, neither visible on screen:
- Trailing spaces —
"A101 "is not"A101". Fix withTRIM. - Number stored as text — a code that is a number in one place and text in the other never matches. The left-aligned entry in a right-aligned column is the giveaway.
- Trailing spaces —
Answer
=IFERROR(VLOOKUP(B5,$H$2:$J$20,3,FALSE),"Not listed")
NoteAlways pass FALSE explicitly. An approximate match on unsorted data returns wrong answers rather than errors, which is far harder to notice.
Practice problems
6 with solutionsWork each one on paper first. The full solution — not just the answer — is one click away.
Distinguish between a formula and a function. Write one formula and one function that both total A1 to A10.
Show solutionHide solution
| Formula | Function | |
|---|---|---|
| What it is | Any calculation the user writes | A ready-made calculation supplied by Excel, called by name |
| Begins with | = | = then the function name |
| Written by | The user, from operators and references | The user, but the logic is built in |
| Length | Grows with the task | Fixed, however large the range |
| Example | =A1+A2+A3 | =SUM(A1:A3) |
A function is used inside a formula, so the two are not alternatives: =SUM(A1:A10)*0.18 is a formula that contains a function.
Totalling A1 to A10.
As a formula:
=A1+A2+A3+A4+A5+A6+A7+A8+A9+A10
As a function:
=SUM(A1:A10)
Why the function is better. It is shorter and readable; it adjusts automatically when rows are inserted inside the range, whereas the long formula silently omits the new row; it ignores text and blanks instead of failing; and it scales — the same nine characters total ten cells or ten thousand.
=; a function is a built-in named calculation used within a formula. =A1+A2+…+A10 against =SUM(A1:A10) — the function is shorter, adjusts when rows are inserted, and scales.State the difference between COUNT, COUNTA and COUNTBLANK. For the range A1:A6 holding , "Pass", empty, , empty, "Fail", give each result.
Show solutionHide solution
- COUNT counts cells containing numbers only. Text, blanks and logical values are ignored.
- COUNTA counts cells that are not empty — numbers, text, dates, logical values, even a formula returning an empty string.
- COUNTBLANK counts cells that are empty.
Applying them to the range.
| Cell | Contents | COUNT | COUNTA | COUNTBLANK |
|---|---|---|---|---|
| A1 | ✓ | ✓ | ||
| A2 | "Pass" | ✓ | ||
| A3 | (empty) | ✓ | ||
| A4 | ✓ | ✓ | ||
| A5 | (empty) | ✓ | ||
| A6 | "Fail" | ✓ |
Note that COUNTA and COUNTBLANK together account for every cell in the range:
The examinable trap. To count students in a column of names, COUNT returns , because names are not numbers. COUNTA is the correct function. Conversely, to count how many students actually sat an examination from a column of marks with blanks for absentees, COUNT is correct — it excludes the blanks automatically.
Explain the IF function. Write formulas for: (a) "Pass" if B2 is at least , else "Fail"; (b) "Pass" only if both B2 and C2 are at least ; (c) a grade of A, B, C or F using bands of , and .
Show solutionHide solution
The IF function tests a condition and returns one of two values.
- logical_test — any expression giving TRUE or FALSE, such as
B2>=40 - value_if_true — returned when the test succeeds
- value_if_false — returned when it fails
Text results must be in quotation marks; numbers must not.
(a) One condition.
=IF(B2>=40,"Pass","Fail")
Note >=, not > — a student with exactly passes.
(b) Two conditions together. Combine with AND, which is TRUE only when every condition is TRUE:
=IF(AND(B2>=40,C2>=40),"Pass","Fail")
Use OR instead if passing either subject would suffice.
(c) Four bands — a nested IF. The false slot holds another IF, and the tests must run from the highest boundary downwards:
=IF(B2>=80,"A",IF(B2>=60,"B",IF(B2>=40,"C","F")))
Tracing : FALSE → TRUE → returns "B" and stops.
Why the order matters. Written from the bottom up — =IF(B2>=40,"C",IF(B2>=80,"A",…)) — a mark of satisfies the very first test and returns "C". Every mark above would be graded C. Descending order is required, not preferred.
Why no upper bound is needed. Once the first test has failed, the value is known to be below , so AND(B2>=60,B2<80) adds nothing.
A cleaner alternative for many bands is IFS:
=IFS(B2>=80,"A",B2>=60,"B",B2>=40,"C",TRUE,"F")
=IF(B2>=40,"Pass","Fail") (b) =IF(AND(B2>=40,C2>=40),"Pass","Fail") (c) =IF(B2>=80,"A",IF(B2>=60,"B",IF(B2>=40,"C","F"))) — nested IFs must test from the highest boundary down.Explain VLOOKUP and its four arguments. What is the difference between TRUE and FALSE as the last argument, and why is FALSE usually safer?
Show solutionHide solution
VLOOKUP — vertical lookup — searches for a value down the first column of a table and returns a value from the same row of another column. It is how one sheet fetches data held in another, replacing manual copying.
1. lookup_value — what to search for. A value, a cell reference, or text in quotation marks.
2. table_array — the range to search. Its first column must be the one containing the lookup value; VLOOKUP cannot look leftward. Normally made absolute ($H$2:$J$20) so the formula can be filled down without the table drifting.
3. col_index_num — which column of the table to return, counted within the table starting at for its first column. If the table is H2:J20, then H is , I is , J is — not , , .
4. range_lookup — the kind of match, and the argument that matters most.
TRUE against FALSE.
FALSE (or ) | TRUE (or omitted) | |
|---|---|---|
| Match | Exact | Approximate — the largest value not exceeding the lookup value |
| Data must be sorted? | No | Yes, ascending, by the first column |
| If not found | Returns #N/A | Returns the nearest lower entry |
| Used for | Codes, names, IDs, item numbers | Banded lookups: grade boundaries, tax slabs, discount tiers |
Why FALSE is usually safer. Two reasons, and the second is the serious one.
-
Most lookups are of identifiers, where an "approximate" item code or roll number is meaningless. There is no such thing as nearly the right student.
-
An approximate match on unsorted data fails silently. It does not report an error; it returns a value — just the wrong one. VLOOKUP with TRUE assumes ascending order and effectively stops as soon as it passes the target, so on unsorted data it returns whatever happened to be there. A plausible-looking wrong price is far more dangerous than a visible
#N/A, because nobody investigates it.
Since TRUE is the default when the argument is omitted, the fourth argument should always be written explicitly.
Handling a genuine miss:
=IFERROR(VLOOKUP(B5,$H$2:$J$20,3,FALSE),"Not found")
When a lookup fails on a value that is visibly present, the cause is almost always invisible: a trailing space (fix with TRIM) or a number stored as text in one of the two places.
Explain any six error values in Excel, with a cause and a remedy for each.
Show solutionHide solution
1. #DIV/0! — division by zero, or by a cell that is empty (an empty cell counts as zero in arithmetic).
Common case: =B2/C2 where C2 has not yet been filled in.
Remedy: guard the formula — =IF(C2=0,"",B2/C2) or =IFERROR(B2/C2,"").
2. #VALUE! — an argument of the wrong type, typically arithmetic on text.
Common case: =A1*2 where A1 contains "10 kg", or a number imported as text.
Remedy: find the text entry — it will be left-aligned in a column of right-aligned numbers — and correct it, or clean it with VALUE or TRIM.
3. #REF! — the reference points to a cell that no longer exists, because its row, column or worksheet was deleted.
Common case: deleting a column that a formula elsewhere depended on.
Remedy: the original address is unrecoverable, so the reference must be rewritten. Undoing the deletion immediately restores it.
4. #NAME? — Excel does not recognise a name in the formula: a misspelled function (=SUME(A1:A5)), text left unquoted (=IF(A1>5,Pass,Fail)), or an undefined range name.
Remedy: correct the spelling, and put quotation marks round text. Choosing the function from the drop-down list as you type prevents this entirely.
5. #N/A — "not available": a lookup found no match.
Common case: VLOOKUP for a code absent from the table, or present but with a trailing space, or stored as text on one side and as a number on the other.
Remedy: verify the value exists, clean it with TRIM, and wrap the lookup in IFERROR for the genuinely missing cases.
6. #NUM! — a numeric value that is impossible or out of range.
Common case: =SQRT(-4), or an iterative function that fails to converge.
Remedy: check the argument; guard with IF(A1>=0,SQRT(A1),"").
Also: #NULL! — an invalid range operator, usually a space typed instead of a colon (=SUM(A1 A5)); and #####, which is not an error at all but merely a column too narrow to display its number.
Two general points. Errors propagate — any formula referring to an error cell shows an error too, so one bad cell can spoil an entire report; and Formulas → Error Checking, with Trace Precedents and Evaluate Formula, is the quickest way to find the cell where the trouble started.
A column of ten marks has two blank cells for absent students. AVERAGE gives but the teacher expects . Explain the discrepancy and give the formula for each interpretation.
Show solutionHide solution
The cause: AVERAGE ignores blank cells entirely — it does not treat them as zero.
Let the eight marks that were entered total .
What AVERAGE computes. It sees eight numeric cells and divides by eight:
What the teacher expected. That an absentee scores zero, so the divisor should be the full ten students:
Both figures are arithmetically correct. They answer different questions, and the spreadsheet cannot know which was meant:
- is the average mark of those who sat the examination
- is the average over the whole class, counting an absentee as zero
The formula for each.
1. Average of those who appeared — the default behaviour, and correct if a blank means "no data":
=AVERAGE(B2:B11)
2. Average over all ten students, absentees counting as zero. Divide the total by the full count rather than by the count of numbers:
=SUM(B2:B11)/COUNTA(A2:A11)
using the names column, which has ten entries, for the divisor. Or, if the class size is fixed:
=SUM(B2:B11)/10
Note that =SUM(B2:B11)/COUNT(B2:B11) would not work — COUNT also ignores blanks and returns eight, reproducing the .
Which is right, and how to make the sheet say so. For most academic purposes the two are genuinely different statistics and both are worth reporting. Ambiguity is the real fault here, and it should be removed from the data rather than patched in the formula:
- If an absentee's mark is zero, enter . Then AVERAGE gives by itself, and every other function agrees.
- If the mark is genuinely unknown — the student will sit a supplementary paper — leave it blank, and label the column heading "Average (present only)" so no reader is misled.
- Use a distinct marker such as "AB" if absence must be visible on the sheet. Being text, it is ignored by AVERAGE exactly as a blank is, but a reader can see why.
The general lesson. A blank cell is an absence of data, not a zero, and Excel's functions treat it that way consistently. Whenever a blank actually means something — zero, not applicable, not yet known, absent — that meaning must be recorded explicitly, because no formula can recover an intention that was never written down.
=AVERAGE(B2:B11) for the present-only mean, or =SUM(B2:B11)/COUNTA(A2:A11) to count absentees as zero — and better, enter an explicit when zero is what is meant.