Search code examples
c#.netms-wordinterop

How to select the last characters of a page with Interop Word?


I'm working on an application that automatically edits Word documents with the Interop.Word API.

I perform formatting corrections on some elements on the first page like title. While I edit the formatting, text on the next sections get moved. This is problematic, it changes positions of figures and tables.

My employer allowed me to solve this problem by playing with the linespacing of one of the elements on the first page. I already have the code to do this. I compare the string before and after editing to perform linespacing modifications.

What I don't know is how to select the last characters of a page.

I already tried this, but the problem is that the whole document gets selected.

        object missing = System.Reflection.Missing.Value;
        object what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
        object which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToAbsolute;
        object count = 1; //pagenumber

        doc.Selection.GoTo(ref what, ref which, ref count, ref missing);
        Object endPageOne = doc.Selection.Range.End;

        Range range = doc.ActiveDocument.Range(ref endPageOne);
        range.Select();
        return range;

I need to find a way to select the last several chars of the first page.


Solution

  • I found the solution myself.

    This code selects the complete first page. With substring I can select the last characters.

            object missing = System.Reflection.Missing.Value;
            object what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
            object which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToAbsolute;
            object count = 1; //pagenumber
            object count2 = (int)count + 1;
    
            Range startRange = doc.Selection.GoTo(ref what, ref which, ref count, ref missing);
            Range endRange = doc.Selection.GoTo(ref what, ref which, ref count2, ref missing);
            endRange.SetRange(startRange.Start, endRange.End);
            endRange.Select();
            return endRange;