Microsoft Word if statement with mergefield is not working

1.7k views Asked by At

I am trying to implement IF statement with microsoft word (Microsoft.Office.Interop.Word dll) and c#. I have a template as below -
template image

and I am getting result like this -
template result image

my code is like this

 Dictionary<String, String> valueDic = new Dictionary<string, string>();
 valueDic.Add("Gender", "Male");
 Object oMissing = System.Reflection.Missing.Value;
 Object oTemplatePath = @"E:\\ContactTemplate2.docx";
 Application wordApp = new Application();
 Document wordDoc = new Document();
 wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
 foreach (Field myMergeField in wordDoc.Fields)
 {
   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 (valueDic.ContainsKey(fieldName))
     {
       myMergeField.Select();
       wordDoc.Application.Selection.TypeText(valueDic[fieldName]);
     }
     else
     {
       myMergeField.Select();
       wordDoc.Application.Selection.TypeText(" ");
     }
   }
 }
 wordDoc.SaveAs(@"E:\\myfile.docx");
 wordApp.Application.Quit();

and I want result like -
expected result

can someone help me with solution?

1

There are 1 answers

0
AudioBubble On BEST ANSWER

So if the MERGEFIELD field name is in your valueDic list, you want to replace the mergefield by its name?

If so, I suggest the next thing you need is something like this (you may need to correct the syntax)

if (valueDic.ContainsKey(fieldname))
{
  Range rngFieldResult = myMergeField.Result;
  myMergeField.Unlink();
  Range.Text = valueDic[fieldName];
}

You would also need to verify whether your field iteration still works if you delete a member of the collection. If not, you will probably have to iterate backwards using a counter. You may also need to pay attention to the IncludeFieldCodes and IncludeHiddenText properties of the TextRetrievalMode of any of the Ranges you are using

(Note: If you do this, Word will interpret { IF Male = "Male" } as a string comparison between "Male" and "Male" unless there is a bookmark called "Male" in which case it will compare the bookmark value with "Male")