问题描述
我试图用一个非常简单的word宏创建一个Word文档.宏会搜索我放置在文本中的书签,然后在该位置添加一个日期,即距未来2周的日期.
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".
如何使它正常工作?我在Document_New()
事件中添加了一些代码,但是一直在报告未找到书签.
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.
由于我的Web服务器无法处理.dotm扩展名,所以我将文档放在rar文件中.文档
I have the document in a rar-file since my webserver can't handle .dotm extensions.Document
我如何做到这一点,以便从该模板生成新文档时,新文档将日期提前2周放置在2个粗体部分之间?
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
推荐答案
这可能是因为在代码中使用了ActiveDocument
.调用宏的文档可能仍然是ActiveDocument
,因此找不到任何书签.这是我从调用宏的文档/模板中执行的方法,效果很好.
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
这篇关于如何在Word-VBA中跳转到书签并插入文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!