Excel vba 在书签前插入未给出预期的词序

Excel vba insert before bookmark does not give expected word order

我正在使用下面的代码打开一个新的 Word 文档并添加一个书签。我正在尝试在书签 'MyBookmark' 中插入多个单词以形成句子:"Once upon a time..."

我希望通过使用 InsertBefore 可以在书签之前插入单词,并且我可以在第一个单词之后添加下一个单词,因为书签在单词的末尾结束。事实并非如此,而是在创建句子的句子开头添加了单词:"a time...upon Once"

如何在句末加词?

我试过使用 InsertAfter,结果相同。我不想更改我添加单词的顺序,因为这在更大范围内是不可行的,我想实现它。下面的代码是我想要在实际实现中实现的示例我正在打开一个保存为 dotx 文件的模板。

Sub InsertBefore()
    ' Open Word document from template
    Set wrdApp = CreateObject("Word.Application")
    wrdApp.Visible = True
    wrdApp.Documents.Add
    wrdApp.Activedocument.Bookmarks.Add Name:="MyBookmark"

    ' Insert text
    wrdApp.Activedocument.Bookmarks("MyBookmark").Range.InsertBefore "Once "
    wrdApp.Activedocument.Bookmarks("MyBookmark").Range.InsertBefore "upon "
    wrdApp.Activedocument.Bookmarks("MyBookmark").Range.InsertBefore "a time..."
End Sub

最简单的方法是使用 Selection 对象。你先去那里然后你就从那里开始打字:

wrdApp.Activedocument.Bookmarks("MyBookmark").Range.Select

'Then from there on you just use the Selection object

wrdApp.Activedocument.ActiveWindow.Selection.TypeText("Once ")
wrdApp.Activedocument.ActiveWindow.Selection.TypeText("upon ")
wrdApp.Activedocument.ActiveWindow.Selection.TypeText("a time...")