Replace Text in Bookmark

时间:2018-04-15 08:51:21

标签: c# ms-word com office-interop

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

2 个答案:

答案 0 :(得分:1)

在VBA中,您将使用以下代码更新书签:

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

您可以使用以下代码调用:

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

我会留给你做C#改编。

答案 1 :(得分:0)

我的理解是TypeText将插入文本,除非Options.ReplaceSelection设置为true。更多:https://msdn.microsoft.com/en-us/VBA/Word-VBA/articles/selection-typetext-method-word