Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position cursor at start/end of Word document

We are manipulating our Word 2007 documents from .Net using Word Interop. Mostly doing stuff with fields as in:

For Each f In d.Fields
    f.Select()
    //do stuff with fields here            
Next

This leaves the last field in the document selected.

So, for the sake of neatness we would like to position the cursor at the end of the document (or even the start would be OK).

Googling for the answer doesn't throw up much ... the nearest I can get seems to be suggesting we need to involve ourselves with ranges or bookmarks. There's a GoTo method for the Document object but none of the WdGoToItem options it offers are useful.

Isn't there a simple way to just send the cursor to the end (or start) of document?

Edit

Part of my problem was I didn't like leaving the last field selected. Have now realised that I can do

f.Unlink

to remove the mergefield and just leave the field text there as plain text. Which is neater, whether or not we also reposition the cursor

like image 644
hawbsl Avatar asked Oct 19 '09 23:10

hawbsl


3 Answers

I'm not sure I'm using the same environment as you, but to go to the start or end of the document here's what works for me:

Private Sub moveCursorToStartOfDocument()
    w.Selection.HomeKey(WdUnits.wdStory, Nothing)
End Sub

Private Sub moveCursorToEndOfDocument()
    w.Selection.EndKey(WdUnits.wdStory, Nothing)
End Sub
like image 92
Fuhrmanator Avatar answered Sep 20 '22 09:09

Fuhrmanator


I use unit Word_TLB in Delphi with Appliction object- Word.Application

as following:

aWordDoc.Application.Selection.EndKey(wdStory,wdMove);

generally end of word document is:

Selection.EndKey( WdUnits.wdStory, WdMovementType.wdMove)

When I use

Selection.GoTo(Word.WdGoToItem.wdGoToLine, Word.WdGoToDirection.wdGoToLast, Nothing, Nothing);
Selection.InsertFile('documnet.docx');

new content was insert before last line.

like image 28
Irq Mishell Avatar answered Sep 19 '22 09:09

Irq Mishell


@Alexander Kojevnikov: Thanks for your help because you put me on the right track. However I found I had to apply the .GoTo to the Word Selection object, not the Document. As in:

    Dim what As Object = Word.WdGoToItem.wdGoToLine
    Dim which As Object = Word.WdGoToDirection.wdGoToLast

    //below line had no effect
    //d.GoTo(what, which, Nothing, Nothing)

    w.Selection.GoTo(what, which, Nothing, Nothing)
like image 20
hawbsl Avatar answered Sep 19 '22 09:09

hawbsl