Search code examples
c#office-interopbookmarks

Delete contents of bookmark without deleting bookmark in ms word using c#


In ms word2010 I have a bookmark with bookmark name: nameOfBookmark

Now the bookmark content could be anything from just text to a mix of pictures, tables and whatever you could think of putting in a word document.

The problem is as following: I've got my bookmark with some contents I want to delete. However each time I try to delete the contents it also deletes my bookmark which I want to keep.

I've tried this, which simply deletes the whole thing:

    public void cleanBookmark(string bookmark)
    {
        var start = currentDocument.Bookmarks[nameOfBookmark].Start;
        var end = currentDocument.Bookmarks[nameOfBookmark].End;
        Word.Range range = currentDocument.Range(start, end);
        range.Delete();
    }

I've also tried to set the range to this:

Word.Range range = currentDocument.Range(start +1, end -1);

But then I end up with a bookmark that still contains the first and the last character of the content I wanted to delete.


Solution

  • Well I wonder why I have to keep answering my own questions, please notify me if you think it could be something about the way I ask questions.

    Anyway I found a solution after a bit more research and it seems like the thing I want simply can't be done or at least not the way I thought it could be done.

    If you delete the contents of a bookmark it also deletes the bookmark. So what you have to do is to store the name and range of the bookmark in a local variable and then add the bookmark again after deleting it.

        public void cleanBookmark(string bookmark)
        {
            var start = currentDocument.Bookmarks[bookmark].Start;
            var end = currentDocument.Bookmarks[bookmark].End;
            Word.Range range = currentDocument.Range(start, end);
            range.Delete(); 
            //The Delete() only deletes text so if you got tables in the doc it leaves the tables empty. 
            //The following removes the tables in the current range.
            if (range.Tables.Count != 0)
            {
                for (int i = 1; i <= range.Tables.Count; i++)
                {
                    range.Tables[i].Delete();
                }
            }
            currentDocument.Bookmarks.Add(bookmark, range);
        }
    

    If you want to read more about this topic see this question.