Microsoft Word Field Maths Tutorial
Microsoft Word Field Maths Tutorial
Introductory Notes
This document shows how to do a range of field-based calculations using Microsoft
Word, versions 97 and later, using field coding instead of macros. Whilst macros are
sometimes simpler to use (for those who know how to use them), using field codes
avoids some of the security issues associated with macros.
Using This Document
In this document, the bookmarks used to create an example may be re-used in other
examples. A side effect of this is that the calculated dates and times in the examples will
display a result based on the last-bookmarked entry for each reference when this
document is first opened. This can be corrected by updating the affected fields and
would not appear in documents where the bookmark names are not re-used.
Viewing Fields
To view the fields in this document, I recommended that you toggle field shading on. You
can do this via Tools|Options|View (Word 97-2003) or Word Options|Advanced>Show
Document Content (Word 2007) and, under Show, selecting the Always or When
selected options. Youll probably find the Always option works best. Doing this has no
effect on the printed output but makes the fields easier to work with on-screen.
To see the inner workings of any field, select it and press Shift-F9. When youre done,
pressing Shift-F9 again will toggle the display back to showing the fields results.
Alternatively, if you press F9, the field will update and toggle the display back to showing
the fields results in one go.
Many of the date and time field examples in this document have been laid out with line
feeds to better show their structure when the field code is toggled on. The line feeds
can be deleted.
A syntax error occurs with some fields while theyre in this document because the fields
concerned are designed for use in a mailmerge main document, which this document
isnt.
Updating and Recalculating Fields
To update/recalculate a given field, simply select in and press F9. Most will update
without any further action on your part, but the interactive examples will prompt you for
input(s). This introduces an important issue with calculations in Word: unlike Excel,
except when used in Form Fields in protected documents with the calculate on exit
attribute set, Word fields cannot be set to automatically calculate whenever their source
data changes you must do something to cause a re-calculation to occur. Printing a
document is another way to force a documents fields to recalculate provided you have
the Update Fields option checked under Tools|Options|Print.
Internationalization Issues
Many of the fields in this document use comma separators for IF tests, MOD statements
and the like. To use the fields in regions that use commas as decimal separators, the
commas in the affected parts of the field codes need to be changed to semi-colons.
Taking the first Rounding Numbers Up or Down field code (Page 15) as an example,
the field code as supplied reads:
{=INT(SUM(5.5,6.6,7.7)+IF(MOD(SUM(5.5,6.6,7.7),1)>0,1,0))}
The modified field for a region requiring semi-colon separators would read:
{=INT(SUM(5.5;6.6;7.7)+IF(MOD(SUM(5.5;6.6;7.7);1)>0;1;0))}
(note the ; semi-colons)
the field braces {} are created via Ctrl-F9 or via the Formula command on the
Table menu to insert an = (Formula) field in a table or in other text (see Perform
calculations in a table in Words Help file for more details). Typing the braces is
not sufficient to create a field;
the first character in the field is an equal sign = (although a space followed by an
equal sign is also valid);
a formula, which may include a bookmark reference, follows the equal sign; and
A formula can use any combination of numbers, bookmarked numbers, fields that output
numbers. Any of Words numeric operators and functions can also be used.
Note: Some of the examples in this document are mere text representations of
field coding, using typed braces {} rather than actual field coding with field
braces. All such examples are still coded the same as true fields and can be
converted to such by replacing the typed braces with field braces (see above).
Operator
Addition
Subtraction
Multiplication
Division
Percentage
{=3+2} = 5
{=3-2} = 1
{=3*2} = 6
{=3/2} = 1.5
{=3*2%} = 0.06
{=3^2} = 9
{=3^(1/2)} = 1.73
Operator
Equal to
Not equal to
<>
Less than
<
<=
Greater than
>
Returns
The positive value of a number or formula, regardless of its actual
positive or negative value. For example, {=ABS(-5)} and {=ABS(5)} both
return 5.
DEFINED(x) The value 1 (true) if the expression x is valid, or the value 0 (false) if the
expression cannot be computed. For example, {=DEFINED(1/0)} returns .
FALSE
INT(x)
The numbers to the left of the decimal place in the value or formula x. For
example, {=INT(5.15)} returns 5.
MIN()
MAX()
MOD(x,y)
The remainder that results from dividing the value x by the value y a
whole number of times. For example, {=MOD(5.15,2)} returns 1.15.
of
values.
For
example,
SUM()
TRUE
Description
AND(x,y)
Returns the value 1 if the logical expressions x and y are both true, or
the value 0 (zero) if either expression is false. For example,
{=AND(5=2+3,3=5-2)} returns 1.
OR(x,y)
NOT(x)
Reverses the logic of its argument. Returns the value 0 (false) if the
logical expression x is true, or the value 1 (true) otherwise. For example,
to test whether two values are equal, you could use {=NOT(3<>2+1)},
which is equivalent to {=(3=2+1)} and returns 1.
IF(x,y,z)
Word lacks an exclusive OR (XOR) field function for testing whether exactly one
expression is true. You can simulate one, though, by use a formula like
=((5=2+3)+(3=5-2)+(2=5-3)=1), which returns 0 here because more than one test
expression is true. Indeed, you can expand this to test whether any exact number
of expressions is true, by replacing the final 1 with the required number of true
expressions. Naturally, if all expressions must be true, youve created the
equivalent of an AND function
Testing Negative Numbers
Word doesnt handle negative numbers correctly in field calculations. Logically, one
would expect a field construction like:
{QUOTE{ASK Val Number }{IF{Val}> -5 True False}}
False
to work, but it doesnt!. For example, the IF test returns True for 6 and false for -1,
whereas it should return False and True, respectively. To get the correct result, you
need to add a value corresponding to the negative positive value to the value being
tested, then compare the result against 0, as in:
{QUOTE{ASK Val Number }{IF{={Val}+5}> 0 True False}}
False
Testing and Returning Text Strings with Logical Functions in Bookmarks
You can use an IF field to test whether two text strings match, and output a variable
result accordingly, as in:
{IF{BkMrk1}= {BkMrk2} "BkMrk1 = BkMrk2" "BkMrk1 <> BkMrk2"} or
{IF{BkMrk}= "True Text" "BkMrk is True Text" "BkMrk is not True Text"} or
{IF Hello World = Hello World True False}
In fact, you can use any of the Formula Field Comparison Operators in IF fields to test
two text strings, and output a variable result accordingly, as in:
{IF{BkMrk1}> {BkMrk2} "BkMrk1 > BkMrk2" "BkMrk1 <= BkMrk2"} and
{IF{BkMrk}=> "True Text" "BkMrk => True Text" "BkMrk < True Text"}
When you use comparison operators this way, Word compares each character in each
string. The fields output is based on the results of that comparison.
As well, you can test whether a string contains a specified sub-string at a specified
position:
{QUOTE{ASK String String}{IF{String} = "?AB*" True False}} True
using ? characters to modify the starting position of the sub-string in the test string and
a * to disregard the rest of the string after the sub-string.
You can also nest IF fields to construct a test like:
{IF{BkMrk1}= {BkMrk2} {IF{BkMrk3}= {BkMrk4} {IF{BkMrk5}= {BkMrk6} "True Text"
"False Text 3"} "False Text 2"} "False Text 1"}
Note: Words IF fields can be nested 20 levels deep, though Im not sure why
youd want to
As previously mentioned, you cant use AND or OR fields directly to test text strings, but
you can achieve similar results using IF fields.
For a simple AND test with text strings you could use:
{IF{={IF{REF BkMrk1}= "True Text" 1 0}*{IF{REF BkMrk2}}= "True Text" 1 0}= 1
Both conditions met At least one condition not met}
or
{IF{={IF BkMrk1 = "True Text" 1 0}*{IF BkMrk2 = "True Text" 1 0}}= 1 Both
conditions met At least one condition not met}
So, for a multi-termed AND test with text strings you could use:
{IF(={IF{REF BkMrk1}= {REF BkMrk2} 1 0}*{IF{REF BkMrk3}= {REF BkMrk4} 1
0}*{IF{REF BkMrk5}= {REF BkMrk6} 1 0}}= 1 All conditions met At least one
condition not met}
For a simple XOR test with text strings you could use:
{IF{={IF{REF BkMrk1}= "True Text" 1 0}+{IF{REF BkMrk2}}= "True Text" 1 0}= 1
Exactly one condition met Not exactly condition met}
or
{IF{={IF BkMrk1 = "True Text" 1 0}+{IF BkMrk2 = "True Text" 1 0}}= 1 Exactly
one condition met Not exactly condition met}
So, for a multi-termed XOR test with text strings you could use:
{IF{={IF{REF BkMrk1}= {REF BkMrk2} 1 0}+{IF{REF BkMrk3}= {REF BkMrk4} 1
0}+{IF{REF BkMrk5}= {REF BkMrk6} 1 0}}= 1 Exactly one condition met Not
exactly condition met}
As with the numeric XOR tests discussed previously, you can expand this to test
whether any exact number of expressions is true, by replacing the final 1 with
the required number of true expressions.
(b)
(c)
(d)
Heres the same cross referencing and calculation from the 3rd line using formula
fields:
2 * 12 = 24 using formula fields coded as {Text3}, {Text6} and {={Text3}*{Text6}},
respectively.
In the VBA Project window, click on the Normal project and expand it if its not
already expanded.1
If the Normal project has a branch named Modules and youre happy to add
the code to an existing code module, expand it, then skip the next step
If the Normal project doesnt have a branch named Modules, or you want to
create a new code module, use Insert|Module to add a code module.
Select your code module and paste the contents of the clipboard into it.
Position the cursor in the cell for which you want the address information;
For regular use, you could add the macro to a toolbar (Word 2000-2003) or to the Quick
Access Toolbar (Word 2007). For instructions on how to do this, go to:
http://www.gmayor.com/installing_macro.htm.
Referencing Cells Containing Numbers
When you use cell references in a table, you reference table cells using an
alpha-numeric column-row format (eg A1, A2, B1, B2, and so on). Cell references in
Microsoft Word, unlike those in Microsoft Excel, are always absolute and are not shown
with dollar signs. For example, referring to a cell as A1 in Word is the same as referring
to a cell as $A$1 in Excel.
Referencing Cells Containing Text
Alpha-numeric column-row cell referencing does not work with text strings, including
dates and other mixed alpha-numeric character strings. Consider the following:
21/03/2000
0.003500
21 March 2000
2021
((15+14)*2-10)/6
10
Hello World
To refer to a character string in a cell, the character string (not the cell itself) must be
individually bookmarked and the bookmark referred to in the reference. See Testing and
Returning Cell Contents in Tables below.
Note: When you close Word, you may be asked whether to save changes to Normal.dot after doing this.
If you want the macro to be available for the future, answer Yes.
1
Reference Operators
You can combine ranges of cells in a table, or across tables, for calculations with either
or both of the following reference operators:
Operator
Description
: (Colon)
Example
Use a row or column range that includes only the number or letter that refers it.
For example, 1:1 to reference the first row in the table, or A:A to reference the
first column in the table. This form of referencing includes all the cells in the row
or column, even if rows/columns are added or deleted later. Dont do this within
the row or column being referenced, though, or your formula will include itself in
the evaluation (ie circular referencing), which will cause arithmetic errors that will
increase every time the field updates.
Use a range that identifies specific cells or ranges of cells. For example, for a 4row table, D1:D4 refers to the cells on rows (1-4) in Column D. This form of
referencing restricts the calculation to include only the particular cells. Adding or
deleting cells later may require you to edit the calculation.
Referencing Adjacent Cells in a Row or Column
For analysing column/row contents within a table, Word offers the ABOVE, BELOW,
LEFT and RIGHT parameters as arguments for the functions AVERAGE(), COUNT(),
MAX(), MIN(), PRODUCT(), and SUM(). At first sight, these parameters would seem to
imply that, when coupled with the functions mentioned, all of the cells ABOVE, BELOW,
LEFT or RIGHT would be evaluated. Unfortunately, thats not always the case and the
behaviour across these functions is inconsistent, as indicated in the table below.
6
1.2
1.2 2.63
{=AVERAGE(ABOVE)}
{=COUNT(ABOVE)}
{=MAX(ABOVE)}
21
{=MIN(ABOVE)}
{=PRODUCT(ABOVE)}
{=SUM(ABOVE)}
Whats going on? The ABOVE, BELOW, LEFT or RIGHT parameters are including the
last non-numeric cell before and all non-numeric cells after the last range containing
numeric values in the range being evaluated (i.e. the shaded cells), but not the entire
ABOVE, BELOW, LEFT or RIGHT range. When using COUNT on an empty column
10
ABOVE, BELOW, LEFT or RIGHT the field returns the number of rows/columns. So, use
these parameters with caution.
Exclude Numbers in Table Heading Cells from Calculations
One of the problems you can encounter when using formulae like {=SUM(ABOVE)} is
that a heading that contains a number will be included in the calculation. There is a
simple way around this, however. Consider the following table:
List of 5 Items
List of 5 Items
15
15
Notice how the number in the left-hand columns heading is included in the column total,
but not for the right-hand column. Yet both use the same {=SUM(ABOVE)} formula. The
difference is that the right-hand column has another single-cell table nested in it. By
putting the heading into a nested table, the heading is isolated from the calculations. An
advantage this has over putting the heading in a separate table is that you can then use
the Heading rows repeat attribute to replicate the table heading on subsequent pages, if
need be, without putting the headings into the page header.
Relative Referencing in Tables
The table below contains various Word formulae.
16.27
$16.00
$32.27
$13,512.35
$292.59
$7.00
$14.00
$13,512.35
$63.00
116.49
$116.00
($0.49)
$13,512.35
$13,512.35
The formulae in Columns D & E show how to implement relative referencing for rows.
These formulae work by setting up sequence number bookmarks for each row, and
using those to create a cell reference for the remainder of the logic. Either of these
allows the formula to be copied down multiple rows, updating row references as it goes.
Columns D and E behave differently due to the differences in how they implement row
sequencing:
Column D uses the SEQ field once per cell to get the row reference, then uses
the row number indirectly in creating cell references. The downside is that all
rows display the same value when the document is opened, since the fields will
'forget' their values when the document is closed. The next time the document is
opened, all display the last rows result. The correct results display immediately
the fields are updated, though.
11
Column E, on the other hand reuses the SEQ field in each cell, re-creating the
row reference for each source cell. To do this, it uses the \c switch to stop
multiple SEQ references changing the SEQ No., but it also needs to divide the
SEQ No by 2 because of a flaw in the way Word updates SEQ fields when used
directly in a cell reference. The advantage is that the cells retain the correct
values when the document is closed.
Note: If your data doesnt start on the first row in the table, you add an offset for
each row before the first data row. Thus, if your data starts on the second row,
youd put +1 after each {SEQ Row} in Column D (i.e. {={SEQ Row}+1}) and after
each {SEQ RowNr}/2 in Column E (i.e. {SEQ RowNr}/2+1). If the data starts on
the third row, you use +2, and so on. Use the same technique to offset the cell
referencing by a predetermined number of rows, using negative values to refer to
rows above, and positive values to refer to rows below.
is
The quick brown fox The quick brown fox Here the cell marker is
jumps over the lazy dog. jumps over the lazy dog. excluded from the bookmark
Using the same cross-references from outside the table, youll get:
The quick brown fox
jumps over the lazy dog.
and
The quick brown fox jumps over the lazy dog.
Similarly, to test whether cell A1 in a table is empty or has any numeric value other than
0, and evaluate B2-B1 only if TRUE, you could use:
{=IF(A1=0,0,B2-B1)} or {=IF(A1,B2-B1,0)}
For a field that evaluates B2-B1 if A1 has any numeric value including 0, you could use:
{=IF(COUNT(A1)=0,0,B2-B1)}
For purely numeric work, you can use a syntax that mirrors Excels (aside from the fact
that Word cell references are always absolute and dont use $ symbols to indicate this).
For example:
{=IF(A1=0,10,B2-B1)}
Things come unstuck using an Excel syntax in a Word table if you want to have a nul
result or evaluate a text string. In Excel you'd use:
=IF(A1=0,"",B2-B1)
to return a nul result but, the equivalent field in Word:
12
{=IF(A1=0,"",B2-B1)}
produces a syntax error. You then need to resort to constructs like:
{IF{=COUNT(A1)}= 0 "" {=(B2-B1)}}
or you could use numeric switch arrangements such as those outlined below.
Note: If you change the font attributes of the true/false responses (eg fore/back
colour, bold, etc), the field results will display with those attributes. This can be
combined with font attributes for numeric switches (see below).
Reference Table Cells from Outside a Table
Only the following functions can accept references to table cells as arguments from
outside that table:
AVERAGE(), COUNT(), MAX(), MIN(), PRODUCT(), and SUM().
When referencing cell values in a table from outside that table, set up a bookmark for the
table (Table1, say), then use the a suitable function (even for a single cell) to retrieve the
table values (e.g. {=SUM(Table1 C1)} or {=SUM(Table1 A3)+SUM(Table1 B3)}).
This technique can be useful when you need to refer to one or more table values in the
documents text, do math with them or even refer to them in another table.
Note: If you use numbers as the last character in bookmark names, make sure
the name includes at least three text characters before the number. Otherwise
Word might interpret the bookmark name as a cell reference.
Referencing Row and Column Totals from Outside a Table
To extract a column total from a table, where the last row of the table contains the total,
but without needing to know the totals row number, simply sum the column and divide
the result by two (eg: {=SUM(Table1 D:D)/2)}. A similar technique could be used for a
row (eg: {=SUM(Table1 3:3)/2)}.
13
for the switch even if positive and negative values are displayed the same way. With a
numeric switch like \# #;-#;, the second semicolon, with nothing after it, tells Word not to
display 0 results. See Columns C-E in the table under Relative Referencing in Tables
for examples of this.
You could even use a switch like: \# #;-#; to display for zero values (Alt-0216 = )
or, indeed, to display different text outputs for positive and negative values too (eg
\# Profit $,0.00;Loss $,0.00;Break Even). Note the quote marks around the switch
coding; required to accommodate the text with spaces. A significant benefit of adding
text and/or suppressing zeros this way (instead of using IF tests to output nulls or
spaces) is that the field will continue evaluate as a number in other formulae. You can
have up to 64 characters between the double-quotes in the field switch.
If you change the font attributes of the numeric switches (eg fore/back colour, bold, etc),
the field result will display with those attributes (eg Profit $1.00, Loss $1.00 &
Break Even.
Ordinal Numbering
Word numeric fields support an \* Ordinal switch (eg {5 \* Ordinal} displays 5th), but what
if you want the figure to display the 5th to display as 5 th? Heres two ways to do it:
5th or 5th
Expressing Numbers as Words
Sometimes, youll want to express a fields result in Words. Microsoft provides two field
switches for this: \* CardText; and \* DollarText. For example:
one hundred twenty-three thousand four hundred fifty-six
one hundred twenty-three thousand four hundred fifty-six and 78/100
Both switches are limited to values less than 1,000,000.
As you can also see, Microsofts DollarText switch also doesnt express a value as X
dollars and Y cents it returns X and Y/00. Heres a more sophisticated approach:
nine hundred ninety-nine thousand nine hundred ninety-nine dollars and ninetynine cents.
Nine hundred and ninety-nine million, nine hundred and ninety-nine thousand,
nine hundred and ninety-nine dollars and ninety-nine cents.
Note: In addition to going well beyond the normal CardText and DollarText limits, the
second field includes and where required for UK/Australian English.
14
Even Rounding
Words formula field also lacks a ROUNDEVEN function, which is sometimes used in
financial circles to counter the cumulative effect of 0.5 units being rounded up. To
overcome this, you can use a formula like:
{=ROUND(5.5)-(MOD(5.5,0.5)=0)*(MOD(ROUND(5.5,0),2)>0)/2,0)} = 6 (as usual)
and
{=ROUND(6.5)-(MOD(6.5,0.5)=0)*(MOD(ROUND(6.5,0),2)>0)/2,0)} = 6 (instead of 7).
This gives a rounding sequence of 0.5:0, 1.5:2, 2.5:2, 3.5:4, etc
To round evenly to the nearest multiple of a number (eg 5), you can use a formula like:
{=ROUND(55-(MOD(55,5)=0)*(MOD(ROUND(55,-1),20)>0)/2,-1)} = 60 (as usual)
and
{=ROUND(65-(MOD(65,5)=0)*(MOD(ROUND(65,-1),20)>0)/2,-1)} = 60 (instead of 70).
This gives a rounding sequence of 5:0, 15:20, 25:20, 35:40, etc
15
Being able to parse data this way can be useful in a mailmerge where, if youre using
formatted sensitive data (eg US Social Security Numbers and telephone numbers) and
only want to include part of it (eg the last 4 digits), you can use something like:
XXX-XX-!Syntax Error,
where ClientRef is the datasource field name.
A similar approach can be taken with US Zip Codes, without having to know in advance
how theyre formatted. With the field coding below, the data source could have any
combination of 5-digit, 5+4-digit formatted, 5+4-digit unformatted (ie 9 digit) and 5-digit
followed by -0000 or --000 (which allows for systems that are unable to differentiate
between 5-digit and 5+4-digit formatted zip codes):
!Syntax Error, !!Syntax Error,
Note: A syntax error occurs with the previous two fields because theyre designed
for use in a mailmerge main document, which this document isnt.
Scientific Notation
Words formula field doesnt include a scientific notation function. To overcome this, you
can use a formula like:
1.006666666667 in scientific notation form is 1.01E 00.
Logarithms
Words formula field also doesnt include a logarithm function. To overcome this, you can
extend the above scientific notation function by adding a Taylor Series approximation to
generate quite accurate results:
The logarithm of 1.006666666667 is approximately -0.4771212547642.
As coded, the field gives valid results for values between 10^-9 and 10^9 to 13 decimal
places, which should be enough for most purposes. If you need to calculate the logs of
larger/smaller values, increase the values in parameter b (the exponent) accordingly.
Note: Although not implemented in this document, references to constants in
tables or bookmarks (as in the SET fields used here to define certain logarithmic
values) need only be established once for the whole document.
Trigonometry
Words formula field also doesnt include trigonometric functions, such as Sine, Cosine
and Tangent. Again, you can use Taylor Series approximations to generate quite
accurate results (to 13 decimal places):
Angle
Sine
Cosine
Tangent
45
0.707107 0.707107 1.000000
To update, select the table and press F9 to input an angle.
16
Financial Calculations
Financial Calculation Algorithms
The financial formulae fields below each solve one financial argument (PV, FV, PMT,
NPER) in terms of the others, using:
(pmt*nper)+pv+fv = 0 if the rate is 0, and
pv*((1+rate)^nper)+pmt*(1+rate*type)*((1+rate)^nper-1)/rate+fv = 0 otherwise, where:
pv
is the present value of a loan or investment, and represents the current
value of a series of future payments. For example, when you borrow money, the
amount you owe is the present value to the lender.
fv
is the future value, or a cash balance of the loan or investment after the
last payment is made. For example: you open a savings account that earns 6%pa
interest compounding monthly for a special project, the account matures in a year
from now, the initial deposit is $2,000 and you deposit a further $150 at the
beginning of every month for the next 12 months. In one year the account will
have a balance of $+5,222.67.
rate is the interest rate per period. For example, if you borrow money at 10%pa
interest, compounding monthly, your monthly interest rate is (10/12)% = 0.8333%.
The fields require only the annual rate of interest to be input: 12 interest periods
pa are assumed, but you can change that, if necessary, by editing the fields.
nper is the total number of payment periods over the life of the loan or
investment. For example, a five-year loan paid monthly has 5*12 = 60 periods.
The pv and fv fields require only the number of years to be input: 12 payments pa
are assumed, but you can change that, if necessary, by editing the fields.
pmt is the fixed instalment paid in each period. The instalment amount usually
includes components to cover both principal and interest but may not include loan
fees etc. For example, the monthly instalment on a $25,000, four-year loan at
13.5% per annum interest is $-676.91, plus any fees & taxes. The result is
negative because it represents money you would pay (i.e. a negative cash flow).
type is the number 0 or 1 and indicates when instalments are paid. 0 indicates
payments are made at the end of the period, 1 indicates payments are made at
the start of the period. Equally, some loans charge interest on the basis of the
amount outstanding at the beginning of the period, whilst others charge interest
on the basis of the amount outstanding at the end of the period.
17
18
macropod 2004-2016
19