Dmitry
Dmitry

Reputation: 227

Replace Text in Bookmark

I'm using Interop.Word for my app. I get the bookmarks from the doc and then i want to insert text in it. But my construction only inserts text after the bookmark:

    WordDocument.Bookmarks[bookmark].Select();
    WordApp.Selection.TypeText(text);

How can i programmatically insert within the brackets, like on the image, not replacing its bookmark? Because for now, the code inserts the text within brackets, but it deletes the bookmark itself.

enter image description here

Upvotes: 1

Views: 2756

Answers (2)

macropod
macropod

Reputation: 13505

In VBA, you'd update a bookmark with code like:

Sub UpdateBookmark(StrBkMk As String, StrTxt As String)
Dim BkMkRng As Range
With ActiveDocument
  If .Bookmarks.Exists(StrBkMk) Then
    Set BkMkRng = .Bookmarks(StrBkMk).Range
    BkMkRng.Text = StrTxt
    .Bookmarks.Add StrBkMk, BkMkRng
  End If
End With
Set BkMkRng = Nothing
End Sub

which you'd call with code like:

Call UpdateBookmark("BookMarkName", "text to apply")

I'll leave it to you to do the C# adaptation.

Upvotes: 1

Rno
Rno

Reputation: 887

My understanding is that TypeText will insert text unless Options.ReplaceSelection is set to true. More: https://msdn.microsoft.com/en-us/VBA/Word-VBA/articles/selection-typetext-method-word

Upvotes: 0

Related Questions