11

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;
                }
            }
dan
  • 111
  • 1
  • 4

2 Answers2

11

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.

Josh M.
  • 26,437
  • 24
  • 119
  • 200
1
    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
    }
Paul H.
  • 158
  • 8
  • This will still throw the error "The range cannot be deleted" COMException – Schuere Nov 04 '14 at 08:50
  • Under what circumstance does this throw the COMException? – Paul H. Nov 05 '14 at 14:07
  • Text Form Field with Field Settings Bookmark. ==> found out Office does not create a correct bookmark when setting this field. You still need to do INSERT => Bookmark => "Select bookmark" => Add. To create a correct bookmark (Sigh...) +EDIT: I will upvote this answer since it is correct. – Schuere Nov 06 '14 at 08:59
  • Ok, thanks for the followup. The above code is in a released product and I was concerned there might be bugs lurking. – Paul H. Nov 06 '14 at 15:22