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:

39 Comments

  • Andrew Morgan says:

    Hi,

    I’m trying to add a content control to a word document. I’m having a problem with your example above in vb.net if I type

    dim contentControls as Word.ContentControls
    dim checkboxControl as Word.ContentControl

    it says Word.ContentControls and Word.ContentControl is not defined.

    I’m using Visual Studio 2010 and Addin Express for Office and .net version 7.2.4055

    Can you help

    Regards
    Andrew

  • Pieter van der Westhuizen says:

    Hi Andrew,

    Do you have an Imports statement at the top of the file you’re declaring the ContentControl? e.g:

    Imports Word = Microsoft.Office.Interop.Word

  • Andrew Morgan says:

    Hi Pieter

    Yes if have Word = Microsoft.Office.Interop.Word in the imports

    Im use Word a number of places in the solution

    Cheers
    Andrew

  • Pieter van der Westhuizen says:

    Hi Andrew,

    Ah ok, in that case, are you targeting Office 2007 and up?
    I did a quick test and it looks like the ContentControls object is only available in Office 2007 and up.

  • Andrew Morgan says:

    I Pieter,

    I’m debugging it use Office 2013, is that the same as targeting? How do I see what versions im targeting.

    Thanks for you help with this.

    Andrew

  • Andrew Morgan says:

    Hi Pieter,

    I found it, I had v11 of Microsoft.office.interop.word instead of v12

    Cheers
    Andrew

  • Pieter van der Westhuizen says:

    Yip, that should do it :)
    Good one, good luck with the project!

  • Diego cecatto says:

    Hello I have a question,
    This procedure to save a property for me only works up before I save the file, but what if I want to keep a property that can be changed at any time as I do?

  • Andrei Smolin (Add-in Express Team) says:

    Hello Diego,

    What procedure do you refer to? And what you mean by “only works up before I save the file”? What occurs if you use it at any other moment? Note that modifying a document after it is saved makes the document non-saved (Document.Saved will return false).

  • naya says:

    How can I pass what’s in a textbox to a word with a bookmark??

    i hope you can help me!!

  • Andrei Smolin (Add-in Express Team) says:

    Hello Naya,

    While a textbox itself is part of the document, the text in the textbox doesn’t belong to the document. Accordingly, you can’t use a bookmark to retrieve the text from the textbox.

  • Jörg Martin says:

    Hi,

    using the first example to receive to BuiltInDocumentProperties causes word to say the document has been modified. So simple accessing the properties modifies the document ? How can i read the property values without changing the document ?

    JM

  • Anonymous says:

    Hello JM,

    I reproduce the issue in Word 2016: accessing the Document.BuiltinProperties property marks the document as “dirty”.

    Here’s a workaround:

    bool isSaved = doc.Saved;
    docprops = doc.BuiltInDocumentProperties as Microsoft.Office.Core.DocumentProperties;
    doc.Saved = isSaved;

  • Jörg Martin says:

    Hi,

    didn’t expect that this property is writeable :)
    Thank you very much…

    JM

  • Bouzid says:

    Hi, I am using bookmarks to update them with new fields, my problem is that bookmarks are unique in word. How can programmatically update one bookmark and that bookmark will update the rest of the concerning fields using cross reference or whatever.
    I have tried to add {REF YourbookmarkName} but this is not done programmatically, each time I add this field and close the word doc then reopen it disappears.

  • Andrei Smolin (Add-in Express Team) says:

    You can use the Word object model to update Range.Fields (Document.Fields, Selection.Fields) using the Fields.Update() method; see https://msdn.microsoft.com/en-us/library/office/ff195114(v=office.15).aspx.

  • Bouzid says:

    I hate to ask again, I do not think I understood. here is what I have

    //This will select the bookmark and update it with the correct value
    Microsoft.Office.Interop.Word.Document docu.Bookmarks[MybookMark].Select();
    Application oWordApp.Selection.TypeText(MyValue);

    Now once the Bookmark is updated, I have a cross reference created and I want to update it with Myvalue. I used this as you suggested but I am sure I am using it wrong.
    docu.Range().Fields.Update();
    oWordApp.Selection.Fields;

    I Cant figure it out

  • Andrei Smolin (Add-in Express Team) says:

    > Now once the Bookmark is updated, I have a cross reference created

    If only the cross reference above was created beforehand, then after you update a bookmark, you need to scan all fields in the current document to find the filed(s) pointing to that bookmark, and update each of these fields via Field.Update (see https://msdn.microsoft.com/en-us/library/office/ff839593(v=office.15).aspx). Alternatively, you can update all fields in the document: get Document.Fields, and call Fields.Update().

    Also, you can get and set Bookmark.Range.Text instead of selecting the bookmark and using Application.TypeText().

    You could use the Macro Recorder to record a VBA macro while updating a bookmark and updating a field(s) in the Word UI. The macro would show you the classes/members involved in the process.

  • Bouzid says:

    I have wrote this to scan through the fields, I added one book mark and two cross references. in the count property I see the 2 fields but I am not able to update them.

    for (int j = 0; j < docu.Fields.Count; j++)
    {
    var F =docu.Fields;
    docu.Fields.Update();

    }

  • Andrei Smolin (Add-in Express Team) says:

    All collections in Office are 1-based:

    for (int j = 1; j <= docu.Fields.Count; j++) { var field = docu.Fields[j]; field.Update(); }

  • Bouzid says:

    Do you think it is best to first create a bookmark then create a cross reference using the book mark in order for the update to hit the cross reference. I mean in this order. because all the cross reference I created using word 2013 are not being updated, I wonder why.

  • Bouzid says:

    Do you think it is best to first create a bookmark then create a cross reference using the book mark in order for the update to hit the cross reference. I mean in this order. because all the cross reference I created using word 2013 are not being updated, I wonder why. but it works if I do it manually meaning, I select a text and then I create a bookmark then when I create a cross reference I push on CTL + SHIFT + F9 then it updates

  • Bouzid says:

    Now it is removing the Bookmark I create, and {REF BookMarkName} is unchanged.

  • Andrei Smolin (Add-in Express Team) says:

    > Now it is removing the Bookmark I create

    Are you saying that you create a bookmark, select the text containing the bookmark, press F9, and the bookmark gets deleted? I don’t believe this understanding is correct. Could you provide more details?

    Why you do not update the cross reference?

    I don’t understand the context when you ask me about the order of creating bookmarks and references. Can you send me a test document so that we are on the same page?

    Did you use the macro recorder to find how all this stuff works behind the scenes?

    And finally, I don’t understand what you need to achieve. Sorry.

  • Bouzid says:

    Hi Andrei, sorry for the confusion. Now, I will try to clarify the task I am working on. I have a word document that I am updating its fields using bookmarks all over, so if I want to update three fields with the same information I have used bookmarks, but since bookmarks are unique I have named the three bookmarks as follows : Version_1 Version_2 Version_3. my code in c# works fine and updates them.

    Now, I want to use crossReference to update my fields instead of using the bookmarks Version_2 Version_3.

    The steps I did take to get the crossreference work are:
    I created a word doc with one bookmark Version_1 and two CrossReferences.

    if(docu.Bookmarks.Exists(“Version_1”))
    {
    var bm = docu.Bookmarks;
    var mbm = bm[XMLkey];
    var bmRange = mbm.Range;
    bmRange.Text = Xmlvalue;
    var h = mbm.Name;

    }
    Now the code below I used as suggested, in the count property, I see the number of my CrossReferences I created in the word document but I can never update them.

    for (int j = 1; j <= docu.Fields.Count; j++)
    {
    var field = docu.Fields[j];
    field.Update();
    }

    Also, when I run this code, the bookmark gets deleted But its content will be filled with my desired text. BUT,the cross reference does not update.

    I have not used the macro recorder. :( got limited time.
    Thank you for your helpppppppppppppppppppppppppppppp :)

  • Andrei Smolin (Add-in Express Team) says:

    I’ve created a document and recorded the VBA macro below while creating a bookmark and three references. Now, if I change the bookmark text, select all references and press F9 in the Word UI, the references are updated with the new text. The code of the reference field is: REF Version_1 \h. The VBA macro is as follows:

    Sub Macro1()

    ‘ Macro1 Macro


    Selection.MoveRight Unit:=wdCharacter, Count:=13, Extend:=wdExtend
    With ActiveDocument.Bookmarks
    .Add Range:=Selection.Range, Name:=”Version_1″
    .DefaultSorting = wdSortByName
    .ShowHidden = False
    End With
    Selection.InsertCrossReference ReferenceType:=”Bookmark”, ReferenceKind:= _
    wdContentText, ReferenceItem:=”Version_1″, InsertAsHyperlink:=True, _
    IncludePosition:=False, SeparateNumbers:=False, SeparatorString:=” ”
    Selection.TypeParagraph
    Selection.InsertCrossReference ReferenceType:=”Bookmark”, ReferenceKind:= _
    wdContentText, ReferenceItem:=”Version_1″, InsertAsHyperlink:=True, _
    IncludePosition:=False, SeparateNumbers:=False, SeparatorString:=” ”
    Selection.TypeParagraph
    Selection.InsertCrossReference ReferenceType:=”Bookmark”, ReferenceKind:= _
    wdContentText, ReferenceItem:=”Version_1″, InsertAsHyperlink:=True, _
    IncludePosition:=False, SeparateNumbers:=False, SeparatorString:=” ”
    End Sub

    Hope this helps.

  • Bouzid says:

    Hi Andrei, Thank you so muchhh for your generous help. you rock

  • Sagar says:

    Please let me know how to add value in BuiltinDocumentProperties in MS project(Microsoft.Office.Interop.MSProject.Application).I have search a lot but not able to find the answer.
    Thanks

  • Andrei Smolin (Add-in Express Team) says:

    Hello Sagar,

    You use the very same code that you would use in case of Word or Excel. The only difference is the starting point:
    – Excel: Workbook.BuiltinDocumentProperties
    – Word: Document.BuiltinDocumentProperties
    – MSProject: Project.BuiltinDocumentProperties

    See https://msdn.microsoft.com/en-us/library/office/ff197172.aspx on how to use that collection.

  • aemon says:

    I have a word template I manually added a few bookmarks. The name of the bookmark is similar to “txt_1, txt_2, checkbox_1, checkbox_2”. Now, I want to change “txt_1.text” and “checkbox_1.value” (ture or false) in C # code. I used the “Inserting a Word content control
    “The sample code. This is my code:

    private Word.Document doc;

    doc = app.Documents.Open(ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
    Word.ContentControls contentControls = null;
    Word.ContentControl checkboxControl = null;
    Word.Range selectionRange = null;
    strJson = DataSelect(wordId);
    JObject obj = JObject.Parse(strJson);
    foreach (var jObject in obj)
    {
    if (doc.Bookmarks.Exists(jObject.Key))//????????????
    {
    if (jObject.Key.ToString().Substring(0, 8).Equals(“checkbox”) || jObject.Key.ToString().Substring(0, 3).Equals(“cb_”))//isCheckBox?
    {
    try {
    selectionRange = doc.Bookmarks[jObject.Key].Range;
    contentControls = doc.ContentControls;
    checkboxControl = contentControls.Add(Word.WdContentControlType.wdContentControlCheckBox, selectionRange);
    if (jObject.Value.ToString().Equals(“1”))
    checkboxControl.Checked = true;
    else
    checkboxControl.Checked = false;
    //checkboxControl.Title = jObject.Value.ToString();
    }
    finally {
    if (selectionRange != null) Marshal.ReleaseComObject(selectionRange);
    if (checkboxControl != null) Marshal.ReleaseComObject(checkboxControl);
    if (contentControls != null) Marshal.ReleaseComObject(contentControls);
    }
    }
    else
    doc.Bookmarks[jObject.Key].Range.Text = jObject.Value.ToString();
    }
    }

    But when i run, in the “contentControls = doc.ContentControls;” will get an exception. (“Doc.ContentControls” raised an exception “System.AccessViolationException” type Microsoft.Office.Interop.Word.ContentControls {System.AccessViolationException}), so how should i modify my program? Looking forward to your reply. Thank you.

    (From Google Translate.)

  • Andrei Smolin (Add-in Express Team) says:

    Hello Aemon,

    Your code works for me when I invoke it in the Click event of a Ribbon button that my test Word add-in creates. Make sure you have no extra WINWORD.EXE hanging in processes. Also turn off all other COM add-ins. Make sure there’s no VBA code in attached template(s).

    I’ve polished your code a bit:

    Word.Documents documents = WordApp.Documents;
    doc = documents.Open(
    ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
    Word.ContentControls contentControls = null;
    Word.ContentControl checkboxControl = null;
    Word.Bookmarks bookmarks = null;
    Word.Bookmark bookmark = null;
    Word.Range bookmarkRange = null;
    try {
    bookmarks = doc.Bookmarks;
    if (bookmarks.Exists(jObjectKey))//????????????
    {
    bookmark = bookmarks[jObjectKey];
    bookmarkRange = bookmark.Range;
    if (isCheckBox)//isCheckBox?
    {
    try {
    contentControls = doc.ContentControls;
    checkboxControl = contentControls.Add(Word.WdContentControlType.wdContentControlCheckBox, bookmarkRange);
    checkboxControl.Checked = true;
    } finally {
    if (checkboxControl != null) Marshal.ReleaseComObject(checkboxControl);
    if (contentControls != null) Marshal.ReleaseComObject(contentControls);
    }
    } else {
    bookmarkRange.Text = “some text”;
    }
    }
    } catch (Exception ex) {
    MessageBox.Show(ex.Message);
    } finally {
    if (bookmarks != null) Marshal.ReleaseComObject(bookmarks);
    if (bookmark != null) Marshal.ReleaseComObject(bookmark);
    if (bookmarkRange != null) Marshal.ReleaseComObject(bookmarkRange);
    if (documents != null) Marshal.ReleaseComObject(documents);
    }

  • MatiasG says:

    hi, sorry my english. I can´t do it your example in asp.net. Can do it? i can´t find an example any where.
    When i try:

    Dim word As New Microsoft.Office.Interop.Word.Application
    Dim doc As Microsoft.Office.Interop.Word.Document = Nothing
    Dim docprops As Microsoft.Office.Core.DocumentProperties = Nothing
    Try
    doc = word.Documents.Open(“C:\temp.docx”)
    docprops = CType(doc.BuiltInDocumentProperties, Microsoft.Office.Core.DocumentProperties) <— trhow excption
    Dim props As String = String.Empty
    For Each prop As Microsoft.Office.Core.DocumentProperty In docprops
    Dim propValue As Object = Nothing
    Try
    propValue = prop.Value
    If (Not (propValue) Is Nothing) Then
    props = (props + String.Format("{0} : {1}{2}", prop.Name, propValue, Environment.NewLine))
    End If

    Catch ex As System.Exception
    'TODO: Warning!!! continue Catch
    End Try

    Next
    MsgBox(props)
    Finally
    If (Not (docprops) Is Nothing) Then
    Marshal.ReleaseComObject(docprops)
    End If

    If (Not (doc) Is Nothing) Then
    Marshal.ReleaseComObject(doc)
    End If

    End Try

    I have an exception:
    System.InvalidCastException: No se puede convertir el objeto COM del tipo 'System.__ComObject' al tipo de interfaz 'Microsoft.Office.Core.DocumentProperties'.

  • MatiasG says:

    hi, Sorry for my english.

    First, thanks for your reply. Second, seems that all post that i found are very old… i can not find the solution to edit or read the custom properties of a word document through vb.net.
    Thanks anyway.

  • Andrei Smolin (Add-in Express Team) says:

    Matias,

    Here’s a suggestion from that page: As a workaround you can use the late binding technology (see Type.InvokeMember) for accessing the object.

    In VB.NET, you need to use Type.InvokeMember() if you have Option Strict = On. If it is Off, you can simply declare Dim docprops As Object.

    HTH

  • Pierre Fontaine says:

    New C# coder.

    I am hoping one of you can help me with this. i have a word template with multiple bookmarks in it. I have been successful in populating the bookmarks with the desired data using C#. My challenge is I would like to delete only the bookmarks (just the bookmarks, not the data) from the generated Word doc.

    I am coming from Microsoft Access and was successful in accomplishing this using VBA.

    Hoping one of you might have the solution.

    thank you in advanced for your support.

  • Andrei Smolin (Add-in Express Team) says:

    You can record a VBA macro while deleting a bookmark using the Bookmarks dialog (Insert | Bookmark). In such a macro I see they call Bookmark.Delete(); see https://docs.microsoft.com/en-us/office/vba/api/word.bookmark.delete.

  • D??ng ?ình D?n says:

    How to check the status attribute of a word document? (using C# code)

  • Andrei Smolin (Add-in Express Team) says:

    Status? The Word object model doesn’t have the Status property on the Document object; see https://learn.microsoft.com/en-us/office/vba/api/word.document.

Post a comment

Have any questions? Ask us right now!