Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 331
Patrick Avatar asked Apr 27 '10 22:04

Patrick


1 Answers

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
like image 136
Todd Main Avatar answered Sep 23 '22 19:09

Todd Main