View Single Post
  #1   Report Post  
Posted to microsoft.public.word.mailmerge.fields
eJimmi eJimmi is offline
external usenet poster
 
Posts: 3
Default Header / Footer mail merge issue with custom built word automation solution.

Office professional 2003
Visual studio 2005
C#
Example mail merge field from header: «Field:Name»

I have smart client that use web services to provide data for mail
merge. The templates contain Custom tokens inserted in the document as
mail merge fields eg {{Field:StudentNumber}}, {{Table:CourseUnits}}.
The client parses the tokens and populates document with the relevant
data. All works well until these fields are in the header or footer.

The main method for performing the merge loops through the supplied
data rows and calls the ProcessFields method passing in the fields
collection from the document, header and footer.


Code stub from the execute method
DataRowCollection rows = _Data.Tables[0].Rows;
for (int i=0; i rows.Count; i++)
{
Word.Document document = null;
if (_DocumentType == DocumentType.Template)
{
document = _Assistant.AddDocument(_FilePath, true);
}
else
{
document = _Assistant.OpenDocument(_FilePath, true);
}
if (_BeforeRowProcessed != null)
{
_BeforeRowProcessed(this, document, rows[i], i);
}
// document.MailMerge.Destination = _Destination;
Word.HeaderFooter header =
document.Sections[1].Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
if (header.Exists)
{
ProcessFields(header.Range.Fields, rows[i]);
}
ProcessFields(document.Fields, rows[i]);
Word.HeaderFooter footer =
document.Sections[1].Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
if (footer.Exists)
{
ProcessFields(footer.Range.Fields, rows[i]);
}
if (_AfterRowProcessed != null)
{
_AfterRowProcessed(this, document, rows[i], i);
}
}


private void ProcessFields(Word.Fields fields, DataRow row)
{
foreach (Word.Field field in fields)
{
field.Select();
Word.Range range = _Assistant.Application.Selection.Range;
if (_OnFieldSelect != null)
{
_OnFieldSelect(this, field, row);
}
ResolveToken(field, row);
}
}


The resolve ResolveToken method maps the word merge field to the
database field writing the text with:

field.Result.Text = DatabaseAssistant.SafeStringValue(row[tokenKey]);

The best I have mamanged is to have either of the header or footer edit
pane open with the resolved value however when I close the window the
merge field only is displayed - the value is gone. I cannot see the
value in the print preview either. Initially I'm only concerned with
the primary header or footer - old tackle the variations of headers /
footers at a later stage.

This is the first Word automation I've built so any pointers will be
appreciated.

JS