How to Jump to a Bookmark in Word-VBA and insert text?

天涯浪子 提交于 2019-12-08 16:35:32

问题


I am trying to create a Word document with a very simple word macro. The macro searches for a bookmark that I have placed in the text and then adds a date, 2 weeks into the future, at that location.

But when I create a new document from the template I keep getting bookmark not found. I have been through it loads of times and sometimes the bookmark is there, sometimes its there but not allowing you to click "Go to".

How can I get it to work? I have added a little piece of code to the Document_New() event but that keeps reporting Bookmark not found.

I have the document in a rar-file since my webserver can't handle .dotm extensions. Document

How can I make it so that when a new document is produced from this template, the new document has the date, 2 weeks ahead, placed between the 2 bold sections?

Sub Two_Weeks_Ahead()
''# Two_Weeks_Ahead Makro
    Selection.GoTo What:=wdGoToBookmark, Name:="TwoWeeks"
    With ActiveDocument.Bookmarks
        .DefaultSorting = wdSortByName
        .ShowHidden = False
    End With

    Dim dt As Date
    dt = DateAdd("d", 14, DateTime.Now)

    Selection.TypeText Text:=Format(dt, "yyyy-MM-dd")
End Sub

Private Sub Document_New()
    Selection.GoTo What:=wdGoToBookmark, Name:="TwoWeeks"
    With ActiveDocument.Bookmarks
        .DefaultSorting = wdSortByName
        .ShowHidden = False
    End With

    Dim dt As Date
    dt = DateAdd("d", 14, DateTime.Now)

    Selection.TypeText Text:=Format(dt, "yyyy-MM-dd")
End Sub

回答1:


This might be because of the use of ActiveDocument in your code. The calling macro's document may still be the ActiveDocument, so it wouldn't find any bookmark. Here's how I would do it from a calling macro-enabled document/template which works well.

Sub AddTwoWeeks()
    Dim d As Document
    Set d = Documents.Add("C:\Users\Me\Desktop\Title.dotx")

    Dim dt As Date
    dt = DateAdd("d", 14, DateTime.Now)

    Dim b As Bookmark
    Set b = d.Bookmarks("TwoWeeks")
    b.Range.Text = Format(dt, "yyyy-MM-dd")
End Sub


来源:https://stackoverflow.com/questions/2725550/how-to-jump-to-a-bookmark-in-word-vba-and-insert-text

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