Sean Hunter
Sean Hunter

Reputation: 1051

Mail Merge Word 2003 Header Fields C#

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?

Upvotes: 1

Views: 2083

Answers (2)

user998303
user998303

Reputation: 156

You need to explicitly search through the headers and footers separately from the main document. This works for me...

putField("First_Name", "Fred");
putField("Last_Name", "Bloggs");

private void putField(string search, string replace) {
    foreach (Section section in doc.Sections) {
        doReplace(section.Range.Find, search, replace);
    foreach (HeaderFooter h in section.Headers) {
        doReplace(h.Range.Find, search, replace);
    }
     foreach (HeaderFooter f in section.Footers) {
        doReplace(f.Range.Find, search, replace);
    }
    }
}

private void doReplace(Find fnd, string search, string replace){
        fnd.ClearFormatting();
        fnd.Replacement.ClearFormatting();
        fnd.Forward = true;
        fnd.Wrap = WdFindWrap.wdFindContinue;
        fnd.Text = "«" + search + "»";
        fnd.Replacement.Text = replace;
        fnd.Execute(Replace: WdReplace.wdReplaceAll);
}

Upvotes: 1

domke consulting
domke consulting

Reputation: 1022

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.

Upvotes: 0

Related Questions