Pieter van der Westhuizen

Working with Word document properties, bookmarks, content controls and quick parts

The Microsoft Word object model is a complex and varied one. You can really get an appreciation for Word as a piece of software after spending some time slogging it out with the Microsoft Word object model.

Even though the object model can be somewhat daunting it gives you amazing flexibility and power over programmatically bending MS Word to your will. In today’s article we’ll have a look at the Microsoft Word document properties, content controls, quick parts and bookmarks, and how you can access and use these objects in your own add-ins. I will provide C# code examples for each of the following items and you can download the C# Word sample add-in at the end of the article:

Word document properties

Document properties are available for Microsoft Word, Excel and PowerPoint documents and act as metadata for the documents. Office stores a range of standard built-in properties for each document, such as Title, Author and Keywords etc.

Retrieving a list of built-in Word document properties

To retrieve a list of built-in Word document properties, use the DocumentProperties object. This object is shared amongst the other MS Office applications and can be found in the Microsoft.Office.Core namespace.

private void adxRibbonButtonShowBuiltInProperties_OnClick(
    object sender, IRibbonControl control, bool pressed)
{
    Word.Document doc = null;
    Microsoft.Office.Core.DocumentProperties docprops = null;
    try
    {
        doc = WordApp.ActiveDocument;
        docprops = doc.BuiltInDocumentProperties as
            Microsoft.Office.Core.DocumentProperties;
 
        string props = string.Empty;
 
        foreach (Microsoft.Office.Core.DocumentProperty prop in docprops)
        {
            object propValue = null;
 
            try
            {
                propValue = prop.Value;
                if (propValue != null)
                {
                    props += String.Format("{0} : {1}{2}",
                        prop.Name, propValue, Environment.NewLine);
                }
            }
            catch
            {
                continue;
            }
        }
        MessageBox.Show(props);
    }
    finally
    {
        if (docprops != null) Marshal.ReleaseComObject(docprops);
        if (doc != null) Marshal.ReleaseComObject(doc);
    }
}

Changing a built-in Word document property’s value

To change the value of a built-in property is fairly straightforward. You need to get an instance of the DocumentProperties collection and declare a new property to hold a reference to the built-in property you want to update.

private void adxRibbonButtonSetBuiltinPropertyValue_OnClick(
    object sender, IRibbonControl control, bool pressed)
{
    Word.Document doc = null;
    Microsoft.Office.Core.DocumentProperties docprops = null;
    Microsoft.Office.Core.DocumentProperty titleProperty = null;
 
    try
    {
        doc = WordApp.ActiveDocument;
        docprops = doc.BuiltInDocumentProperties as 
            Microsoft.Office.Core.DocumentProperties;
        titleProperty = docprops["Title"];
        if (titleProperty != null)
        {
            titleProperty.Value = "A new Title";
        }
        doc.Save();
    }
    finally
    {
        if (titleProperty != null) Marshal.ReleaseComObject(titleProperty);
        if (docprops != null) Marshal.ReleaseComObject(docprops);
        if (doc != null) Marshal.ReleaseComObject(doc);
    }
}

Creating a custom Word document property

The Word object model allows you to store additional information about the document inside the custom document properties. To create a custom document property, use the following code:

private void adxRibbonButtonCreateCustomProperty_OnClick(
    object sender, IRibbonControl control, bool pressed)
{
    Word.Document doc = null;
    Microsoft.Office.Core.DocumentProperties docprops = null;
    Microsoft.Office.Core.DocumentProperty projectNameProperty = null;
 
    try
    {
        doc = WordApp.ActiveDocument;
        docprops = doc.CustomDocumentProperties as 
            Microsoft.Office.Core.DocumentProperties;
        projectNameProperty = docprops.Add(
            "Customer Name",
            false,
            Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString,
            "Add-in Express");
        doc.Save();
    }
    finally
    {
        if (projectNameProperty != null)
            Marshal.ReleaseComObject(projectNameProperty);
        if (docprops != null) Marshal.ReleaseComObject(docprops);
        if (doc != null) Marshal.ReleaseComObject(doc);
    }
}

Changing a custom Word document property value

You can change a custom document property value with the following code:

private void adxRibbonButtonSetCustomPropertyValue_OnClick(
    object sender, IRibbonControl control, bool pressed)
{
    Word.Document doc = null;
    Microsoft.Office.Core.DocumentProperties docprops = null;
    Microsoft.Office.Core.DocumentProperty projectNameProperty = null;
 
    try
    {
        doc = WordApp.ActiveDocument;
        docprops = doc.CustomDocumentProperties as 
            Microsoft.Office.Core.DocumentProperties;
        projectNameProperty = docprops["Customer Name"];
        projectNameProperty.Value = "Acme Inc.";
        doc.Save();
    }
    finally
    {
        if (projectNameProperty != null) 
            Marshal.ReleaseComObject(projectNameProperty);
        if (docprops != null) Marshal.ReleaseComObject(docprops);
        if (doc != null) Marshal.ReleaseComObject(doc);
    }
}

Word bookmarks

A bookmark in Microsoft Word is exactly that, a bookmark for a specific location or selection within the document.

Creating a Word bookmark

To create a bookmark, first get a reference to the current document’s Selection object. This will give you access to a Range object, which is required in order to create the bookmark.

private void adxRibbonButtonCreateBookmark_OnClick(
    object sender, IRibbonControl control, bool pressed)
{
    Word.Document doc = null;
    Word.Bookmarks bookmarks = null;
    Word.Bookmark myBookmark = null;
    Word.Range bookmarkRange = null;
    Word.Selection selection = null;
 
    try
    {
        doc = WordApp.ActiveDocument;
        selection = WordApp.Selection;
        bookmarkRange = selection.Range;
        bookmarks = doc.Bookmarks;
        myBookmark = bookmarks.Add("MyBookmark", bookmarkRange);                
    }
    finally
    {
        if (selection != null) Marshal.ReleaseComObject(selection);
        if (bookmarkRange != null) Marshal.ReleaseComObject(bookmarkRange);
        if (myBookmark != null) Marshal.ReleaseComObject(myBookmark);
        if (bookmarks != null) Marshal.ReleaseComObject(bookmarks);
        if (doc != null) Marshal.ReleaseComObject(doc);
    }
}

Inserting text at a Word bookmark

Once the bookmark has been created, you can insert any text at the bookmark location by getting a reference to the Bookmark object.

private void adxRibbonButtonInsertTextinBookmark_OnClick(
    object sender, IRibbonControl control, bool pressed)
{
    Word.Document doc = null;
    Word.Bookmarks bookmarks = null;
    Word.Bookmark myBookmark = null;
    Word.Range bookmarkRange = null;
 
    try
    {
        doc = WordApp.ActiveDocument;
        bookmarks = doc.Bookmarks;
        myBookmark = bookmarks["MyBookmark"];
        bookmarkRange = myBookmark.Range;
        bookmarkRange.Text="Hello World!";
    }
    finally
    {
        if (bookmarkRange != null) Marshal.ReleaseComObject(bookmarkRange);
        if (myBookmark != null) Marshal.ReleaseComObject(myBookmark);
        if (bookmarks != null) Marshal.ReleaseComObject(bookmarks);
        if (doc != null) Marshal.ReleaseComObject(doc);
    }
}

Retrieving a list of bookmarks

Use the code like this to retrieve a list of Word bookmarks:

to private void adxRibbonButtonListBookmarks_OnClick(
    object sender, IRibbonControl control, bool pressed)
{
    Word.Document doc = null;
    Word.Bookmarks bookmarks = null;
    string bookmarkNames = string.Empty;
 
    try
    {
        doc = WordApp.ActiveDocument;
        bookmarks = doc.Bookmarks;
 
        for (int i = 1; i <= bookmarks.Count; i++)
        {
            bookmarkNames += bookmarks[i].Name + Environment.NewLine;
        }
 
        MessageBox.Show(bookmarkNames);
    }
    finally
    {
        if (bookmarks != null) Marshal.ReleaseComObject(bookmarks);
        if (doc != null) Marshal.ReleaseComObject(doc);
    }
}

Word content controls

Word Content controls are a great way to build easy-to-complete forms in Microsoft Word. Word provides a range of content controls such as the Plain Text, Combo box, Check box and Date Picker content controls.

To manually insert these controls into a Word document, you’ll need to first show the Developer tab and then click on the controls inside the Controls ribbon group.

Content controls on the Developer tab

Inserting a Word content control

Word provides a reference to all the content controls in the document via the ContentControls collection. To create a new content control, use the following code:

private void adxRibbonButtonInsertContentControl_OnClick(
    object sender, IRibbonControl control, bool pressed)
{
    Word.Document doc = null;
    Word.ContentControls contentControls = null;
    Word.ContentControl checkboxControl=null;
    Word.Selection selection = null;
    Word.Range selectionRange = null;
 
    try
    {
        doc = WordApp.ActiveDocument;
        selection = WordApp.Selection;
        selectionRange = selection.Range;
        contentControls = doc.ContentControls;
        checkboxControl = contentControls.Add(
            Word.WdContentControlType.wdContentControlCheckBox, selectionRange);
        checkboxControl.Title = "Agree to Terms and conditions";
        doc.Save();
    }
    finally
    {
        if (selectionRange != null) Marshal.ReleaseComObject(selectionRange);
        if (selection != null) Marshal.ReleaseComObject(selection);
        if (checkboxControl != null) Marshal.ReleaseComObject(checkboxControl);
        if (contentControls != null) Marshal.ReleaseComObject(contentControls);
        if (doc != null) Marshal.ReleaseComObject(doc);
    }
}

Retrieving a list of all content controls

And the following code will get a list of all content comtrols:

private void adxRibbonButtonListContentControls_OnClick(
    object sender, IRibbonControl control, bool pressed)
{
    Word.Document doc = null;
    Word.ContentControls contentControls = null;
    Word.ContentControl contentControl = null;
 
    string controlsList = string.Empty;
 
    try
    {
        doc = WordApp.ActiveDocument;
        contentControls = doc.ContentControls;
        for (int i = 1; i <=contentControls.Count; i++)
        {
            contentControl = contentControls[i];
            controlsList += String.Format("{0} : {1}{2}",
                contentControl.Title, contentControl.Type,Environment.NewLine);
            if (contentControl != null) Marshal.ReleaseComObject(contentControl);
        }
        MessageBox.Show(controlsList);
    }
    finally
    {               
 
        if (contentControls != null) Marshal.ReleaseComObject(contentControls);
        if (doc != null) Marshal.ReleaseComObject(doc);
    }
}

Word quick parts

The Word Quick Parts gallery is a collection of reusable content including document properties and AutoText. You are also able to add your own pieces of reusable content to this gallery.

Adding WordArt to a Word document

Adding WordArt to a Word document programmatically can be somewhat complicated, as you need the left and top coordinates of where you would like to insert the text. But, once you’ve established that, adding WordArt is as simple as invoking the AddTextEffect method of the Word Shapes collection.

private void adxRibbonButtonInsertWordArt_OnClick(
    object sender, IRibbonControl control, bool pressed)
{
    Word.Document doc = null;
    Word.Shapes shapes = null;
    Word.Selection selection = null;
 
    float left = 0;
    float top = 0;
 
    try
    {
        doc = WordApp.ActiveDocument;
        shapes = doc.Shapes;
        selection = WordApp.Selection;
        left = (float)selection.get_Information(
            Word.WdInformation.wdHorizontalPositionRelativeToPage);
        top = (float)selection.get_Information(
            Word.WdInformation.wdVerticalPositionRelativeToPage);
 
        shapes.AddTextEffect(
            Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect11,
            "You Name in WordArt Here",
            "Verdana",
            26,
            Microsoft.Office.Core.MsoTriState.msoFalse,
            Microsoft.Office.Core.MsoTriState.msoFalse,
            left,
            top,
            Type.Missing);
    }
    finally
    {
        if (selection != null) Marshal.ReleaseComObject(selection);
        if (shapes != null) Marshal.ReleaseComObject(shapes);
        if (doc != null) Marshal.ReleaseComObject(doc);
    }
}

When running the above code in MS Word the WordArt will look like the following image:

WordArt in Microsoft Word 2013 documen

Thank you for reading. Until next time, keep coding!

Available downloads:

This sample Word add-in was developed using Add-in Express for Office and .net:

Word Fields Word add-in (C#)

Word add-in development in Visual Studio for beginners:

Post a comment

Have any questions? Ask us right now!