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

dan picture dan · Feb 10, 2011 · Viewed 7.1k times · Source

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 yours, from a Sept. 2009 post) however, I cannot get past the error

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

(I'm using VS 2010 with Windows 7 and Word 2010 14.0).

My code:

 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;
                }
            }

Answer

Josh M. picture Josh M. · Mar 7, 2011

Instead of altering the range directly, try something like:

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

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

//Overwrite the selection.
wordApp.Selection.TypeText(text);

E.g. use your Word application instance to alter the document instead.