The Muffin Boy
The Muffin Boy

Reputation: 314

How do I programmatically update Word fields?

I have a word document with fields: https://www.avantixlearning.ca/microsoft-word/word-tip-create-dynamic-word-documents-insert-fields/

There are number of fields that need to be updated, and updating them through the Word GUI is tedious.

I'm looking through the Word.Interop and it doesn't look like Word.Fields supports changing the value of the field (or a way to identify fields beyond the index or checking the result)

Is there another approach I could try?

Upvotes: 1

Views: 3066

Answers (1)

Axel Kemper
Axel Kemper

Reputation: 11322

To access the Fields collection of the current document, you could use ActiveDocument.Fields or ActiveDocument.Variables. If you want to access a non-active document, you have to create or open a Document object which represents it.

Most Word Field objects need not and cannot be changed in terms of their values. Variables can be referenced within the document text as DOCVARIABLE fields.

See a related questions here and here.

The following shows how this works in practice:

using Word = Microsoft.Office.Interop.Word;

namespace akWordFieldDemo
{
    class Program
    {
        static void Main(string[] args)
        {   
            //  start Word application
            var oWord = new Word.Application
            {
                Visible = true
            };

            //  create new document
            var oDoc = oWord.Documents.Add();

            //  add a DOCVARIABLE field
            Word.Paragraph para = oDoc.Paragraphs.Add();
            object fieldType = Word.WdFieldType.wdFieldEmpty;
            object text = "DOCVARIABLE myVar";
            object preserveFormatting = true;
            var field = oDoc.Fields.Add(para.Range, ref fieldType, ref text, ref preserveFormatting);

            //  set the value of the DOCVARIABLE
            oDoc.Variables["myVar"].Value = "some value";

            oDoc.Fields.Update();
            oDoc.SaveAs2("myDoc.docx");
            oDoc.Close();
            oWord.Quit();
        }
    }
}

Upvotes: 1

Related Questions