Using Fields to Insert Dynamic Data


The real secret to creating truly dynamic documents in Word is a little-known and even less understood feature called the field. A field is a miniprogram that generates or calculates a result and then displays that result in your document or stores it in a bookmark. Each field consists of code that resides inside a placeholder that you can put anywhere inside your document. Word has dozens of these codes, and they all generate data based on various kinds of information, such as the following:

  • Information that lies elsewhere in the documentFor example, a document property or the value stored in a bookmark.

  • Information from the environmentFor example, the current date or time, or input supplied by the user.

  • Information that results from a calculationFor example, the sum of a table column or the average of a set of numeric values stored in bookmarks.

The dynamism of the field comes from the fact that any of this information can change over time. When it does, the result displayed by the field also changes when the field is updated.

Even if you've never used fields directly (or haven't even heard of them), you've probably worked with fields at least indirectly. For example, if you select Insert, Date and Time, you're actually inserting a field that displays the current date or time (or both, depending on the format you select in the Date and Time dialog box). Similarly, if you've ever inserted page numbers, a table of contents, or a cross-reference, you've inserted a field in each case.

These examples serve as a reminder for an important field caveat: Fields can be amazingly powerful, but remember that Word often provides easier and more direct methods for accomplishing a field-related task. In general, if a field or field equivalent is also available via a menu command, a toolbar button, or some other part of the Word interface, you should always use the interface method. It saves times and reduces the chances that you'll make a mistake.

Inserting a Field

Besides using Word's built-in features (such as the Insert menu's Date and Time or Page Numbers commands) to insert fields, you can also add fields to your document using two other methods: using the Field dialog box and manually, as discussed in the next few sections.

Using the Field Dialog Box

The Field dialog box is the quickest and safest way to insert a field, because it acts as a front end for the 70-odd Word fields and their myriad properties and switches. (A switch is extra code added to the field that determines the look or behavior of the field.) Here are the general steps to follow to insert a field:

1.

Position the cursor where you want the field's result to appear.

2.

Select Insert, Field to display the Field dialog box.

3.

If you know the category assigned to the field, use the Category list to select it. Otherwise, select (All) in the Category list.

4.

Use the Field Names list to click the field you want to insert. Depending on the field you selected, the Field dialog box displays one or more controls in the Field Properties and Field Options areas. In Figure 1.13, for example, the Date field shows controls in both areas.

Figure 1.13. To avoid errors, use the Field dialog box to insert a field along with any properties or switches.


5.

Use the Field Properties controls to customize the field output.

6.

Use the Field Options controls to customize how the field operates.

7.

Click OK. Word inserts the field and displays its current value.

Understanding Field Code Syntax

Before you learn how to insert a field manually, you need to know the syntax used by field codes. The Field dialog box can help. First, here's the general syntax:

 { FIELD instructions } 

The braces serve to enclose the field code. The FIELD part is the name of the field. This is usually seen with all uppercase letters, but field names aren't case sensitive. (In this book, I use the all-uppercase format in the code examples. However, when I discuss fields in the main text, I'll use the initial caps or inner caps format: Date, EditTime, and so on.) The instructions part consists of the elements that control the behavior of the field and the look of its result. They correspond to the controls displayed in the Field Properties and Field Options areas of the Fields dialog box. There are often several items in the field instructions, and these items can include document elements (such as the name of a bookmark) and switches. Most instructions are not case sensitive, but a few are, as you'll see a bit later (for example, see Table 1.1).

Table 1.1. General Format (\*) Switches

Switch

Description

Character Formatting

\* charformat

Applies the formatting of the field code's first (nonblank) character to the entire result.

\* mergeformat

Applies the formatting of the original result to any new result that occurs when the field is updated.

Case Conversion

\* caps

Converts the first character of each word in the result to uppercase.

\* firstcap

Converts the first character of the first word in the result to uppercase.

\* lower

Converts all the characters in the result to lowercase.

\* upper

Converts all the characters in the result to uppercase.

Number Conversion

\* alphabetic

Converts the result to lowercase, alphabetic characters. The numbers 1 to 26 are converted to a through z, 27 becomes aa, 28 becomes bb, and so on. Zero displays a blank, and negative numbers generate an error.

\* Alphabetic

Converts the result to uppercase, alphabetic characters. The numbers 1 to 26 are converted to A through Z, 27 becomes AA, 28 becomes BB, and so on. Zero displays a blank, and negative numbers generate an error.

\* arabic

Converts the result to an Arabic number. (Arabic numbers are what the rest of us call cardinal numbers; that is, they're just the numbers 0 through 9.) For example, the result 3rd is converted to 3. Decimal results are rounded to the nearest whole number.

\* cardtext

Converts the result to a cardinal number written as text. For example, the result 32 is converted to thirty-two. Decimal results are rounded to the nearest whole number.

\* dollartext

Converts the whole number part of the result to cardinal text, replaces the decimal place with and, and displays the decimal part (rounded to two places) as a numerator over 100. For example, the result 10.95 is converted to ten and 95/100.

\* hex

Converts the result to hexadecimal numbers. For example, the result 30 is converted to 1E.

\* ordinal

Converts the result to an ordinal number. For example, the result 21 is converted to 21st.

\* ordtext

Converts the result to ordinal number written as text. For example, the result 21 is converted to twenty-first.

\* roman

Converts the result to lowercase Roman numerals. For example, the result 14 is converted to xiv.

\* Roman

Converts the result to uppercase Roman numerals. For example, the result 14 is converted to XIV.


The Ref field, for instance, displays the value of a bookmark. Among the many switches you can add to this field, the \* lower switch formats the displayed text as lowercase, and the \h switch sets the field as a hyperlink (that is, Ctrl+clicking the field takes you to the bookmark). Here's the field code that displays the value of a bookmark named FileName in lowercase as a hyperlink to the bookmark:

 { REF FileName \* lower \h } 

To help you learn not only the field names but also the instructions that go along with each field, open the Field dialog box, select the field, and then click the Field Codes button. The dialog box changes to show the field code and the general syntax for the field, as shown in Figure 1.14.

Figure 1.14. Click Field Codes to see this version of the Field dialog box.


To add further instructions to the code, click Options to display the Field Options dialog box, the layout of which depends on the field. Figure 1.15 shows the Field Options dialog box for the REF field.

Figure 1.15. Click Options to display the Field Options dialog box for the selected field.


For most fields, the Field Options dialog box has two tabs: General Switches and Field-Specific Switches. As the name implies, the items in the Field-Specific Switches tab are specific to the field you're working with. The General Switches are used in multiple fields, and they fall into three categories: format, numeric picture, and date-time picture.

The format switches all begin with the characters \* (followed by a space) and they handle character formatting, case conversion, and number conversion, as detailed in Table 1.1.

A numeric picture switch begins with the characters \# (followed by a space). You use it to specify how you want Word to display a numeric result. You build a numeric picture switch using the symbols described in Table 1.2.

Table 1.2. Symbols Used in Numeric Picture (\#) Switches

Symbol

Description

#

Holds a place for a digit, but displays nothing if no digit exists in the position. For example, if the result is 5 and the switch is \# ##, Word displays 5.

0

Holds a place for a digit. Displays zero if no digit is present in the position. For example, if the result is 5 and the switch is \# 00, Word displays 05.

. (period)

Displays the decimal point. For example, if the result is 24 and the switch is #0.00, Word displays 24.00.

, (comma)

Displays a comma as the thousands separator in results greater than or equal to 1,000 and less than or equal to 1,000.

$ or %

Displays the character.


Enter Picture Switches First

If you're inserting or editing the field by hand, make sure you enter the numeric picture or date-time picture switches before the format switches. If you insert the format switch first, Word displays an error as the field result.


Displaying Other Characters

Except for the standard numeric picture symbols# 0. and ,you can insert any character within the numeric picture and Word will display that character. For example, the following numeric picture switch appends the degree symbol to the result:

 \# #0.0° 


If you want to include a word or phrase within the results, you must enclose the entire numeric picture in quotation marks. For example, the following switch adds the phrase ° Celsius to the result:

 \# "#0.0° Celsius" 

Inserting Special Symbols

Symbols such as the degree sign (°) aren't available directly via your keyboard, of course. You can use Word's Insert, Symbol command to insert them, or, if you know the symbol's ANSI code, you can use your keyboard's numeric keypad (make sure the NumLock key is activated). For example, to enter the degree sign, press Alt+0176 on the numeric keypad. Here are some common ANSI characters you can use:

Key Combination

ANSI Character

Alt+0163

£

Alt+0162

¢

Alt+0165

¥

Alt+0169

©

Alt+0174

®

Alt+0176

°



If you want to use a different numeric picture for a result depending on whether it's positive, negative, or zero, use the following syntax:

 \# positive;negative;zero 

The three parts, separated by semicolons, determine how various numbers are presented. The first part defines how a positive number is displayed; the second part defines how a negative number is displayed; and the third part defines how zero is displayed. For example, the following switch specifies different pictures for positive, negative, and zero results (note the parentheses specified for the negative result):

 \# $0;($0);0 

If you leave out the zero picture, a zero result uses the positive picture:

 \# $0;($0) 

A date-time picture switch begins with the characters \@ (followed by a space). You use it to specify how you want Word to display a date or time result. You build a date-time picture switch using the symbols described in Table 1.3.

Table 1.3. Symbols Used in Date-Time Picture (\@) Switches

Symbol

Description

Date Formats

d

Displays the day part of the result without a leading zero (1 to 31).

dd

Displays the day part of the result with a leading zero (01 to 31).

ddd

Displays the day part of the result as a three-letter day abbreviation (Mon, for example).

dddd

Displays the day part of the result as the full day name (Monday, for example).

m

Displays the month part of the result without a leading zero (1 to 12).

mm

Displays the month part of the result with a leading zero (01 to 12).

mmm

Displays the month part of the result as a three-letter month abbreviation (Aug, for example).

mmmm

Displays the month part of the result with the full month name (August, for example).

yy

Displays the year part of the result as a two-digit year (00 to 99).

yyyy

Displays the year part of the result as the full year (1900 to 2078).

Time Formats

h

Displays the hour part of the result without a leading zero (0 to 24).

hh

Displays the hour part of the result with a leading zero (00 to 24).

m

Displays the minute part of the result without a leading zero (0 to 59).

mm

Displays the minute part of the result with a leading zero (00 to 59).

s

Displays the seconds part of the result without a leading zero (0 to 59).

ss

Displays the seconds part of the result with a leading zero (00 to 59).

AM/PM or am/pm

Displays the time using a 12-hour clock and either AM or PM or am or pm.

/ or :

Separates parts of dates or times.


Displaying Other Characters

If you need to include spaces in your date-time picture, enclose the picture in quotation marks, as shown here:

 \@ "m/d/yyyy h:mm AM/PM" 

As with numeric pictures, you can insert any character within the date-time picture and Word will display that character. If you want to include a word or phrase within the results, you must enclose the entire numeric picture in quotation marks. For example, the following switch adds the phrase Eastern Time to the result:

 \@ "h:mm Eastern Time" 


Inserting a Field Manually

If you know the code for the field you want to insert and that code is relatively simple, it's often fastest to insert the field by hand. To do that, move the cursor to where you want to insert the field and then press Ctrl+F9. As you can see in Figure 1.16, Word inserts a new, empty field that includes only the braces. Type the code between the braces, as shown in Figure 1.17. When you're done, press F9 to update the field and display its result.

Figure 1.16. Press Ctrl+F9 to start a new field.


Figure 1.17. Type the field code between the braces.


Viewing and Navigating Fields

After you insert a field, Word displays the field results. If you want to do further work with any of a document's field, you need to be able to view and navigate the fields, as described in the next two sections.

Toggling Field Codes

If you want to view a field's underlying code, you need to toggle the field from showing its results to showing its code. You can use either of two methods:

  • To toggle between results and code for a single field, either click inside the field and then press Shift+F9, or right-click the field and then select Toggle Field Codes.

  • To toggle between results and code for all the document's fields, press Alt+F9.

Showing Field Codes All the Time

If you always prefer to see the field codes when you first open a document, you can force Word to display them. Select Tools, Options to display the Options dialog box, select the View tab, and then activate the Field Codes check box.


Navigating a Document's Fields

Before you can work with a field, you need to navigate to it within the document. This isn't a problem if you're dealing with only a couple of fields and you know exactly where they are. You just click inside the field and Word marks the occasion by shading the full field result. If you need to select the entire field (to move it or delete it, for example), either use your mouse to click and drag over the entire field, or move to the right of the field and press Backspace.

Controlling Field Shading

Normally, Word shows the field shading only when you click inside or select a field. If you have trouble finding your fields, you might prefer to see the field shading even when fields aren't selected. Conversely, if other people will be working with your document, you might prefer that no shading appears, making it less likely that others will edit the fields. To control the shading, select Tools, Options to display the Options dialog box, and then select the View tab. In the Field Shading list, select Never, Always, or When Selected (the default).


However, fields have a nasty habit of blending in with the surrounding text; it's easy to lose fields and have trouble finding them. Toggling all the document's fields to code can help, but many people find it easier to navigate from field to field. Word gives you two techniques to work with:

  • Press F11 to move forward to the next field in the document.

  • Press Shift+F11 to move backward to the previous field in the document.

As you navigate, Word selects each field. Unfortunately, these techniques don't wrap. That is, after you've navigated to the last field in a document, pressing F11 doesn't take you to the first field in the document; similarly, pressing Shift+F11 in the first field doesn't take you to the last field.

Updating a Field

Fields are dynamic, which means that the data underlying the field can change. For example, if you insert a field to show the current date, the underlying data changes each day. However, Word does not automatically update the field result. To update fields on-the-fly, use any of the following techniques:

  • Navigate to a field and press F9. Alternatively, right-click the field and then click Update Field.

  • To update multiple fields, select the text that includes all the fields and then press F9.

Updating All Fields with a Macro

When you're working with fields, it's common to need to update all of a document's fields at once. One way to do this is to select the entire document and press F9. This works, but it's a hassle because not only must you perform the extra step of selecting the entire document, but that extra step also means that you lose your current cursor position.

To avoid this problem, create a VBA macro that updates all the document's fields. Press Alt+F11 to open the VBA Editor, add a module to the Normal project, and then enter the sub-procedure shown in Listing 1.1 (see Figure 1.18).

Figure 1.18. Add the UpdateAllFields procedure to the Normal project to make it available for all your documents.


Listing 1.1. A Macro to Update All the Fields in the Active Document
 Sub UpdateAllFields()     ActiveDocument.Fields.Update End Sub 

Assign this macro to a toolbar button or keyboard shortcut. (I use Ctrl+Alt+Shift+F9.)

Cross-Reference

See Chapter 11, "Maximizing Office with VBA Macros," to learn how to work with the VBA Editor and create macros. To learn how to customize Word's toolbars, see Chapter 10, "Customizing Office to Suit Your Style," particularly the "Creating Custom Toolbars" section. For custom Word keyboard shortcuts, see Chapter 10's "Creating Custom Keyboard Shortcuts in Word" section.


Updating Fields When Opening a Document

It's often useful to update all of a document's fields when the document is opened. Word doesn't do that by default, but you can create a macro that does.

Launch the VBA Editor and open the project that corresponds to your document. In the project's Microsoft Word Objects branch, double-click the ThisDocument object. In the code window that appears, select Document in the object list and select Open in the event list. Add the following statement to the Document_Open() stub that appears:

 ThisDocument.Fields.Update 

Figure 1.19 shows the completed code.

Figure 1.19. Add this code to your document's Open event to update all fields each time the document is opened.


Change Your Macro Security

For a macro to work with the document's Open event, macro security must be set to Medium or Low (in Chapter 14, see the section titled "Setting the Macro Security Level"). Alternatively, apply a digital signature to the project, as described in Chapter 14's "Self-Certifying Your VBA Projects" section.


Updating Fields by Field Type

Rather than updating all the fields in a document, you might prefer to update only fields of a particular type. For example, the EditTime field displays the total time, in minutes, that the document has had the system focus (and, presumably, has been edited) since the document was created. This is the same as the Total editing time value displayed in the Statistics tab of the document's Properties dialog box (select File, Properties). If you want to track the total editing time, it's often convenient to add the EditTime field to the document rather than opening the dialog box. But if you have other fields in the document that you'd rather not update at the same time, it would be useful to be able to update only the EditTime field.

You can do this quite simply using a VBA macro. In VBA, Word's field types are implemented as constants with the following form:

 wdFieldFieldType 

Here, FieldType is the type of field, such as EditTime. So the constant for the EditTime field is wdFieldEditTime.

To put this to use, Listing 1.2 provides some code that updates only the EditTime field.

Listing 1.2. Updating the EditTime Field
 Sub UpdateEditTime()     Dim f As Field     For Each f In ThisDocument.Fields         If f.Type = wdFieldEditTime Then             f.Update             Exit For         End If     Next 'f End Sub 

This procedure runs through all the fields in the document and looks for one where the Type property is wdFieldEditTime. When the property is found, the Update method refreshes the field and then exits the For loop.

Updating Multiple Fields of the Same Type

If your document has more than one field of a particular type and you want to update all such fields, delete the Exit For statement in the code. This forces Word to loop through all the fields in the document, so each instance of the field type you want to update is found by the loop.


Updating Fields by Name

If you have a specific field you want to update, looping through all the fields to find the field's type is often inefficient. If you know the field's position within the document, you can specify the position as the index number of the Fields collection in a VBA macro. For example, the following statement updates the first field in the active document:

 ActiveDocument.Fields(1).Update 

However, that's a bit of a blunt instrument because the index numbers of the fields change as fields are added and deleted.

A better solution is to reference fields by name. You can't do this directly, but you can assign a bookmark to a field and then use the bookmark's name. For example, suppose you select the EditTime field and insert a bookmark named TotalEditTime. Then the following statement will update the field:

 ActiveDocument.Bookmarks("TotalEditTime").Range.Fields.Update 

Preventing Updates by Locking a Field

At times, you might not want a field updated. For example, you may have edited the field result, so updating the field will overwrite your changes. Similarly, if you're updating all the fields in a document, you might want to skip those fields that prompt for information. Use the following techniques to lock and unlock the current field:

  • Press Ctrl+F11 to lock the field.

  • Press Ctrl+Shift+F11 to unlock the field.

Converting a Field Result to Text

You might decide that the current field result should remain permanent. For example, you might have novice users working with the document, and you don't want them getting confused by or editing the field codes. Instead of locking all the fields, a better solution is to convert the current field results to plain text. You do that by selecting one or more fields and then pressing Ctrl+Shift+F9.

Keyboard Shortcuts for Fields

Table 1.4 provides a reference to the various keyboard shortcuts that you can use to work with fields. The table also gives the Word command equivalent for each action, in case you want to create custom toolbar buttons for those field techniques you use most often.

Table 1.4. Keyboard Shortcuts for Working with Fields

Key Combo

Command Equivalent

Action

F9

UpdateFields

Updates the selected field or fields.

Ctrl+F9

InsertField

Begins a new field.

Shift+F9

ToggleFieldDisplay

Displays the code for the selected field.

Alt+F9

ViewFieldCodes

Displays the codes for all the document's fields.

Alt+Shift+F9

DoFieldClick

Activates a GOTOBUTTON or MACROBUTTON field.

F11

NextField

Goes to the next field.

Shift+F11

PrevField

Goes to the previous field.

Ctrl+F11

LockFields

Locks the selected fields to prevent them from being updated.

Ctrl+Shift+F11

UnlockFields

Unlocks the selected field.

Ctrl+Shift+F9

UnlinkFields

Converts the selected field's result to text.


Putting Fields to Good Use

Word 2003 has a huge repertoire of fieldsmore than 70 in all. A full accounting of all the fields would require a chapter several times the length of this one. In any case, no such accounting is necessary because Word's online Help provides an excellent field reference.

Instead, the next few sections highlight a few of the most useful fields and take you through some examples that show the fields in their best and most practical light.

Viewing Total Editing Time Updated in Real-Time

Earlier I mentioned the EditTime field, which reflects the total amount of time, in minutes, that the document has been edited (or at least has held the system focus). The total amount of time that a document has been edited is useful for freelancers, lawyers, consultants, and other professionals who bill for their time. Knowing how long you have spent working on a document enables you to provide a more accurate accounting of your time.

If you have a time budget that you're trying to stick to, you may find yourself constantly checking the document's properties to view the Total editing time value. Rather than wasting time performing that chore, add the EditTime field to your document. Here's some code that displays the total editing time with the word minutes added for clarity:

 Total Editing Time: {EDITTIME \# "0 minutes" \* mergeformat } 

Now all you have to do is update the field to check the total editing time.

If even that sounds like a hassle, you can add a relatively simple macro to the document that will update the EditTime field in real-time. Open the VBA Editor and insert a module in the document's project. Add the code in Listing 1.3 to the module.

Listing 1.3. Updating the EditTime Field in Real-time
 Sub UpdateEditTime()     Dim f As Field     For Each f In ThisDocument.Fields         If f.Type = wdFieldEditTime Then             f.Update             Exit For         End If     Next 'f     Application.OnTime Now + TimeValue("00:01:00"), _         "Chapter01.Module1.UpdateEditTime" End Sub 

This procedure runs through all the fields in a document looking for one where the Type property is wdFieldEditTime, which corresponds to the EditTime field. When the property is found, the Update method refreshes the field. The key to the real-time updating is the Application.OnTime statement, which sets up the UpdateEditTime procedure to run again in one minute.

Displaying the Editing Time in the Status Bar

To constantly monitor the EditTime field as it's updated in real-time, you can place the field at the top or bottom of the document and then split the window (select Window, Split) so that the field remains visible in one pane. If that's not convenient for some reason, you can display the latest EditTime result in the status bar. In Listing 1.3, insert the following statement after the f.Update method:

 Application.StatusBar = f.Result 

The Field object's Result property returns the current result of the specified field.


Tracking the Number of Words

If you're a professional writer or editor, you may be more concerned with the number of words in your documents. This value is available in the document's Properties dialog box, in the Statistics tab. However, you can also track this value outside of the dialog box by using a field. Insert the NumWords field and use the macro techniques in this section to update the field in real-time.


Running a Macro

If you have a macro that you want to make available for yourself or other users, you can assign it a shortcut key or a toolbar button. But what if you want an in-text reference to a macro? That is, what if you want some text or an image that the user can double-click to launch the macro? You can do this using a MacroButton field:

 { MACROBUTTON MacroName DisplayText } 

Here, MacroName is the name of the macro you want to run, including the project name and module name; DisplayText is the text the user double-clicks to launch the macro. (You can also launch the macro by clicking the field and then pressing Alt+Shift+F9.)

For example, the following code creates a MacroButton field that displays Update Editing Time and runs the Chapter01.Module1.UpdateEditTime macro:

 { MACROBUTTON Chapter01.Module1.UpdateEditTime Update Editing Time } 

Figure 1.20 shows the field in a document with surrounding text. In this case, I've underlined the field text and changed the text color (it's blue) to ensure that the reader knows what text to double-click.

Figure 1.20. In this example, double-clicking the MacroButton field runs the UpdateEditTime macro to update the EditTime field.


Another way to do this is to display a small image instead of text. You do this by inserting an InsertPicture field as the MacroButton field's DisplayText property:

 { INSERTPICTURE FileName } 

Replace FileName with the full path and filename of the image you want to use. If the path contains spaces, replace each backslash (\) with double backslashes (\\). Here's an example:

 { MACROBUTTON Chapter01.Module1.UpdateEditTime { INSERTPICTURE C:\\Documents and Settings\\Paul\\My Documents\\My Pictures\\clock.jpg } } 

Figure 1.21 shows the result.

Figure 1.21. Use the InsertPicture field within a MacroButton field to have the user double-click an image to run the macro.


Creating "Click-and-Type" Text Placeholders

Another use for the MacroButton field is to create "click-and-type" text placeholders. Figure 1.22 shows some examples of what I mean. I created this document using Word's Professional Fax template. As you can see, there are placeholders such as [Click here and type name]. The idea is that you click the placeholder and then type the required text.

Figure 1.22. Word's Professional Fax template includes "click-and-type" text placeholders.


Interestingly, look what happens when you click one of these placeholders and then press Shift+F9, as shown in Figure 1.23.

Figure 1.23. The placeholders are really just MacroButton fields that reference a nonexistent macro.


As you can see, the placeholder is actually a MacroButton field:

 { MACROBUTTON NoMacro [Click here and type name] } 

The NoMacro option refers to a nonexistent macro. When you click within the field and begin to type, the field is replaced by the text.

Watch the Fake Macro Name

Make sure the fake macro name you use for the placeholder MacroButton field is not the same as any built-in or custom macro that you've created. This ensures that the user won't accidentally run the macro.


Creating a Shortcut Menu of AutoText Entries

Word's AutoText feature comes with a handy AutoComplete option. When you type the first few letters of the AutoText entry, a banner appears with the complete entry, and you press Enter to insert the full entry. (To ensure that this option is turned on, select Tools, AutoCorrect Options, display the AutoText tab, and make sure the Show AutoCorrect Suggestions check box is activated.) This is useful, but it requires knowing the available AutoText entries. The other problem is that you might prefer to choose from among a selection of AutoText entries. You can do this via the menu bar by selecting Insert, AutoText, selecting a style such as Salutation, and then selecting the entry you want. However, Word gives you a much easier way to do this, and it also solves the problem of knowing the first characters of the AutoText entries.

The solution is the AutoTextList field, which, when right-clicked, displays a menu of AutoText entries from a particular style:

 { AUTOTEXTLIST LiteralText [\s Style] [\t Tooltip] } 

Using Quotation Marks

If the LiteralText, Style, or Tooltip values contain spaces, be sure to surround them with quotation marks.


LiteralText is the text that is displayed as a prompt inside the document. The optional Style Name is an AutoText style such as Salutation or Closing. If you omit this option, Word displays all the AutoText entries. The Tooltip text option specifies the text that appears in a banner when the user hovers the mouse pointer over the field.

Following is an AutoTextList field example that displays the literal text Choose salutation and displays a list of the AutoText entries in the Salutation category:

 { AUTOTEXTLIST "Choose salutation" \s Salutation \t "Right-click to see a list of salutations" } 

Figure 1.24 shows the list that appears when the user right-clicks the field.

Figure 1.24. Use an AutoTextList field to give the user a list of related AutoText entries when he or she right-clicks the field.


Removing the Create AutoText Command

If you don't want other users to have access to the Create AutoText command that appears at the bottom of the AutoTextList shortcut menu, you can delete it. Select Tools, Customize, and then activate Shortcut Menus in the Toolbars tab. In the Shortcut Menus toolbar that appears, click Text and then click AutoTextList Field. Drag the Create AutoText command from the menu to delete it.


Building a Formula Field

Most fields return predefined results, such as document properties or the current date and time. If you have a custom calculation that you want to appear in your document, you need to build a formula field.

All formula fields have the same general structure: an equal sign (=), followed by one or more operandswhich can be a literal value, the result of another field, the contents of a bookmark, a table reference, or a function resultseparated by one or more operatorsthe symbols that combine the operands in some way, such as the plus sign (+) and the greater-than sign (>). These field formulas come in two varieties: arithmetic and comparison.

Arithmetic formulas are by far the most common type of formula. They combine operands with mathematical operators to perform calculations. I've summarized the mathematical operators used in arithmetic formulas in Table 1.5.

Table 1.5. Word's Formula Field Arithmetic Operators

Operator

Name

Example

Result

+

Addition

{ =10+5 }

15

Subtraction

{ =105 }

5

*

Multiplication

{ =10*5 }

50

/

Division

{ =10/5 }

2

%

Percentage

{ =10% }

0.1

^

Exponentiation

{ =10^5 }

100000


For example, suppose you want to know the average number of words per page in your document. That is, you need to divide the total number of words (as given by the NumWords field) by the total number of pages (as given by the NumPages field). Here's a formula field that does this:

 {= { NumWords } / { NumPages } } 

A comparison formula is an expression that compares two or more numeric operands. If the expression is true, the result of the formula is 1. If the statement is false, the formula returns 0. Table 1.6 summarizes the operators you can use in comparison formulas.

Table 1.6. Word's Formula Field Comparison Operators

Operator

Name

Example

Result

=

Equal to

{ =10=5 }

0

>

Greater than

{ =10>5 }

1

<

Less than

{ =10<5 }

0

>=

Greater than or equal to

{ =10>=5 }

1

<=

Less than or equal to

{ =10<=5 }

0

<>

Not equal to

{ =10<>5 }

1


For example, suppose you want to know whether a document's current size on disk (as given by the FileSize field) is greater than 50,000 bytes. Here's a comparison formula field that checks this:

 {= { FileSize } > 50000 } 

Finally, Word also offers a number of functions that you can plug into your formula fields. Table 1.7 lists the available functions.

Table 1.7. Word's Formula Field Functions

Function

Returns

ABS(x)

The absolute value of x.

AND(x,y)

1 if both x and y are true; 0 otherwise.

AVERAGE(x,y,z,...)

The average of the list of values given by x,y,z,....

COUNT(x,y,z,...)

The number of items in the list of values given by x,y,z,...

DEFINED(x)

1 if the expression x can be calculated; 0 otherwise.

FALSE

0.

INT(x)

The integer portion of x.

MIN(x,y,z,...)

The smallest value in the list of values given by x,y,z,....

MAX(x,y,z,...)

The largest value in the list of values given by x,y,z,....

MOD(x,y)

The remainder after dividing x by y.

NOT(x)

1 is x is false; 0 if x is true.

OR(x,y)

1 if either or both x and y are true; 0 if both x and y are false.

PRODUCT(x,y,z,...)

The result of multiplying together the items in the list of values given by x,y,z,....

ROUND(x,y)

The value of x rounded to the number of decimal places specified by y.

SIGN(x)

1 if x is positive; 1 if x is negative.

SUM(x,y,z,...)

The sum of the items in the list of values given by x,y,z,....

trUE

1.


Suppose you want to know whether your document has more than 1,000 words (as given by the NumWords property) or more than 100 lines (as given by the DocProperty Lines field). Here's a formula field that checks this using the OR function:

 { = OR( { NumWords } > 1000, { DOCPROPERTY Lines } > 100) } 

Calculating Billable Time Charges

You saw earlier that you use the EditTime field to return the total editing time for a document. If you bill by the hour based on the amount of time you have worked on a document, you might want to keep track of how much money you've earned so far. If you earn, for instance, $100 per hour, the following formula displays your current billable earnings:

 { = { EDITTIME } / 60 * 100 } 

The EditTime result is given in minutes, so you have to divide by 60 to get the number of hours. You then multiply that result by 100 to get the earnings.

To ensure accurate billing, you may want to use the ROUND function to round the result to the nearest dollar:

 { = ROUND( { EDITTIME } / 60 * 100, 0) \#$0.00 } 

This formula field also uses a numeric picture to format the result with a dollar sign and two decimal places, as shown in Figure 1.25.

Figure 1.25. A formatted formula field that calculates the billable charge based on the current EditTime result.


Creating Decision-Making Fields

One of the most powerful fields is the If field, which compares two expressions and then returns one of two values depending on the result:

 { IF Expression1 Operator Expression2 TrueResult FalseResult } 

Expression1 and Expression2 are operands, and Operator is one of the comparison operators listed in Table 1.6. If the result of this comparison operation is true, the field displays the trueResult text; if the result of this comparison operation is false, the field displays the FalseResult text.

For example, here's a field that checks the NumWords field to see whether it's greater than 1,000:

 { IF { NumWords } > 1000 "Over word count!" "Word count okay" } 

If the NumWords result is greater than 1,000, the field displays Over word count!; if the NumWords result is less than or equal to 1,000, the field displays Word count okay.

Prompting the User for Input

With many templates, the user is required to fill in certain document properties, such as the title, subject, author, or keywords. Ensuring that these values are entered can be a crucial part of a document management system. One way to do this is to use a Fill-in field, which displays a dialog box that prompts the user for data. The entered data is then displayed as the field result:

 { FILLIN Prompt } 

Prompt is the text that appears as a prompt in the dialog box. Here's an example:

 { FILLIN "Please enter the document title:" } 

If you insert this field in a template, Figure 1.26 shows the dialog box that appears when the user creates a new document based on the template.

Figure 1.26. When you update a Fill-in field, Word displays a dialog box similar to this one.


Although it may occasionally be useful to store user input in the document (see, for example, Chapter 6's "Personalizing Mail Merges with Fill-in Fields"), what if what you really want to do is change the actual document properties? Because each document property has its own field type, you can change many properties by specifying the Fill-in result as the new property value. For example, the following code prompts the user for a document title and then stores the result in the Title property using the Title field:

 { TITLE { FILLIN "Please enter a document title:" } } 

Hiding the Fill-in Result

Unfortunately, the result of the Title field appears in the document text. To avoid this, you can hide the result by placing everything inside a Seq field. You normally use this field to create a sequential numbering system, but it comes with a \h switch that hides the field. Here's the hidden form of the Fill-in field:

 { SEQ \h { TITLE { FILLIN "Please enter a document title:" } } } 


Prompting to a Bookmark with Ask

Word also comes with an Ask field type. This works the same as Fill-in, except that the result is stored in a bookmark:

 { ASK Bookmark Prompt } 




Tricks of the Microsoft Office Gurus
Tricks of the Microsoft Office Gurus
ISBN: 0789733692
EAN: 2147483647
Year: 2003
Pages: 129

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net