repeating data (populating multiple fields) in ms word

13
(A Microsoft Word Help & Tip page by Gregory K. Maxey) This Microsoft Word Tips & Microsoft Word Help page offers several solutions to the question, "How do I enter data in one place in a document and have it automatically repeated in other places?" My intention is not to reinvent the wheel, so after a brief introduction I may simply send you on to an existing tips page or other web article containing full explanations of some of the more comprehensive methods. See section 7, Content Controls, if you want to go directly to information about the new Content Controls introduced in Word 2007. 1. Userform A Userform provides a graphical User Interface (UI) with a document template which you can use to prompt your document user to enter all pertinent data. User entered data is then populated in one or multiple locations in the document. See: Microsoft Word MVP Userform FAQs for an index of Userform Frequently Asked Questions (FAQS). A basic introduction and example Userform is contain in the article " How to Create a Userform." For more in-depth examples see my Create and employ a Userform, Custom VBA\Userform Message Box and Validate Userform Text Entry. 2. On-Line Form If you find a Userform daunting, or if you want to avoid VBA and macros, then you might try a Word on-line (protected) form. On-line forms are Word documents that have "fill in the blanks." They are like a pre-printed form with "fields" on the screen instead of blank lines on paper. The beauty of on-line forms is that you can fill in one field and Word will fill in or populate " most" other designated "like" fields automatically. An example of an on-line form is provided in the following demonstration project. On-Line Form demonstration Note: While this demonstration and illustrations were created using Word 2003, the method is wholly functional in Word 2007/2010/2013. If you plan to use On-line (protected) forms in Word 2007/2010/2013 see my: Classic Form Controls. Open a new blank document. Click View>Toolbars>Forms. The forms toolbar opens. Type - "Customer Name " and then insert a text form field using the forms toolbar. Double click the text form field to display the options dialog. Note the bookmark name (Text1) and check "calculate on exit." Note: Text1 is the default name for the first text form field inserted in the document. You can change this name to practically whatever you want to better suit your application. PrintWhatYouLike on Repeating Data (Populating Multiple Like Fields) http://www.printwhatyoulike.com/print?url=http://gregmaxey.mvps.or... 1 of 13 10-09-2014 15:52

Upload: baanaadi

Post on 14-Dec-2015

243 views

Category:

Documents


1 download

DESCRIPTION

This document offers several solutions to the question, "How do I enter data inone place in a document and have it automatically repeated in other places?"

TRANSCRIPT

Page 1: Repeating Data (Populating Multiple Fields) in MS Word

(A Microsoft Word Help & Tip page by Gregory K. Maxey)

This Microsoft Word Tips & Microsoft Word Help page offers several solutions to the question, "How do I enter data inone place in a document and have it automatically repeated in other places?" My intention is not to reinvent the wheel,so after a brief introduction I may simply send you on to an existing tips page or other web article containing fullexplanations of some of the more comprehensive methods. See section 7, Content Controls, if you want to go directly toinformation about the new Content Controls introduced in Word 2007.

1. UserformA Userform provides a graphical User Interface (UI) with a document template which you can use to prompt yourdocument user to enter all pertinent data. User entered data is then populated in one or multiple locations in thedocument.

See: Microsoft Word MVP Userform FAQs for an index of Userform Frequently Asked Questions (FAQS).

A basic introduction and example Userform is contain in the article "How to Create a Userform."

For more in-depth examples see my Create and employ a Userform, Custom VBA\Userform Message Box andValidate Userform Text Entry.

2. On-Line FormIf you find a Userform daunting, or if you want to avoid VBA and macros, then you might try a Word on-line (protected)form.

On-line forms are Word documents that have "fill in the blanks." They are like a pre-printed form with"fields" on the screen instead of blank lines on paper.

The beauty of on-line forms is that you can fill in one field and Word will fill in or populate "most" otherdesignated "like" fields automatically. An example of an on-line form is provided in the followingdemonstration project.

On-Line Form demonstration

Note: While this demonstration and illustrations were created using Word 2003, the method is wholly functional inWord 2007/2010/2013. If you plan to use On-line (protected) forms in Word 2007/2010/2013 see my: Classic FormControls.

Open a new blank document. Click View>Toolbars>Forms. The forms toolbar opens.

Type - "Customer Name " and then insert a text form field using the forms toolbar.

Double click the text form field to display the options dialog. Note the bookmark name (Text1) and check"calculate on exit."

Note: Text1 is the default name for the first text form field inserted in the document. You can change this nameto practically whatever you want to better suit your application.

PrintWhatYouLike on Repeating Data (Populating Multiple Like Fields) http://www.printwhatyoulike.com/print?url=http://gregmaxey.mvps.or...

1 of 13 10-09-2014 15:52

Page 2: Repeating Data (Populating Multiple Fields) in MS Word

Now enter one or more REF fields in your document where you want to repeat the customer name. REFfields fill the role of the "like" fields I mentioned earlier.

Note: When adding your REF fields remember they must point to the correct target. If you rename your formfield's bookmark name (e.g., from Text1 to Customer) then your REF field must point to Customer e.g., {REFCustomer }.

Bonus Tip: You can quickly enter REF fields by typing and selecting "REF Text1" (excluding the quotes) and thenpressing CTRL+F9.

After you have entered one or more REF Text1 fields, press the Protect Form icon on the Forms tool bar.Type a name in the form field and press TAB. Word will populate the REF Text1 fields with the name youentered in your form field.

Word Online Forms are a powerful tool. A detailed and very informative series of articles by Dian Chapmanon using Online Forms can be accessed from links on the following Word MVP FAQ page: I'm designing aform that needs to have "fill-in-the-blanks" lines. What is the best way to create them?

Additional notes and complications.

1. In the introduction to this section I stated that Word will fill in or populate "most" other designated "like" fieldsautomatically. REF fields that are located outside the main text range of the document (e.g., headers, footers, text boxes,etc.) will not automatically update on exit from the field. However, there are some well suited work a rounds. You can use aSTYLEREF field as described in MVP Suzanne Barnhill's presentation on STYLEREF fields, or you can run a macro on exitfrom the field that will update all of the fields, including REF Fields, anywhere in a document. For more on macros forworking with the field collection in Word, see: Field Macros.

PrintWhatYouLike on Repeating Data (Populating Multiple Like Fields) http://www.printwhatyoulike.com/print?url=http://gregmaxey.mvps.or...

2 of 13 10-09-2014 15:52

Page 3: Repeating Data (Populating Multiple Fields) in MS Word

2. For reasons too complicated to go into here, REF and other field codes will not be updated using "calculate on exit" if theREF field follows a TOC field in the document. Provided that you don't need the TOC to update after protecting thedocument, you can simply lock the TOC field (select it and press CTRL+F11) before protecting the document. When youneed to update the TOC you can unprotect the form and unlock the TOC with CTRL+SHIFT+F11. If it is essential that theTOC itself be "dynamic" and updated based on real time formfield text changes then you can use the method illustratedbelow.

Document TOC field is physically located following last REF field

Visible TOC is displayed by the REF field

Process requires a bit of VBA

PrintWhatYouLike on Repeating Data (Populating Multiple Like Fields) http://www.printwhatyoulike.com/print?url=http://gregmaxey.mvps.or...

3 of 13 10-09-2014 15:52

Page 4: Repeating Data (Populating Multiple Fields) in MS Word

Code to execute

3. BookmarksProbably the easiest method is to simply select and bookmark the text you want repeated and use REF fields asdescribed above.

The menu sequence Insert>Bookmark opens the Bookmark dialog box. Here we are creating a bookmark"bmCompanyName."

Create the REF fields as described above, right click, and select update field

Bonus Tip: Use of the field name REF is optional in cross references to bookmark names (i.e., you can use { REFbmCompanyName } or simply {bmCompanyName} as I have done in this example).

Bonus Tip: If you change the bookmark value, simply press CTRL+a to select all fields and press F9 to update.

PrintWhatYouLike on Repeating Data (Populating Multiple Like Fields) http://www.printwhatyoulike.com/print?url=http://gregmaxey.mvps.or...

4 of 13 10-09-2014 15:52

Page 5: Repeating Data (Populating Multiple Fields) in MS Word

4. OLE LinkSimply copy the text you want repeated and paste it in the repeated location use menu sequence Edit>Paste Special.Paste as Formatted or Unformatted text and select the radio button "Paste link." This automatically creates a bookmarkat the source location and creates a Link field at the destination locations.

5. DocPropertyNearly all of the methods described above apply a cross reference to bookmarked text. Each has its advantages anddisadvantages.

Even the most basic User Form requires rudimentary VBA macros.Online form must be protected with accompanying limitationsBookmarked text is easily and accidentally deleted

A DocProperty is simple to use and much less prone to be accidentally altered or deleted. There are two types ofDocProperties, built-in and custom. To view and apply DocProperties, click File>Properties. The Summary tab lists built inDocProperty names, the Custom tab list a dozen or so pre-named properties. Both tabs provide the user interface forstoring document information as properties.

DocProperty demonstration

Open the Properties dialog (File>Properties).

Click the "Summary" tab.

Fill in the Title, Subject, and Author fields then click "OK"

PrintWhatYouLike on Repeating Data (Populating Multiple Like Fields) http://www.printwhatyoulike.com/print?url=http://gregmaxey.mvps.or...

5 of 13 10-09-2014 15:52

Page 6: Repeating Data (Populating Multiple Fields) in MS Word

Open the Properties dialog (File>Properties).

Click the "Custom" tab.

Type in a unique custom property name (e.g., badge number).

Apply a type (text is default).

Type in value value (e.g., 0001).

Click "Add" then click "OK".

PrintWhatYouLike on Repeating Data (Populating Multiple Like Fields) http://www.printwhatyoulike.com/print?url=http://gregmaxey.mvps.or...

6 of 13 10-09-2014 15:52

Page 7: Repeating Data (Populating Multiple Fields) in MS Word

Now create your fields. We are going to use the three built in fields (Title, Subject, Author) and the customproperty (Badge Number) with { DocProperty } fields to populate a form.

Note: Use of the field name "DocProperty" is optional with built-in DocProperties. Field name required withcustom document properties and property name must be enclosed in quotes.

Built in and custom DocProperty fields can be used once or multiple times in each document to populateform entries and repeat text. When all of your fields are entered simply select all (CTRL+a) and F9 to updatethe fields.

6. Automatic User PromptsMany people ask "How can I set up my document or template so that I am prompted to enter information when I openthe document or create a new document." The best answer to this question is to send you back to the Userform. It isthe Cadillac interface between the human user and the Word form. Still there are alternatives. Each with its advantagesand disadvantages. All are best employed using a template vice individual documents.

FILLIN field

A FILLIN field fires a prompt when a new document is created based on a template containing the FILLINfield, when a document containing a FILLIN field is opened, and (very unfortunately) when you print adocument containing a FILLIN field if the "Update Fields" option is checked in File>Print>Options>PrintingOptions. There is no bookmark associated with the FILLIN field.

Bonus Tip: You can of course nest a FILLIN field in a Set field to create a bookmark and use REF fields asdescribed in the bookmark method above or ASK method below (e.g., { SET Name{FILLIN "What is yourname?"}{REF Name}).

PrintWhatYouLike on Repeating Data (Populating Multiple Like Fields) http://www.printwhatyoulike.com/print?url=http://gregmaxey.mvps.or...

7 of 13 10-09-2014 15:52

Page 8: Repeating Data (Populating Multiple Fields) in MS Word

ASK & REF fields

An ASK field fires a prompt when the field is specifically instructed to update. Like the FILLIN field, thisunfortunately occurs when you print.

Unlike a FILLIN fields, ASK fields do not automatically fire the prompt when a new document is created orwhen an existing document is opened.

In addition to firing a prompt, the ASK field sets a bookmark. The bookmark value can then be employedwith REF fields to repeat data in multiple fields.

In the illustration that follows, the ASK field sets the bookmark value "bmName." The bookmark is used withREF fields to populate the form.

Like most Word fields, the ASK field can be updated (and therefore fire the prompt) by selecting the fieldand pressing F9 or update all document fields by pressing CTRL+a and then F9.

Bonus Tip: The following single line of VBA code in a template AUTONEW or AUTOOPEN macro can be used toauto fire the template ASK field: "ActiveDocument.Fields.Update

7. Content ControlsContent Controls (CCs) are a feature introduced with Word 2007. While they have some room to grow, they are alreadyincredibly versatile and will most likely meet or exceed your needs for repeating data in a document.

The real power of content controls lies in their ability to be bound (or mapped) to a custom XML data node contained inthe new OfficeOpenXML file format. Through this binding:

All CCs mapped to a unique data node reflect the same value.If you change the value in a document CC that is mapped to a data node then the data node value is alsoupdated and changed.Consequently, all other CCs mapped to that data node are updated and changed.

Do you see the huge impact and advantage? This means that "any and all" of your repeated data fields can serve as amaster data field. For example, if you are at the end of a long document and notice a misspelling in a client name youcan change it then and there and all previous mapped CCs will update!! You don't have to plow back to the beginning ofyour document, reopen a form or property dialog, to update data.

PrintWhatYouLike on Repeating Data (Populating Multiple Like Fields) http://www.printwhatyoulike.com/print?url=http://gregmaxey.mvps.or...

8 of 13 10-09-2014 15:52

Page 9: Repeating Data (Populating Multiple Fields) in MS Word

Built-in Document Property Content Controls

A very simple method of repeating data with content controls without requiring any knowledge of any XMLand VBA programing skills or other third party tools is to use the built-in Document Property content controlscollection.

The collection consists of 15 pre-defined content controls mapped to internal data nodes in theOpenOfficeXMLFormat file structure of the document.

Insert the controls in your document using the Insert tab>Text>QuickParts> Document Property menu.

Note: These controls are actually mapped to the 15 like named built-in document properties and they canprovide an effective way to manage those properties. If you insert one and enter a value and then go look at thedocument properties dialog it should come as no surprise to see the data reflected there.

But hey, its your application, use it in whatever way make your work easiest. If you need a repeating datafield and don't have need for the document property "Abstract" (for example), insert the "Abstract" control inyour document, use the Developer tab>Controls>Properties dialog to rename it to suit your needs and yourjob is done.

Insert Document Property Content Control

Assign a meaningful title using CC Properties dialog

PrintWhatYouLike on Repeating Data (Populating Multiple Like Fields) http://www.printwhatyoulike.com/print?url=http://gregmaxey.mvps.or...

9 of 13 10-09-2014 15:52

Page 10: Repeating Data (Populating Multiple Fields) in MS Word

VBA Script: Copy to clipboard

Define placeholder text as required.

Copy and past CC as required.

Change one and they all change!!

Remember the method discussed above employs the content control designed for the built-in document property"abstract." While we have renamed it "Client Name," it still manages the document property "Abstract." If you shoulduse a { DocProperty "Abstract" } field in the document it will display the value set in the content control. If youchange the value of the content control the value of the document property is automatically updated. However, anyDocProperty field will not display the changed value until the field is updated.

Simple Linked Content Controls

While not actually mapped, the following quick and simple method was suggested by Aaron Marin via user feedback onthis page:

Insert a plain text content control.Select the control (by clicking the small control tab)then Developer>ontrols>Properties and define a title for the control.Right click and select "Copy."Position the cursor where you need the text repeated.Using the Home tab click Paste>Paste Special and select the "Paste link" option button. Then in the "As" dropdown select"Unformatted Text" and click "OK."Now anytime the text is changed in the initial control and you exit the control all of the linked copies will update.

Note: Unfortunately the simply linked controls are very fragile not really practical in most situations. If you save thefile with a new name, the link between the controls is broken. I've left left the method posted here for informationalpurposes.

Advanced Custom Mapping

A full blown discussion of the VBA and "under the hood" workings of the XML data store are beyond the scope of thistips page. A good understanding of both are required should you decide to roll up your sleeves and create your owndetailed custom content control data store. However, just for for the sake of completeness, the following VBA script willallow you to create multiple content controls mapped to a single data node:

Sub AddContentControlAndMap()

PrintWhatYouLike on Repeating Data (Populating Multiple Like Fields) http://www.printwhatyoulike.com/print?url=http://gregmaxey.mvps.or...

10 of 13 10-09-2014 15:52

Page 11: Repeating Data (Populating Multiple Fields) in MS Word

Dim oCC As Word.ContentControlDim oCustomPart As Office.CustomXMLPart'All new documents already have 3 reserved customXMLParts built-in. We create\use the 4th one.'If it doesn't exist (and it wont' the first time this code is run _ then we will throw an error and use that error to create it.On Error GoTo Err_NoXMLPartSet oCustomPart = ActiveDocument.CustomXMLParts(4)Err_ReEntry:'Create the CC at the selection.Set oCC = ActiveDocument.ContentControls.Add(wdContentControlText)With oCC 'Give it at title .Title = "My Mapped CC" 'Map the CC to the customXMLPart data node. .XMLMapping.SetMapping "/ccMap/ccData[1]"End WithExit SubErr_NoXMLPart:'Define the customXMLPart and data node.Set oCustomPart = ActiveDocument.CustomXMLParts.Add("<ccMap><ccData></ccData></ccMap>")

See: Installing Macros for instructions on how to set up and use the macros in this tips page.

By adding additional child nodes to the basic XML and judicious management of the mapping, you could dozens orhundreds of content controls linked to dozens or hundreds of unique data nodes.

For your convenience I have included tools for simplifying content control mapping in a Word Template add-in: ContentControl Tools.

8. StyleRef FieldsThe StyleRef Field is particularly handy for repeating/displaying main body text defined by a specific style in a header or footer. A basicexample is repeating text defined using the "Title" style shown below:

Field code

Field result

The text returned by a StyleRef is defined by several factors 1) the style name 2) applied switches, and 3) field locationin the document. In the following example I have created a character style named WordDef and applied it to first word

PrintWhatYouLike on Repeating Data (Populating Multiple Like Fields) http://www.printwhatyoulike.com/print?url=http://gregmaxey.mvps.or...

11 of 13 10-09-2014 15:52

Page 12: Repeating Data (Populating Multiple Fields) in MS Word

in each listed definition:

When the fields result is displayed the resulting text is evaluated according to the following rules:

Word searches the current page, from top to bottom, for the specified style.If the style isn't found, Word searches next from the top of the page to the beginning of the document, andthen from the bottom of the page to the end of the document.If the \l switch is used, Word searches from the bottom of the page to the beginning and then to the end ofthe document.

Note: The style referenced must be applied to text in the main body of the document. Otherwise the field will return"Error - No text of specified style found in document."

For a full list of StyleRef field switch and position behavior, see: StyleRef Field

9. Document VariablesLastly, the "Hidden Gems" in Word, Document Variables. Created, edited and destroyed only with VBA, DocumentVariables provide a robust method for storing information. This stored information remains part of the document and isready for repeated using even if a document is closed and then reopened. This information is easily retrieved anddisplayed in your document using the DocVariable field. The following template contains examples of the documentvariable and DocVariable fields used to create a simple form. The template also provides examples of setting documentproperties using VBA: VBA Template.

Note: For more on document variables, see my: Create and Employ a Userform.

PrintWhatYouLike on Repeating Data (Populating Multiple Like Fields) http://www.printwhatyoulike.com/print?url=http://gregmaxey.mvps.or...

12 of 13 10-09-2014 15:52

Page 13: Repeating Data (Populating Multiple Fields) in MS Word

That's it! I hope you have found this tips page useful and informative.

PrintWhatYouLike on Repeating Data (Populating Multiple Like Fields) http://www.printwhatyoulike.com/print?url=http://gregmaxey.mvps.or...

13 of 13 10-09-2014 15:52