I am in the process of writing a small library that will perform a MailMerge on a word 2003 .DOT document in C#. I am able to retrieve and replace all of the document body fields like so:
foreach (Field mergeField in document.Fields)
{
if (mergeField.Type == WdFieldType.wdFieldMergeField)
{
string fieldText = mergeField.Code.Text;
string fieldName = Extensions.GetFieldName(fieldText);
if (values.ContainsKey(fieldName))
{
mergeField.Select();
application.Selection.TypeText(values[fieldName]);
}
}
}
But this does not retrieve the Header or Footer fields from the document..
I have tried this:
subscriptionDocument.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Fields.Count;
To query the header fields, but am getting a count returned of "0", even though the fields physically exist.
Is there a way that I can do a achieve the desired affect on Header and Footer fields as well?
Your code is correct, and normally you can count the fields in a header with it. I guess that the test document you're working with has a slightly different layout, e.g. even headers or a first page header. With "wdHeaderFooterPrimary" you access not the first page, if "Different First Page" is activated in the section. Open your test document in Word, fire up the VBA Editor (Alt+F11), go to the Immediate Windows and type
?activedocument.Sections(1).Headers(wdHeaderFooterFirstPage).Range.Fields.Count
to access the fields in the first page header.