范围无法删除.在Microsoft.Office.Interop.Word.Range.set_Text(String prop)

dan*_*dan 9 c# bookmarks office-interop

用文本替换书签的推荐c#.net代码看起来很直接,我在很多网站上看到了相同的代码(包括你的,从2009年9月的帖子开始)然而,我无法通过错误

范围无法删除.在Microsoft.Office.Interop.Word.Range.set_Text(String prop)

(我在Windows 7和Word 2010 14.0中使用VS 2010).

我的代码:

 private void ReplaceBookmarkText(Microsoft.Office.Interop.Word.Document doc, string bookmarkName, string text)
        {
            try
            {
                if (doc.Bookmarks.Exists(bookmarkName))
                {
                    Object name = bookmarkName;
                    //  throws error 'the range cannot be deleted' 
                    doc.Bookmarks.get_Item(ref name).Range.Text = text;
                }
            }
Run Code Online (Sandbox Code Playgroud)

Jos*_* M. 10

不要直接改变范围,尝试以下方法:

Bookmark bookmark = doc.Bookmarks.get_Item(ref name);

//Select the text.
bookmark.Select();

//Overwrite the selection.
wordApp.Selection.TypeText(text);
Run Code Online (Sandbox Code Playgroud)

例如,使用Word应用程序实例来改变文档.