vba Excel / Word无法跳转到书签

时间:2013-07-21 11:40:45

标签: vba

Dim AppWD As Object
Dim objDoc As Object
Dim objDocProdTP As Object
...
Set AppWD = CreateObject("Word.Application") 'Word als Object starten
AppWD.Visible = True
Set objDocProdTP = AppWD.documents.Open(workPath & "\vorlagen\LFPostTemplate.docx")
Set objDoc = AppWD.documents.Open(workPath & "\vorlagen\LFTemplate2.docx")
...
MsgBox (objDoc.Bookmarks.Count)
objDoc.Goto what:=wdGoToBookmark, Name:="lblSFirma"

MSGBox返回11个书签(与LFPostTemplate.docx中的书签总数匹配)

但我尝试的每个书签都会返回“此书签不存在”

我认为问题很简单......但谷歌似乎没有任何解决方案

2 个答案:

答案 0 :(得分:2)

你通过后期绑定(从Excel?)开始Word,所以我假设可能没有定义单词常量。尝试使用-1而不是wdGotoBookmark

objDoc.Goto what:=-1, Name:="lblSFirma"

(或者您可以设置对 Microsoft Word xx.xx对象库的引用,然后可以使用常量)

答案 1 :(得分:0)

我在Excel 2010中使用了以下代码。我切换窗口视图模式以使我的书签所在的页面出现在窗口的顶部(我的书签所在的位置)。

Public Sub OpenWordDocAndGotoBookmark(strDocPathAndName As String, strBookmark As String)
    Dim AppWD As Object
    Dim objDoc As Object
    Dim objBookmark As Object

    Set AppWD = CreateObject("Word.Application") ' Start Word
    AppWD.Visible = True

    Set objDoc = AppWD.Documents.Open(strDocPathAndName)

    Set objBookmark = objDoc.Bookmarks(strBookmark)

    ' Move cursor to left of Bookmark
    objDoc.Range(objBookmark.Start, objBookmark.Start).Select

    ' Set window to make top of page with bookmark appear at top of window
    AppWD.ActiveWindow.ActivePane.View.Zoom.PageFit = wdPageFitFullPage
    AppWD.ActiveWindow.ActivePane.View.Zoom.PageFit = wdPageFitBestFit
End Sub