Search code examples
c#ms-wordcomoffice-interop

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


Solution

  • 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.