Jul
28
2011

Word VBA ContentControls in Header

I spent days trying to figure out a good way to set the value of a word content control in the header of a document using VBA. The solution was very useful for dealing with content controls in general…

The problem is that Word splits a document up into different regions (called stories) and each seem to contain their own collections. So the thisdocument.contentcontrols collection only refers to content controls located in the main section of your document, but not the header and footer.

If you want to put content controls in the header and footer, you can run into trouble.

There are a couple of solutions to addressing content controls in the header and footer of a word document, but I prefer the solution by Sunil Thomas at the following forum:

http://www.officekb.com/Uwe/Forum.aspx/word-vba/24300/replace-picture-in-content-control

Syntax is:

ActiveDocument.SelectContentControlsByTag("Your-Content-Control-Tag").Item(1).Range.Text = strYourString

Since I only have three content controls to address, I don’t need to loop through the collection and I can just address them by tag. Simple, love it!

Word VBA Window

Written by admin in: VBA | Tags: , , , ,

3 Comments »

  • Juan José

    this work for me:

    Dim oContent_Control As Object
    Dim oRange As Object

    For Each oRange In ActiveDocument.StoryRanges
    For Each oContent_Control In oRange.ContentControls
    On Error GoTo ErrHandler:
    oContent_Control.LockContents = False
    oContent_Control.Range.Text = oContent_Control.Tag
    oContent_Control.LockContents = True
    ErrHandler:
    Next
    Next

    Comment | November 20, 2012
  • Juan José

    The
    oContent_Control.Tag

    Should be replace for the text you want to put in de content control

    Comment | November 20, 2012
  • admin

    Thanks Juan.

    Comment | January 9, 2013

RSS feed for comments on this post. TrackBack URL

Leave a comment

Theme: TheBuckmaker.com Themes for WordPress | Cheap Web Hosting compared, Camping