开发者

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

开发者 https://www.devze.com 2022-12-28 15:18 出处:网络
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.

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开发者_StackOverflow 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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消