How do I use the Microsoft Word API and Bookmarks feature to programmatically open a Word document to a specific location?

五迷三道 提交于 2019-12-08 19:34:16

问题


I'm trying the following code in a Windows Form application. I'm not sure what I'm doing wrong (and I could easily be doing it wrong because I don't have a lot of experience with the Word API) but the GoTo command just cannot find the bookmark. I always get a COMException on the last line, "This bookmark does not exist."

But the wordDoc.Bookmarks.get_Item(ref name) method does find the bookmark! What gives?

Object fileName = System.Windows.Forms.Application.StartupPath + "\\Bookmarks.docx";
Object readOnly = false;
Object isVisible = true;
Object missing = System.Reflection.Missing.Value;

Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document wordDoc = new Microsoft.Office.Interop.Word.Document();

wordApp.Visible = true;
wordDoc = wordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);

Object item = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;
Object whichitem = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToFirst;
Object count = 1;
Object name = "Location3";

Bookmark bMark = wordDoc.Bookmarks.get_Item(ref name);
wordDoc.GoTo(ref item, ref whichitem, ref count, ref name);

回答1:


How about using the Bookmark object?

    object bookmarkName = "Location3";
    if (wordDoc.Bookmarks.Exists(bookmarkName.ToString()))
    {
        Bookmark bookmark = wordDoc.Bookmarks.get_Item(ref bookmarkName);
        bookmark.Select();
    }

I didn't check if the window scrolls there... but this should get you started.


EDIT: This is the VB code that is recorded when I do a Goto->Bookmark macro:

Selection.GoTo What:=wdGoToBookmark, Name:="Location3"

Did you try passing Type.Missing for WhichItem and Count so it replicates the VB call?




回答2:


Philip Wallace's answer works great.

To use the GoTo Command, Use the Word.Application object

object What = Word.WdGoToItem.wdGoToBookmark;
object oMissing = System.Reflection.Missing.Value;    
wordApp.Selection.GoTo(What, oMissing, oMissing, "bookMarkName");


来源:https://stackoverflow.com/questions/1646319/how-do-i-use-the-microsoft-word-api-and-bookmarks-feature-to-programmatically-op

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!