MatAff
MatAff

Reputation: 1331

Excel vba insert before bookmark does not give expected word order

I'm using the code below to open a new Word document and add a bookmark. I'm trying to insert multiple words a the bookmark 'MyBookmark' to form the sentence: "Once upon a time..."

I was expecting that by using InsertBefore the word would be inserted before the bookmark and I could add the next word after the first one, since the bookmark ends up at the end of the word. This is not what happens, instead the word gets added at the start of the sentence creating the sentence: "a time...upon Once"

How can I add words at the end of the sentence?

I've tried using InsertAfter, which had the same result. I don't want to change the order in which I add the words as this is not feasible on the larger scale I would like to implement this. The code below is an example of what I'd like to achieve in the actual implementation I'm opening a template saved as a dotx file.

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

Upvotes: 0

Views: 546

Answers (1)

ib11
ib11

Reputation: 2568

The easiest approach is to use the Selection object. You go there first and then you just start typing from there:

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...")

Upvotes: 1

Related Questions