I'm using Office Interop with MS Word (Microsoft.Office.Interop.Word) and Microsoft.Office.Tools.Word to modify a word document in a Word Add-in. I have a Range which contains specific text I want to edit.
When I update the Text object, the paragraph formatting of the Range is reset, specifically the Alignment and the LeftIndent. I can save the Alignment and LeftIndent in temp variables and reset them, but this is not ideal. Is there a way to stop the ParagraphFormat from being reset and if not, are there any other properties that I may be forgetting that I need to save (I just realized the before and after paragraph spacing also gets reset...).
Microsoft.Office.Interop.Word.Range range = myObject.range;
var oldAlignment = range.ParagraphFormat.Alignment;
var oldLeftIndent = range.ParagraphFormat.LeftIndent;
range.Text = "new text";
range.ParagraphFormat.Alignment = oldAlignment;
range.ParagraphFormat.LeftIndent = oldLeftIndent;
Edit: I just tried saving the ParagraphFormat as a temp variable and then resetting the formatting with that, but the temp variable loses its formatting as well.
oldParagraphFormat = range.ParagraphFormat;
range.Text = "new text";
range.ParagraphFormat = oldParagraphFormat; // oldParagraphFormat's objects are reset
Try creating a duplicate of the Range.ParagraphFormat
object prior to changing the text. You can do this via the ParagraphFormat.Duplicate object. This will retain the old ParagraphFormat value. After you change a range's text and its ParagraphFormat resets, you can restore the value from the duplicate.
// Get current value of ParagraphFormat.
Microsoft.Office.Interop.Word.Range range = myObject.range;
var oldParagraphFormat = myObject.range.ParagraphFormat.Duplicate;
// Change the range's text. This will reset ParagraphFormat, so reapply the previous value.
range.Text = "new text";
range.ParagraphFormat = oldParagraphFormat;
Some background as to what's going on: Changing Range.Text
essentially resets the Range object because a Range is text + formatting. So changing the text without including any formatting information will cause all previous formatting to be lost. (Much like how changing an HTML tag's innerText property causes that tag to lose all child tags.)
If duplicating the ParagraphFormat doesn't help then you may want to look into setting the Range.FormattedText property instead of Range.Text.