1

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?

The Muffin Boy
  • 314
  • 4
  • 14
  • 1
    Are the word documents the new .docx format? If so you can use the OpenXML SDK. This question may help. https://stackoverflow.com/questions/52206121/how-can-i-update-all-fields-cross-reference-with-openxml-in-c I'd avoid the Word Interop as it has a dependency on office being installed. – Ryan Thomas Jun 23 '21 at 20:04

1 Answers1

1

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();
        }
    }
}
Axel Kemper
  • 10,544
  • 2
  • 31
  • 54