Position cursor at start/end of Word document

2019-01-20 08:15发布

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

8条回答
我只想做你的唯一
2楼-- · 2019-01-20 08:58

Try this :

int lNumberOfPages = 
  _WordDoc.ComputeStatistics(Word.WdStatistic.wdStatisticPages, false);

WordApp.Selection.GoTo(Word.WdGoToItem.wdGoToPage,WordApp.WdGoToDirection.wdGoToLast, lNumberOfPages);
查看更多
一夜七次
3楼-- · 2019-01-20 09:01

You can use the predefined bookmark:

EndOfDoc oDoc.Bookmarks.Item("\endofdoc").Range

Other predefined bookmarks:

ActiveDocument.Bookmarks("\Para").Copy "currpara"

https://msdn.microsoft.com/en-us/VBA/Word-VBA/articles/predefined-bookmarks

查看更多
登录 后发表回答