Personal website of Gregory K. Maxey, Commander USN (Retired)
Do you have ad-blocking software enabled? While I respect your right to do so, your donations and the minimal advertisements on this site help to defray internet and other costs of providing this content. Please consider excluding this website from blocking or turning off the blocker while browsing this site.
The information, illustrations and code contained in my "Microsoft Word Tips" are provided free and without risk or obligation.
However, the work is mine. If you use it for commercial purposes or benefit from my efforts through income earned or time saved then a donation, however small, will help to ensure the continued availability of this resource.
If you would like to donate, please use the appropriate donate button to access PayPal. Thank you!
The purpose of this Microsoft Word Tips & Microsoft Word Help page is to review/introduce readers to the Document_ContentControlOnExit event and illustrate several methods that you can use to insert defined content (text or graphics) into your Word documents based on a selection or entry the document user makes in the document content controls
The source of the defined content can include text and graphics stored in other Word documents or text and graphics stored as Building Blocks in the document template or other external template (e.g., the Word Built-In Building Blocks.dotx). It can also include text strings included in VBA procedures or even document variables.
Friend and frequent tips project collaborator Graham Mayor provides a similar discussion and examples for inserting content based on a user selection or entry in legacy form fields: Insert content from a form field
For more on Content Controls see: Content Controls
Note: I have limited the discussion and examples in this page to Microsoft Word. Most of the examples could easily be adapted to include the insertion of data from other external sources (e.g., Excel or Access).
Before getting to the examples I want to ensure that all visitors to this page are familiar with the Document_ContentControlOnExit event. This is a built-in document event that you can leverage each time your document user exits a document content control range. Understanding this event is key to examples that follow. The following steps provide a working example and review of the event.
Note: A template isn't necessary for this review, but we will be using features of a template as the examples are developed so we might as well start with one now.
Option Explicit Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, _ Cancel As Boolean) MsgBox ContentControl.Title End Sub
Option Explicit Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, _ Cancel As Boolean) Select Case ContentControl.Title Case "Files" MsgBox "The user selected a file, specifically: " & ContentControl.Range.Text Case "Offense" MsgBox "The user selected an offense, specifically: " & ContentControl.Range.Text Case Else 'The user exited some other content control that we don't care about. End Select lbl_Exit: Exit Sub End Sub
Note: The Document_ContentControlOnExit event is a new document event introduced with content controls in Word 2007. The demonstration above should show that it can serve the dual purposes of the "Calculate on exit" or "Run a macro on exit" function available in legacy form fields.
The first example uses the content control "Files," created in the review and a series of nested "If", "Ref" and and "IncludeText" fields placed in the template at the point inserted text should appear. The "Include Text" field used in this example includes the entire content of an external file.
Note: For the following examples I have created a folder on my computer "D:\Data Stores\IncludeText Tip" that contains three simple files named "File A.docx, File B.docx and File C.docx." Each file contains a text and graphic example. To duplicate this demonstration you will need to create and store similar named files in a similar named folder. If you choose to use a different folder or file names then modify file path and name in any example field or VBA code accordingly.
Option Explicit Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, _ Cancel As Boolean) Select Case ContentControl.Title Case "Files" 'Simple command to update fields. ActiveDocument.Fields.Update Case "Offense" MsgBox "The user selected an offense, specifically: " & ContentControl.Range.Text Case Else 'The user exited some other content control that we don't care about. End Select lbl_Exit: Exit Sub End Sub
1. The field method shown above is discussed in greater detail in Graham Mayor's Insert content from a form field including tips for creating and abbreviating the field code and expanding the update fields procedure to cover fields that could be located outside the main text range of the document (e.g., headers or footers).
2. This method and all methods that follows require that the user to make the selection and physically "exit" the content control.
Example 2 employs the content control "Files," a target bookmark in the active document and separate called VBA procedure. In this example a second "Select Case" statement in the OnExit event is used to resolve which content control list entry the user selected. The selected list entry value and target bookmark is passed as arguments to a separate procedure to build a custom IncludeText field in the target bookmark range that displays the appropriate file content.
Option Explicit Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, _ Cancel As Boolean) Dim oRng As Word.Range Select Case ContentControl.Title Case "Files" ActiveDocument.Fields.Update Select Case ContentControl.Range.Text Case "File A" IncludeTextFile "File A.docx", "FileTarget" Case "File B" IncludeTextFile "File B.docx", "FileTarget" Case "File C" IncludeTextFile "File C.docx", "FileTarget" Case Else IncludeTextFile " ", "FileTarget" End Select Case "Offense" MsgBox "The user selected an offense, specifically: " & ContentControl.Range.Text Case Else 'The user exited some other content control that we don't care about. End Select lbl_Exit: Exit Sub End Sub
Sub IncludeTextFile(ByRef strFileName As String, strBMTarget As String) 'Identify the file name and path of the data source. If you use a different folder _ then modify the path accordingly. Note the use of double "\\" in the path construction. Const pDataPath As String = "D:\\Data Stores\\IncludeText Tip\\" Dim strFile As String Dim oFld As Word.Field Dim oRng As Word.Range 'Enclosed path and file name in quotation marks. strFile = Chr(34) & pDataPath & strFileName & Chr(34) 'Set target range for the file being inserted. This is the bookmark "FileTarget" range. Set oRng = ActiveDocument.Bookmarks(strBMTarget).Range Application.ScreenUpdating = False 'Clear target range to ensure bookmark range is empty of any previous content. oRng.Delete If Not strFileName = " " Then 'Insert the IncludeText field and referenced filename Set oFld = ActiveDocument.Fields.Add(oRng, wdFieldEmpty, "IncludeText " & strFile, False) 'Show field result oFld.ShowCodes = False 'Redefine the range to encompass the field Set oRng = ActiveDocument.Range(Start:=oFld.Code.Start, End:=oFld.Result.End) 'Unlink field for easier in document editing. (Optional) oFld.Unlink Else oRng.Text = "" End If 'Redefine the bookmark ActiveDocument.Bookmarks.Add strBMTarget, oRng Application.ScreenUpdating = True lbl_Exit: Exit Sub End Sub
1. I used VBA to create and insert an IncludeText field in this example because of the simplicity in determining the range of the inserted file. The range is needed to recreate the bookmark that bounds the inserted file.
2. Inserting the file "in the bookmark" vice "at the bookmark" accommodates and allows the user to change his or her selection in the content control and avoid duplicate files from being inserted . For example if the user returns to the content control "Files" and selects "File B" then the content of "File C.docx" is removed from the document and replaced with the content of "File B.docx."
3. In this example I have included an optional statement "oFld.Unlink" which makes the process behave similar to the user interface process of inserting "Text from file ..." Omit this statement if you want your text to remain linked to the source document.
The third example employs the template content control "Offenses," a target bookmark in the active document, a reference bookmarks in a separate source document and a separate called VBA procedure. In this example I will employ the VBA "InsertFile" method to insert a range of text. The range of text is defined by a bookmark in the source document.
1. For this example I have added a file "IncludeTextDataStore.docx" to the "D:\Data Stores\IncludeText Tip." This file contains a collection of bookmarked narrative text as shown below. The narrative for the offense "Murder" is bookmarked using the bookmark name "Murder." The narrative of the offence "Rape" is bookmarked "Rape" and so on.
2. The "InsertFile" method and IncludeText field method shown above work equally well but the process of determining the range using the InsertFile method is, as you will soon see, a bit clunky.
'Snippet only!! Case "Offense" Select Case ContentControl.Range.Text Case "Murder" InsertFileRange "Narrative", "Murder" Case "Rape" InsertFileRange "Narrative", "Rape" Case "Arson" InsertFileRange "Narrative", "Arson" Case "Burglary" InsertFileRange "Narrative", "Burglary" Case Else InsertFileRange "Narrative", " " End Select
Sub InsertFileRange(ByRef strBMTarget As String, strBMSource As String) 'Identify the file name and path of the data source Const pDataFile As String = "D:\\Data Stores\\IncludeText Tip\\IncludeTextDataStore.docx" Dim oRng As Word.Range Dim oRngFileRangeEnd As Word.Range 'Set a target range for the text to insert. This is the bookmark "Narrative" range. Set oRng = ActiveDocument.Bookmarks(strBMTarget).Range Application.ScreenUpdating = False 'Clear target range of any previous content. This deletes the bookmark. If Len(oRng.Text) > 0 Then oRng.Delete If Not strBMSource = " " Then 'When you use InsertFile method you have to use a little Word trickery to determine _ the range of the inserted text. 'Anchor range start oRng.Collapse wdCollapseStart 'Create a duplicate range Set oRngFileRangeEnd = oRng.Duplicate 'Add a temporary character to the duplicate range oRngFileRangeEnd.InsertAfter "*" 'Insert the content oRng.InsertFile pDataFile, strBMSource 'Add ", , True" to link to the source text. 'Remove the temporary character from the duplicate range. oRngFileRangeEnd.Characters.Last.Delete 'Anchor range end oRng.End = oRngFileRangeEnd.End Else oRng.Text = "" End If 'Re-create the bookmark ActiveDocument.Bookmarks.Add strBMTarget, oRng Application.ScreenUpdating = True lbl_Exit: Exit Sub End Sub
The fourth example (showing code for the called procedure only) employs a dropdown content control, a target bookmark and defined building block entries.
The Document_ContentControlOnExit event code and the building block entries for the example mentioned above are available in the demonstration file you can download from the link at the end of this page.. For more on Building Blocks see: Building Blocks & AutoText
Sub InsertBBEinBM(ByRef pBMTarget As String, pBBEName As String) Dim oRng As Word.Range With ActiveDocument Set oRng = .Bookmarks(pBMTarget).Range If Not pBBEName = " " Then Set oRng = .AttachedTemplate.BuildingBlockTypes(wdTypeAutoText).Categories("Fruit") _ .BuildingBlocks(pBBEName).Insert(oRng, True) Else oRng.Text = "" End If .Bookmarks.Add pBMTarget, oRng End With End Sub
The final example employs a pair of content control checkboxes (Word2010 only) to insert text in a target bookmark. In this example all the code and text is contained in the Document_ContentControlOnExit event.
Case "Male" With ActiveDocument Select Case "True" Case ContentControl.Checked .SelectContentControlsByTitle("Female").Item(1).Checked = False Set oRng = .Bookmarks("GenderInst").Range oRng.Text = "The shuttle for Mars departs from space port 9 at 1500." .Bookmarks.Add "GenderInst", oRng Case ActiveDocument.SelectContentControlsByTitle("Female").Item(1).Checked = True 'Do nothing Case Else Set oRng = .Bookmarks("GenderInst").Range oRng.Text = "" .Bookmarks.Add "GenderInst", oRng End Select End With Case "Female" With ActiveDocument Select Case "True" Case ContentControl.Checked .SelectContentControlsByTitle("Male").Item(1).Checked = False Set oRng = .Bookmarks("GenderInst").Range oRng.Text = "The shuttle for Venus departs from space port 17 at 1600." .Bookmarks.Add "GenderInst", oRng Case ActiveDocument.SelectContentControlsByTitle("Male").Item(1).Checked = True 'Do nothing Case Else Set oRng = .Bookmarks("GenderInst").Range oRng.Text = "" .Bookmarks.Add "GenderInst", oRng End Select End With
Note: Again, the absence of a OnChange event make it necessary for the user to make the selection and "exit" the checkbox.
There you have it! The examples in this tips page should illustrate the wide range of options available for inserting content using content controls. You can download the files and template used to prepare the examples here: Demo Insert with CC
Do you want to make a payment for consulting work or donate to help support this site?
PayPal is a safe, easy way to pay online.
Use the appropriate currency "Donate" button to make a payment or donation.