插入多个书签位置 - Excel VBA

时间:2016-04-18 17:35:49

标签: excel vba ms-word

我正在使用Excel宏,我将相同的文本插入Word文档中的多个书签。如何通过指定insert命令一次并将其应用于所有书签位置来完成此操作?

现在我正在为所有书签做以下事情?

Dim monYear As String
monYear = Format(DateAdd("m", -1, Now), "mmmm yyyy")


wdApp.Selection.GoTo what:=-1, Name:="Front_Page_Month_Year"
wdApp.Selection.TypeText monYear

wdApp.Selection.GoTo what:=-1, Name:="Page2_Month_Year"
wdApp.Selection.TypeText monYear

等等......

1 个答案:

答案 0 :(得分:2)

无法使用单个命令写入多个书签位置。但是,你可以做的是 reference 一个书签位置,以便在多个位置显示该书签的内容。

创建书签,然后在要显示书签内容的每个位置插入交叉引用。 (或创建一个交叉引用,然后复制/粘贴到其他位置。)

您的代码提示:您使用Selection对象的方法并不是最佳选择。与Excel一样,最好使用对象模型,而不是依赖于Selection。因此:

Dim doc as Word.Document
Set doc = wdApp.ActiveDocument 'Note: if you're opening a document, set in the Open method
doc.Bookmarks("Front_Page_Month_Year").Range.Text = monYear
'When you're done, update the REF fields (references)
doc.Fields.Update