The range cannot be deleted. at Microsoft.Office.Interop.Word.Range.set_Text(String prop)

后端 未结 2 1426
梦谈多话
梦谈多话 2021-01-17 15:24

The recommended c# .net code to replace a bookmark with text appears very straight forward and I have seen the same code all over the net on so many websites (including your

2条回答
  •  半阙折子戏
    2021-01-17 15:45

        if (doc.Bookmarks.Exists(name))
        {
            Word.Bookmark bm = doc.Bookmarks[name];
            bm.Range.Text = text
        }
    

    This works but remember, if you replace the entire text of an existing bookmark this way, the bookmark disappears. Anytime you replace the first character of an existing bookmark (even if you replace it with what was already there) the bookmark is consumed. What I've found works (although I do not claim this is the Microsoft approved method) is something like this:

        if (doc.Bookmarks.Exists(name))
        {
           Word.Bookmark bm = doc.Bookmarks[name];
           Word.Range range = bm.Range.Duplicate;
           bm.Range.Text = text;                   // Bookmark is deleted, range is collapsed
           range.End = range.Start + text.Length;  // Reset range bounds
           doc.Bookmarks.Add(name, range);         // Replace bookmark
        }
    

提交回复
热议问题