Reputation: 23
I am trying to access a set of previously defined variables in a MS Word document using Interop. So far I managed to do it reading the variable code as a string and filtering the name, but I would like to do it using directly the variable names.
Please help reading DocVariable names list.
Code already working:
Microsoft.Office.Interop.Word.Document my_Document = (Microsoft.Office.Interop.Word.Document)my_Word.Documents.Open(ref oLoc, ref oMissing, ref oFalse, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oTrue, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
foreach (Field f in my_Document.Fields)
{
if (f.Type == WdFieldType.wdFieldDocVariable)
{
string txt = f.Code.Text;
string str = txt.Split(" ".ToCharArray())[2];
foreach (LabsandVals recList in list)
{
if (str == recList.Labels)
{
string valso = recList.Vals;
my_Document.Variables[str].Value = recList.Vals;
my_Document.Fields.Update();
}
}
}
}
I would like to use instead my_Document.Fields.OfType to be read as a list.
Upvotes: 1
Views: 1184
Reputation: 25693
Word Field objects don't fulfill the criteria for using OfType: "Filters elements of a System.Collection IEnumerable based on a specified type."
It might be better to loop my_Document.Variables and compare the Variable.Name against recList. That would certainly be more efficient than looping the fields in the document, comparing the field type, splitting the code.
foreach (Word.Variable DocVar in my_Document.Variables)
{
MessageBox.Show(DocVar.Name.ToString());
}
Also, for reasons of efficiency, it would be better to put my_Document.Fields.Update
outside the loop so that the fields in the document update only once. Depending on what fields the document contains, updating them could take a noticeable amount of time (links, for example).
Upvotes: 1