Add, Count, Retrieve and Remove Variables in a Word document Using C#

Document variables are used to preserve macro settings in between macro sessions. Spire.Doc allows adding variables, counting the number of variables, retrieving the name and value of variables, and removing specific variables in a Word document.

Add a Variable

Use the Add method to add a variable to a document. The following example adds a document variable named "A1" with a value of 12 to the document.

//Instantiate a document object
Document document = new Document();
//Add a section
Section section = document.AddSection();
//Add a paragraph
Paragraph paragraph = section.AddParagraph();
//Add a DocVariable Filed
paragraph.AppendField("A1", FieldType.FieldDocVariable);
//Add a document variable to the DocVariable Filed
document.Variables.Add("A1", "12");
 //Update fields
document.IsUpdateFields = true;
//Save and close the document object
document.SaveToFile("AddVariable.docx", FileFormat.Docx2013);
document.Close();

Add, Count, Retrieve and Remove Variables in a Word document Using C#

Count the number of Variables

Use the Count property to return the number of variables in a document.

//Load the document
Document document = new Document("AddVariable.docx");
//Get the number of variables in the document
int number = document.Variables.Count;

Console.WriteLine(number);

Add, Count, Retrieve and Remove Variables in a Word document Using C#

Retrieve Name and Value of a Variable

Use the GetNameByIndex and GetValueByIndex methods to retrieve the name and value of the variable by index, and the Variables[String Name] to retrieve or set the value of the variable by name.

//Load the document
Document document = new Document("AddVariable.docx");

// Retrieve name of the variable by index
string s1 = document.Variables.GetNameByIndex(0);

// Retrieve value of the variable by index
string s2 = document.Variables.GetValueByIndex(0);

// Retrieve or set value of the variable by name
string s3 = document.Variables["A1"];

Console.WriteLine("{0} {1} {2}", s1, s2, s3);

Add, Count, Retrieve and Remove Variables in a Word document Using C#

Remove a specific Variable

Use the Remove method to remove the variable from the document.

//Load the document
Document document = new Document("AddVariable.docx");

//Remove the variable by name
document.Variables.Remove("A1");

//Save and close the document object
document.SaveToFile("RemoveVariable.docx", FileFormat.Docx2013);
document.Close();