Search code examples
c#comms-wordrangeoffice-interop

How to update the Start and End positions of the specific Range after making changes to the document?


I am creating a MS Office Word Add-in in C#. I need to get some information from the Document while working with it.

I take a certain Range of the document and save it.

For example, in the text:

Text1 text2 text3 text4

I save Range of the "text3". Its Start position = 13, End position = 17 (the number of characters, as I understand it).

If I change the text in front of this word:

Text1 NEW TE XT te xt2 text3 text4

Positions of its Range will remain the same. When trying to select the text I get an incorrect text range.

Is there a way to update the data of the Range object after editing the document?


Solution

  • The documentation states:

    Each Range object is defined by a starting and ending character position

    So what you assume:

    I save Range of the "text3". Its Start position = 13, End position = 17 (the number of characters, as I understand it).

    ... is correct.

    Positions of its Range will remain the same. When trying to select the text I get an incorrect text range.

    I believe this is intended behavior, and I think it matches quite well what the documentation states about ranges here: http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.range(v=office.14).aspx

    Is there a way to update the data of the Range object after editing the document?

    As far as I know, this is not possible, and as far as I can see, the documentation does not state that this should be possible either.

    At first I thought that maybe a Word object existed encapsulating such functionality, but it turns out that the Words collection on a document only contains Ranges that represents one word each - and that does not help much either.