I'm trying to automate mailmerge using a .net program. There's a one page letter in word document addressed to a particular person with a mailmerge field by name 'Person'. Our database has got multiple persons and each person name has to go into a copy of the letter. We want the one-page letters to be concatenated one after the other. Currently this code tries to use two persons with - name1 & name2. The code below opens a separate instance of word for every person name.
object oMissing = System.Reflection.Missing.Value;
//CREATING OBJECTS OF WORD AND DOCUMENT
Word.Application oWord = new Word.Application();
Word.Document oWordDoc = new Word.Document("C:\\Test\\AddressTemplate.docx");
//SETTING THE VISIBILITY TO TRUE
oWord.Visible = true;
//THE LOCATION OF THE TEMPLATE FILE ON THE MACHINE
Object oTemplatePath = "C:\\Test\\AddressTemplate.docx";
oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
foreach (Microsoft.Office.Interop.Word.Field field in oWordDoc.Fields)
{
if (field.Code.Text.Contains("Person"))
{
field.Select();
oWord.Selection.TypeText(name1);
}
}
oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
foreach (Microsoft.Office.Interop.Word.Field field in oWordDoc.Fields)
{
if (field.Code.Text.Contains("Person"))
{
field.Select();
oWord.Selection.TypeText(name2);
}
}
Question: How can I change the code to open just one instance of word, fill in the mailmerge field and concatenate one letter at the end of the other?