I am creating a quote generator that takes word doc templates and replaces key words in the template to generate a quote. Afterwards the document is returned as a PDF file. There are a few sections of the template that need to be removed if there is no data to fill them out.
Currently there is a table row that could have 2 different notes attached to it. If there are no notes to add, there is a lot of white space in the row if I don't delete these lines.
This is a Windows form App Using the .NET Framework in Visual studios. I have search for this error on Sack-overflow and the Microsoft.Office.Interop.Word API and have not been able to find a similar issue. Originally I was using the same range object to do the search and delete. So I tried making a new range object but I still get the same issue.
I have put some code here:
//If there is data to add
if (temp.DATAOBJECT != null){
FindAndReplace(_word, "<<Add-on Note PRODUCT>>", temp.DATAOBJECT, 1);
}else{
//////HERE IS WHERE THE FIRST RANGE IS DELETED. THIS ONE WORKS///////
range.Find.Execute("<<Add-on Note PRODUCT>>");
range.Expand(WdUnits.wdParagraph);
range.Delete();
}
//If there is data to add
if (temp.DATAOBJECT != null){
FindAndReplace(_word, "<<Add-on Note LINE>>", temp.DATAOBJECT, 1);
}else{
///HERE IS WHERE THE SECOND RANGE IS DELETED. THIS ONE DOESN'T WORK///
range2.Find.Execute("<<Add-on Note LINE>>");
range2.Expand(WdUnits.wdParagraph);
range2.Delete();
}
I have succeeded in deleting one of these line notes but when I attempt to delete the second line I get the error "Error -2146822384: Cannot edit Range."
I can not just make the line blank with "" because it leaves to much white space. It must be deleted.
Thanks to @CindyMeister in the comments We have found out why the error is happening.
The range in questions was selecting the end of a cell in a table which also selects the"\a" tag that signifies the end of the cell. We can not call Delete on this range if the \a tag is selected. Here is the updated code:
//If there is data to add
if (temp.DATAOBJECT != null){
FindAndReplace(_word, "<<Add-on Note LINE>>", temp.DATAOBJECT, 1);
}else{
range2.Find.Execute("<<Add-on Note LINE>>");
range2.Expand(WdUnits.wdParagraph);
range2.MoveEnd(WdUnits.wdCharacter, -1);
range2.Delete();
}
Hope this helps someone in the future