如何在Word-VBA中跳转到书签并插入文本?
我正在尝试使用非常简单的Word宏创建一个Word文档。该宏搜索我在文本中放置的书签,然后在该位置添加一个未来 2 周后的日期。
但是,当我从模板创建新文档时,我不断收到找不到书签的信息。我已经浏览过很多次了,有时书签在那里,有时它在那里但不允许您单击“转到”。
我怎样才能让它发挥作用?我已向 Document_New()
事件添加了一小段代码,但仍然报告未找到书签。
我的文档位于 rar 文件中,因为我的网络服务器无法处理 .dotm 扩展名。 文档
我怎样才能做到这一点,以便当从此模板生成新文档时,新文档具有日期,提前两周,放在两个粗体部分之间?
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能是因为您的代码中使用了
ActiveDocument
。调用宏的文档可能仍然是ActiveDocument
,因此它找不到任何书签。以下是我从调用宏启用的文档/模板中执行此操作的方法,效果很好。This might be because of the use of
ActiveDocument
in your code. The calling macro's document may still be theActiveDocument
, so it wouldn't find any bookmark. Here's how I would do it from a calling macro-enabled document/template which works well.