How to insert a docVariable field without changing the Word source content?

Hi all,

in a recent project, I need to insert some kind of markers in the Word source document without changing the content/text. I end up using docVariable to do that and it works until hitting the use case when track changing is enabled. When adding the docVariable to the document, I need to specify a value, which should be the text of the range of a place of interest, e.g., a bookmark, in the source document, since I don't want to change the content. After adding the docVariable to the range as a field, Word automatically replaces the range text with the docVariable value, which is actually the same as the range text. However, when track change flag is on, the color and style (e.g., underline) will be changed and modification on the source document is noticeable, as shown in the screenshot below.  

The followings are the related C# code. Note that the lines to add underline and change text color won't work for an unknown reason. Please let me know if there is a way to fix this issue or if anything is wrong or there is an alternative solution without using docVariable to achieve what I need. Thanks in advance!

wordDocument.TrackRevisions = false;

wordDocument.ActiveWindow.ActivePane.View.RevisionsFilter.Markup = WdRevisionsMarkup.wdRevisionsMarkupNone;

/* suppose the current range is for the heading "ANALYSE DE MARCHE" and the marker we want to embed is "docVarName", i.e., the name of the docVariable */

wordDocument.Variables.Add(docVarName, range.Text);

Object obj = range.get_Style();

wordDocument.Fields.Add(range, WdFieldType.wdFieldDocVariable, docVarName, true);

range.set_Style(obj);

range.Font.Underline = WdUnderline.wdUnderlineSingle;

range.Font.ColorIndex = WdColorIndex.wdDarkRed;

range.Fields.Update();

Answer
Answer

Given a range, the following codes are not working.

range.Font.Underline = WdUnderline.wdUnderlineSingle;

range.Font.ColorIndex = WdColorIndex.wdDarkRed;

When working with fields, the font attributes are managed by applying either:

• the required formatting to the entire field, including the field braces (i.e. not to just the field's result); or

• adding a Charformat switch to the field (delete any Mergeformat switch that's present) and applying the desired formatting to at least the field code's first character (e.g. { DOCVARIABLE MyVar \* Charformat }).

Neither approach allows you to apply formatting to only part of the field. Any other approach will result in the formatting being lost when the field is refreshed.

Cheers
Paul Edstein
(Fmr MS MVP - Word)

Was this reply helpful?

Sorry this didn't help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

 
 

Question Info


Last updated October 5, 2021 Views 1,005 Applies to: