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 a
You could try with:
_doc = _app.Documents.Add(ref _docName , ref _missing , ref _missing , ref _missing );
instead of
_doc = _app.Documents.Open(.......);
and then check if this line is correct:
if (f.Code.Text.IndexOf("MERGEFIELD \"" + pMergeField + "\"") > -1)
I have a functioning code that works in this way
mailMerge = doc.MailMerge;
foreach (Word.MailMergeField f in mailMerge.Fields)
{
// Extract the name of the MergeField starting from the 11 character
// and looking for the first space after the name
// (this means that you avoid MergeFields names with embedded spaces)
string fieldName = f.Code.Text.Substring(11).Trim();
int pos = fieldName.IndexOf(' ');
if (pos >= 0) fieldName = fieldName.Substring(0, pos).Trim();
if (fieldName == pMergeField)
{
f.Select();
app.Selection.TypeText(pValue);
}
The final code I used and which works for me is as follows:
public static void TextToWord(string pWordDoc, string pMergeField, string pValue)
{
Object oMissing = System.Reflection.Missing.Value;
Object oTrue = true;
Object oFalse = false;
Word.Application oWord = new Word.Application();
Word.Document oWordDoc = new Word.Document();
oWord.Visible = true;
Object oTemplatePath = pWordDoc;
oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
foreach (Word.Field myMergeField in oWordDoc.Fields)
{
Word.Range rngFieldCode = myMergeField.Code;
String fieldText = rngFieldCode.Text;
if (fieldText.StartsWith(" MERGEFIELD"))
{
Int32 endMerge = fieldText.IndexOf("\\");
Int32 fieldNameLength = fieldText.Length - endMerge;
String fieldName = fieldText.Substring(11, endMerge - 11);
fieldName = fieldName.Trim();
if (fieldName == pMergeField)
{
myMergeField.Select();
oWord.Selection.TypeText(pValue);
}
}
}
}
This code is orignally from here.