3

I've been trying to create a library to replace the MergeFields on a Word 2003 document, everything works fine, except that I lose the style applied to the field when I replace it, is there a way to keep it?

This is the code I'm using to replace the fields:

private void FillFields2003(string template, Dictionary<string, string> values)
{
    object missing = Missing.Value;
    var application = new ApplicationClass();
    var document = new Microsoft.Office.Interop.Word.Document();

    try
    {
        // Open the file

        foreach (Field mergeField in document.Fields)
        {
            if (mergeField.Type == WdFieldType.wdFieldMergeField)
            {
                string fieldText = mergeField.Code.Text;
                string fieldName = Extensions.GetFieldName(fieldText);

                if (values.ContainsKey(fieldName))
                {
                    mergeField.Select();
                    application.Selection.TypeText(values[fieldName]);
                }
            }
        }
        document.Save();
    }
    finally
    {
        // Release resources
    }
}

I tried using the CopyFormat and PasteFormat methods in the selection, also using the get_style and set_style but to no exent.

Berkay Turancı
  • 3,373
  • 4
  • 32
  • 45
willvv
  • 8,439
  • 16
  • 66
  • 101

1 Answers1

6

Instead of using TypeText over the top of your selection use the the Result property of the Field:

          if (values.ContainsKey(fieldName))
          {
             mergeField.Result = (values[fieldName]);
          }

This will ensure any formatting in the field is retained.

hawbsl
  • 15,313
  • 25
  • 73
  • 114
  • 3
    Hi This helped a lot! thanks. Although, the right format is: mergeField.Result.Text = (values[fieldName]). Because the type of Result is "Range". Thanks a lot – willvv Oct 20 '09 at 14:10
  • Yes, f.Result.Text, as you say, absolutely. – hawbsl Oct 20 '09 at 14:33
  • Although it works, the result is not as intended. My code is `{MERGEFIELD ClientName * Upper}`. However, after running the merge, it doesn't display upper case of the client name. Can you help me? Thank you. – Thang Nguyen Oct 15 '15 at 01:53
  • @ThangNguyen you might want to ask that as a new question. it's been a long time since i answered the above, and i'm not going to remember how it works in detail – hawbsl Oct 15 '15 at 12:03