Search code examples
c#ms-wordoffice-interop

Move my cursor to selected Line in MsWord using C#


I am doing Word automation in C#. I want to move current cursor position to selected line number.

Let me explain with an example:

Line 1
Line 2
Line 3
Line 4

Line 6
Line 7

Now I have purposely left Line 5 blank. After Line 7, I want to move cursor to Line 5. I am using oWord.Selection.Range method, but no luck so far.


Solution

  • Well It seems no one found any thing.Let me help my self and others who might face this problem

    well the logic here is that,every time you move your cursor to the top of the position,here Line 1

       WRange.Range Myrng = oDoc.Range(ref StartPos, ref Endpos);
                       Myrng.Select();
    
                       object Story = WdUnits.wdLine;
                       oWord.Selection.EndKey(ref Story, ref extend);
    
                       object NewEndPos = oWord.Selection.End - 1;
                       Myrng = oDoc.Range(ref NewEndPos, ref NewEndPos);
                       Myrng.Select();
    

    after this point the output is something like Line 1 I now I will move the cursor to Line 5 for that

                       object Count=5;
                       oWord.Selection.MoveDown(ref unit, ref Count, ref oMissing);
    

    And Voila here you are to Line Number 5