I'm using the following code to send a text to a simple word template I've set up just with a single MergeField at present to test I can get this working.
The code I am using is as follows:
public static void ReplaceMailMergeField(string pWordDoc, string pMergeField, string pValue)
{
object docName = pWordDoc;
object missing = Missing.Value;
Word.MailMerge mailMerge;
Word._Document doc;
Word.Application app = new Word.Application();
app.Visible = false;
doc = app.Documents.Open(ref docName, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
mailMerge = doc.MailMerge;
foreach (Word.MailMergeField f in mailMerge.Fields)
{
if (f.Code.Text.IndexOf("MERGEFIELD \"" + pMergeField + "\"") > -1)
{
f.Select();
app.Selection.TypeText(pValue);
}
}
object saveChanges = Word.WdSaveOptions.wdSaveChanges;
doc.Close(ref saveChanges, ref missing, ref missing);
app.Quit(ref missing, ref missing, ref missing);
}
Which I call from my application with the following:
string pWordDoc = @"C:\Users\Pete-Laptop\Documents\CMS Document Mangement\Word Template.dotx";
cDocument.ReplaceMailMergeField(pWordDoc, "fieldAddress1", "Put address here!");
But nothing happens. When I step through the code it gets as far as the app.Documents.Open and then seems to freeze. I believe this is because the application cannot find my Word document. Am I correct in sending the full file path to the filename parameter? If not, how else is the application going to find my Word Template?