Search code examples
c#.netms-wordrangeoffice-interop

Word Cannot Edit Range


I'm trying to automate the editing of a form and I've run into an issue with the bookmarks. The way I'm doing the forms is filling one out, saving it, redoing all the fields and saving it again. This saves time saving, opening and closing lots of different files and means I don't have to iterate through bookmarks and formfields each time.

However it would appear that when a bookmark has text inserted into it using wordApp.Selection.TypeText() the bookmark is destroyed or lost. Whatever the case I can no longer get hold of it. At the moment I have been getting the range and placing a new bookmark at the location after I put text into the old one.

Unfortunately this leaves the previous text behind when I try to replace it because I'm not overwriting the text in the old bookmark. Such as:

Form 0:

Name: John Smith

Form 1:

Name: Jane DoeJohn Smith

I've been trying to select the previous text and delete it but I'm being blocked by two similar errors, "Cannot Edit Range" and "Range cannot be deleted". I'm attempting it with:

//Exception - CANNOT EDIT RANGE
Range range = doc.Bookmarks[fieldName].Range.Duplicate;
doc.Range(range.Start, range.End).Delete();

I've also tried range.text = "" but I get the same result or "Range Cannot be Deleted".

It's a bit messy but I've tried many different variations of ranges trying to get the text but it always boils down to it not letting me change the text I've entered.

I looked at the similar question to this:

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

But the answer there thus far has not been able to resolve my issue.


Solution

  • Using the edit provided to this question I was able to get it to work the way I wanted:

    How can I keep bookmarks as bookmarks after editing the text value?

    if (doc.Bookmarks.Exists(fieldName))
    {
        doc.FormFields[fieldName].Result = text;
    }