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();
}
}
}