0
votes

I have an existing word document which has a formatted mail merge field({ MERGEFIELD Payment_Date \@ "MMMM d,yyyy" }).

When I pass a string(say (01/01/2016)) from C# to do a mail merge the code field.Select() selects the entire merge field and replaces it with the string I am passing and I lose the formatting.

How can I prevent this?

foreach (Microsoft.Office.Interop.Word.Field field in document.Fields)
{                         
    if (field.Code.Text.Contains("Payment_Date"))
    {
        DateTime pDate = new DateTime(2016, 12, 30);
        field.Select();                                   

        application.Selection.TypeText(pDate.ToString());            
    } 
}      

This is the code that I am using to do the mail merge.

1

1 Answers

0
votes

You either have to extract the format string from the field and transform it into something that lets you format your C# string correctly, or (simpler IMO) replace the field by one that retains the format string and let Word do the formatting for you.

For example, you might be able to replace it with

{ QUOTE "2016-12-30" \@ "MMMM d,yyyy" } 

(I would advise that you insert the date string in YYYY-MM-DD format, as I believe Word always interprets the day and month correctly in that case).

(NB, you can't just insert the text with { } - you have to insert a field. Then, if you just want the result, you can ensure the field has been Updated, then Unlink the field, just leaving the result).

One situation remains - what if the MERGEFIELD field has no date/time format switch? In that case you will need to impose a format (I do not think it will be possible to discover the document author's intent).