I have a word 2007 .doc file that contains multiple sub documents separated by sections.
Is there a way to remove all section breaks from the document?
I have tried to Find and Replace them but I receive an error.
private void RemoveAllSectionBreaks(Word.Document doc)
{
Word.Find find = doc.Range(ref oMissing, ref oMissing).Find;
find.ClearFormatting();
//find.Text = "^b"; // This line throws an error
find.Text =((char)12).ToString(); // Same error when attempting it this way
find.Replacement.ClearFormatting();
find.Replacement.Text = "";
find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, Word.WdReplace.wdReplaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
}
The find.Text line will generate an error -
SEHException was unhandled by user code
External component has thrown an exception.
I do not get any further details on what the error might have been. The code is working okay in word 2003, but I need this working in Word 2007.
Am I following the right approach for word 2007?
I ended up doing a different approach. As the word find feature was causing an error, I decided to code the search/removal. The following code removes all section breaks it encounters.
private void RemoveAllSectionBreaks(Word.Document doc)
{
Word.Sections sections = doc.Sections;
foreach (Word.Section section in sections)
{
section.Range.Select();
Word.Selection selection = doc.Application.Selection;
object unit = Word.WdUnits.wdCharacter;
object count = 1;
object extend = Word.WdMovementType.wdExtend;
selection.MoveRight(ref unit, ref count, ref oMissing);
selection.MoveLeft(ref unit, ref count, ref extend);
selection.Delete(ref unit, ref count);
}
}
Late comeback but an other solution I used is that you may also use the vsto find and replace replacing the section break by paragraph using "^m" for section and "^p" for paragraph, or with empty string.
using Word = Microsoft.Office.Interop.Word;
object missing = Missing.Value;
Word.Document tmpDoc = wordApp.Documents.Open(fileToOpen);
object findText = "^m";
object replaceText = "^p^p";
tmpDoc.Range().Find.Execute(ref findText,
true, true, true, ref missing, ref missing, ref missing,
ref missing, ref missing, ref replaceText, Word.WdReplace.wdReplaceAll,
ref missing, ref missing, ref missing, ref missing);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With