How to go to a bookmark in Word-VBA and insert text?

I am trying to create a Word document with a very simple macro of words. The macro searches for the bookmark that I placed in the text, and then adds a date of 2 weeks in the future at this place.

But when I create a new document from the template, I still do not get the bookmark. I went through this many times, and sometimes there is a bookmark there, sometimes it is there, but it does not allow you to click Go.

How can I make it work? I added a small piece of code to the Document_New() event, but it saves the message "Bookmark not found."

I have a document in a rar file, since my web server cannot handle .dotm extensions. Document

How can I make sure that when creating a new document from this template, the new document has a date two weeks ahead, located between the two 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 
+6
ms-word word-vba word-2007
source share
1 answer

This may be due to the use of ActiveDocument in your code. The calling macro may still be an ActiveDocument , so it will not find any bookmark. Here, how would I do it from the calling macro 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 
+1
source share

All Articles