Repeating Data (or populating fields)

Home Up Odds & Ends Photo Gallery Search Contact Me

 

 

The information in this website is provided without risk or obligation and free of charge.  However, if you have benefitted from my efforts here and would like to make a contribution to help me continue and maintain this work then any donation will be greatly appreciated. Please click the adjacent button to access PayPal.  Thank you.
 

This Microsoft Word Help & Tips 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 will simply send you on to existing web articles containing full explanations of some of the more comprehensive methods.   See paragraph 7 if you want to go directly to information about the exciting new Content Controls in Word2007.

1.  UserForm.  .  A UserForm is a provides a graphical UserInterface with a document template with prompts for all pertinent information required to complete a Word form.  An introduction to UserForms and an index to UserForm Frequently Asked Questions (FAQS) can be found in the article "How to Create a UserForm" at: Microsoft Word MVP FAQ (then click the User Form tab), also see my: 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 Online (Protected)  Form.  Online 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 "most1" other designated "like" fields automatically.  Here is a quick sample to whet your curiosity.

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

   b.  Type - Customer Name and then insert a text form field.

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

       Tip:  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.      

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

     Tip - You can easily enter REF fields by just typing and selecting the text "REF Text1" and then pressing CTRL+F9.

   e.  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 you entered in your form field.

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

   g.  Some additional notes and complications.

       (1)  In the introduction to this section I stated that Word will fill in or populate "most" other designated "like" fields automatically.  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 arounds.  You can use a STYLEREF field as described in MVP Suzanne Barhhill's presentation on STYLEREF fields, or you can run a macro on exit from the field that will update all of the fields, including REF Fields, anywhere in a docuement.   For more on macros for working with the field collection in Word, see:  Field Macros.

       (2)  For reasons to complicated to go into here, REF and other field codes will not be updated using "calculate on exit" if the REF field is located after a TOC field in the document.  There are a few work arounds.  Provided that you don't need the TOC to update after protecting the document you can simply lock the TOC field (select it and press CTRL+F11) before protecting the document.  When you need to update the TOC you can unprotect the form and unlock the TOC with CTRL+SHIFT+F11.  If it is essential that the TOC itself be updated based on formfield text changes then you can use the following method shown to me by regular newgroup contributor "Macropod."   

    * Here a SET field located after the last REF field in the document is used to hold the TOC field and effectively hide it from view at this location.  A reference to MyTOC is used where the TOC should appear.   When field codes are toggled the display looks like this.

3.  Bookmark.  A third quick and simple method is to select and bookmark the text you want repeated and use REF fields as described above. 

   a.  Insert>Bookmark opens the Bookmark dialog box.  Here we adding a bookmark named "cName."    

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

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

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

4.  OLE Link Simply copy the text you want repeated and paste it in the repeated location use Edit>Paste Special.  Paste as Formatted or Unformatted text and select the radio button "Paste link."  This automatically creates a bookmark at the source location and creates a Link field and the destination locations.
5.  DocProperty.  Nearly all of the methods described above apply a cross reference to bookmarked text.  Each has its advantages and disadvantages.  Even the most basic User Form requires rudimentary VBA macros, the Online Form is protected with accompanying limitations, and the simple bookmarked text can be accidentally deleted.   A DocProperty is simple to use and much less prone to be accidentally altered or deleted.  There are two types of DocProperties, built-in and custom.  To view and apply DocProperties, click File>Properties.  The Summary tab lists built in DocProperty names, the Custom tab list a dozen or so pre-named properties.  Both tabs provide the user interface for storing document information as properties.   Now on to the exercise.      
   a.  Open the Properties dialog (File>Properties).

        1) Click the Summary tab.

        2) Type in some information in the property fields.

        3) Click OK

 

   b.  Open the Properties dialog.

        1) Click the Custom tab.

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

        3) Apply a type (text is default)

        4) Type in a value

        5) Click Add, then OK

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

        Tip - Use of the field name "DocProperty" is optional with built in DocProperties.

   c.  Built in and custom DocProperty fields can be used once or multiple times in each document to populate form entries and repeat text.  When all of your fields are entered simply right click and press update fields.
6.  User Prompts.  Many people ask "How can I set up my document or template so that I am prompted to enter information when I open the document or create a new document."  The best answer to this question is to send you back to the the User Form.  It is the Cadillac interface between the human user and the Word form.  Still there are alternatives.  Each with its advantages and disadvantages.  All are best employed using a template vice individual documents.  
       a.  FILLIN Field.  A FILLIN field fires a prompt when a new document is created based on a template containing the FILLIN field, when a document containing a FILLIN field is opened, and (very unfortunately) when you print a document containing a FILLIN field if the "Update Fields" option is checked in File>Print>Options>Printing Options.  That is it.  There is no bookmark associated with the FILLIN field. 

       Tip - You can of course nest the Fillin field in a Set field to create a bookmark and use REF fields as described in the bookmark method above or ASK method below (e.g., { SET Name{Fillin "What is your name?"}{REF Name}).   

     b.  ASK and REF.  An ASK field fires a prompt when the field is specifically instructed to update.  Like the FILLIN field, this unfortunately occurs when you print.  Unlike a FILLIN fields, ASK fields do not automatically fire the prompt when a new document is created or when an existing document is opened.  In addition to firing a prompt, the ASK field sets a bookmark.  The bookmark value can then be employed with REF fields to populate multiple fields with repeating data.  In this example the ASK field sets the bookmark value "Name."  The bookmark is used with REF fields to populate the form.  Like most Word fields, the ASK field can be updated (and therefore fire the prompt) by selecting the field and pressing F9.  You can update all fields in a document by pressing CTRL+a and then F9.

    Tip - A simple line of VBA code in an AUTONEW and AUTOOPEN macro stored in the template can be used to make ASK fields autofire:  ActiveDocument.Fields.Update 

7.  Word2007 & Content Controls.  This is relatively new territory for me and I am not certain that I will ever completely grasp XML mapping and all the benefits that it holds.    It is beyond the scope of this page to try a complete explanation of content controls or the "under the hood" technical aspects of how these new controls are bound to XML data stored in the new OfficeOpenXML file format.   What I can do is offer what I have managed to discover through experimentation.

    a.  A very simple method of repeating data in a Word2007 document without knowledge of any XML or VBA is to use the built-in Document Property content controls.  These are a collection of pre-defined content controls on the Quick Part>Document Property menu.  The "titles" can be changed to whatever you like.  For example, let's create a repeating content control for a client name.  Use the Insert ribbon to select Quick Parts then Document Properties then pick one of the predefined content controls.  I used "Comments."     

    

     - This inserts a content control titled "Comments" at the IP just after the text "Client Name:  " which I had previously typed in the document.

     - Selecting the content control and using the Devoper tab>controls group>properties, open the content control properties dialog and assign "Client Name" to the control title property.  The click OK.

     - Click in the pre-defined placeholder text and change it to suit your needs.

     - Select and copy the content control then paste it to the other location you want Client_Name to appear.

     - Changing any of the content control contents will automatically repeat over all the controls.

     - You can use the content control properties dialog box to prevent direct editing in one or more of the individual controls.
     - Remember this method employs the content control designed for the built-in document property "Comments."  While we have renamed it "Client Name," it still manages the document property "Comments."  If you use a { DocProperty "Comments" } field in the document it will display the value set in the content control.  If you change the value of the content control the value of the document propertry is automatically updated.  However, any DocProperty field will not display the changed value until the field is updated.

     b.  While the method above is well suited for simple forms it will fall short if there are more independent data fields in your form than the 15 pre-defined content controls or if your need one of those to serve its specific intended purpose.  This next method employs VBA and an Event procedure.  Copy the following code to the "This Document" class of your form's VBA project:     

Private Sub Document_ContentControlOnExit(ByVal currentCC As ContentControl, Cancel As Boolean)
Dim oDoc As Word.Document
Dim rngStory As Word.Range
Dim oCCs As Word.ContentControls
Dim oCC As Word.ContentControl
Set oDoc = ActiveDocument
For Each rngStory In oDoc.StoryRanges
    Do
        Set oCCs = rngStory.ContentControls
        For Each oCC In oCCs
            If oCC.Title = currentCC.Title Then
                oCC.LockContents = False
                oCC.Range.Text = currentCC.Range.Text
            End If
        Next oCC
        Set rngStory = rngStory.NextStoryRange
    Loop Until rngStory Is Nothing
Next rngStory
Set oDoc = Nothing
Set oCCs = Nothing
Set oCC = Nothing
End Sub

     - Insert and assign a title to a content control.  Copy the control and paste it where the data will be repeated.  The procedure above runs on exit from each content controls.  All like named controls will update to value entered in the current control. 

NOTE - Based on what I have learned since first publishing this page, the method above is the least favorable.  I have experienced some buggy behaviour with Document_ContentOnExit event and the method requires VBA in the activedocument and all the security baggage that contains.  I have left it here just for illustrative purposes.

     c.  The real power of content controls lies in their ability to be bound (or mapped), just like the document properties described above are mapped,  to an XML data store contained in the new OfficeOpenXML file format.  Through this binding, any changes in the datastore data is automatically repeated in all content controls mapped to that data and changes to a content control automatically updates the datastore and all other content controls mapped to that datastore data.  As I mentioned at the start of this section XML is not my strong suit.  However, here is a basic example of using content controls and mapping to XML data:
    -  Open a new document and insert a couple of labels and content controls.  Let's call one Client_Name and the other Client_ID as shown below:   

   - Add the following code to the template VBA project.  When the code is executed (execute it!), it creates the XML datastore in the document and maps the two content controls to that data.  oCC(1) represents our "Client_Name" control.  It is mapped to element1 of the datastore.  oCC(2), Client_ID, is mapped to element2 of the data store. 
     Sub AddCustomXMLPartAndMapCCs()
     Dim oCustPart As CustomXMLPart
     Dim oCCs As ContentControls
     Set oCustPart = ActiveDocument.CustomXMLParts.Add
     Set oCCs = ActiveDocument.ContentControls
     oCustPart.LoadXML ("<docparts><element1>Click and enter Client_Name</element1>" & _
          "<element2>Click and enter Client_ID</element2></docparts>")
     oCCs(1).XMLMapping.SetMapping _
          "/docparts/element1", , oCustPart
     oCCs(2).XMLMapping.SetMapping _
          "/docparts/element2", , oCustPart
     Set oCCs = Nothing
     End Sub
The source XML for the procedure above is embedded in the VBA procedure itself.  It is the data starting with ("<docparts>  and ending with </docparts").  There is nothing magic about it.  I just made it up.  It coud have just as easily started with ("<bologna_sandwich> and ended with </bologna_sandwich>").   

The intial XML can also be loaded from an external XML file.    For example, here is the text of an external XML file saved on my harddrive as "C:\mySillySample.xml"

     <bologna_sandwich>
     <pickle1>Click to enter Client Name</pickle1>
     <pickle2>Click to enter Client ID</pickle2>
     </bologna_sandwich>
We could map our two content controls using this external XML file as follows:
     Sub AddCustomXMLFromExtSourceAndMapCCs()
     Dim oCustPart As CustomXMLPart
     Dim oCCs As ContentControls
     Set oCustPart = ActiveDocument.CustomXMLParts.Add
     Set oCCs = ActiveDocument.ContentControls
     oCustPart.Load ("C:\mysample.xml")
     oCCs(1).XMLMapping.SetMapping "/bologna_sandwich/pickle1", , oCustPart
     oCCs(2).XMLMapping.SetMapping "/bologna_sandwich/pickle2", , oCustPart
     End Sub
Running either code establishes and XML datastore in the document file.  There is really no further need for the VBA or the external XML file.
With the content controls mapped you can now copy and paste either content control to other points in the document.  Changes made in any content control will update the data store and all like named content controls. 

Update: I have learned a little more about XML and I have put together a convient ADDIn that lets you easily create and map content controls.  See:  Create and Map Content Controls

8.  In addition to the methods above, VBA can be used to automatically set document properties, variables, and bookmarks in a new or existing document and update corresponding fields.  You can download a template here that contains a sample AutoOpen and AutoNew macros to set properties, variables, and fields for automating a Word form.  Template

Looking for something else?

Google