Search code examples
vbac#-2.0office-interopbookmarks

How to delete text between two bookmarks in word with c#


I have two bookmarks in a word document. in between these bookmarks there is some text.

Now i want to be able to delete this text by using c# office interop.

I have got this working in VBA, but how can i do this in c#

Dim delRange As Range
Set delRange = ActiveDocument.Range

delRange.Start = delRange.Bookmarks("HTML_SECTION_START").Range.End
delRange.End = delRange.Bookmarks("HTML_SECTION_END").Range.Start
delRange.Delete

Solution

  • Try this:

            _Application app = new Application();
            try
            {
                _Document doc = app.Documents.Open("c:\\xxxx\\doc.doc");
                try
                {
                    Range delRange = doc.Range();
                    delRange.Start = doc.Bookmarks.get_Item("HTML_SECTION_START").Range.End;
                    delRange.End = delRange.Bookmarks.get_Item("HTML_SECTION_END").Range.Start;
                    delRange.Delete();
                    doc.Save();
                }
                finally
                {
                    doc.Close();
                }
            }
            finally
            {
                app.Quit();
            }
    

    You can protect the Bookmark get_Item with Bookmark.Exists

    Edit: You should save and close the document and the application