views:

390

answers:

1

Hi

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.

Any help will be appreciated.

Thanks

+2  A: 

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
HiThis 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
Yes, f.Result.Text, as you say, absolutely.
hawbsl