How do I use the Microsoft Word API and Bookmarks feature to programmatically open a Word document to a specific location?
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开发者_Python百科.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);
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?
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");
精彩评论