如何使用Microsoft Word API和书签功能以编程方式将Word文档打开到特定位置? [英] How do I use the Microsoft Word API and Bookmarks feature to programmatically open a Word document to a specific location?

查看:125
本文介绍了如何使用Microsoft Word API和书签功能以编程方式将Word文档打开到特定位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Windows窗体应用程序中尝试以下代码.我不确定自己在做什么错(我很容易就做错了,因为我对Word API的使用经验不多),但是GoTo命令只是找不到书签.我总是在最后一行此书签不存在"中得到一个COMException.

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."

但是wordDoc.Bookmarks.get_Item(ref name)方法确实找到了书签! 有什么作用?

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

推荐答案

如何使用Bookmark对象?

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.

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

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

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

您是否尝试为WhothItem和Count传递Type.Missing,以便它复制VB调用?

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

这篇关于如何使用Microsoft Word API和书签功能以编程方式将Word文档打开到特定位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆