Search code examples
c#ms-wordoffice-interopms-office-addin

Word Interop change text of paragraph before a table


I want to change the text af a paragraph. Thought it is totally simple - until there was a table.

Actually it is just one line of code:

activeDocument.Paragraphs[2].Range.Text = "abcd" + "\r";

Word Document before

line1
line2
line3

Word Document after

line1
abcd   -> OK: text in paragraph replaced
line3

But with table it becomes strange (see below). The second paragraph is moved inside the table.

Word Document before

line1
line2
+-------+
| line3 |
+-------+

Word Document after

line1
+-------+
| abcd  |  -> NOK: text in paragraph replaced - but moved also into table
|       |
| line3 |
+-------+

how can i prevent the paragraph from being moved to the table?


Solution

  • I guess this is because paragraph is merged into the table when you overwrite its terminating carriage return character. I can think of several solutions to avoid that. Let's implement them as an extension method of Paragraph interface.

    Exclude terminating CR from the range

    public static class ParagraphExtensions
    {
        public static void SetText(this Paragraph paragraph, string text)
        {
            var range = paragraph.Range;
            var textRange = range.Document.Range(range.Start, range.End - 1);
            textRange.Text = text;
        }
    }
    

    Use TypeText() method of Selection to change paragraph's text

    public static class ParagraphExtensions
    {
        public static void SetText(this Paragraph paragraph, string text)
        {
            paragraph.Range.Select();
            paragraph.Application.Selection.TypeText(text);
        }
    }
    

    The drawback is that it changes the selection.

    Add brand new paragraph

    public static class ParagraphExtensions
    {
        public static void SetText(this Paragraph paragraph, string text)
        {
            // insert new paragraph before this paragraph
            var newParagraph = paragraph.Range.Document.Paragraphs.Add(paragraph.Range);
            newParagraph.Range.Text = text + "\r";
            // delete original paragraph
            paragraph.Range.Text = string.Empty;
        }
    }
    

    The usage of the extension methods for each of the options above is

    activeDocument.Paragraphs[2].SetText("abcd");