如何使用Microsoft Word API和书签功能以编程方式将Word文档打开到特定位置?

时间:2009-10-29 20:27:20

标签: c# ms-word bookmarks

我正在Windows窗体应用程序中尝试以下代码。我不确定我做错了什么(我很容易做错,因为我没有很多Word API的经验)但GoTo命令却找不到书签。我总是在最后一行得到一个COMException,“这个书签不存在。”

但是wordDoc.Bookmarks.get_Item(ref name)方法找到了书签! 什么给出了?

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);

2 个答案:

答案 0 :(得分:7)

如何使用书签对象?

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

我没有检查窗口是否滚动到那里......但这应该让你开始。


编辑:这是我在执行Goto-> Bookmark宏时录制的VB代码:

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

您是否尝试将Type.Missing传递给WhichItem和Count以便复制VB调用?

答案 1 :(得分:1)

菲利普华莱士的回答很有效。

要使用GoTo命令,请使用Word.Application对象

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