Word 2007 删除分节符

3

我有一个包含多个子文档的word 2007 .doc文件,这些子文档由分节符分隔。

有没有一种方法可以从文档中删除所有分节符?

我尝试使用查找和替换功能,但是出现了错误。

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);
}

find.Text这一行会导致错误 -

用户代码未处理的SEHException

外部组件引发了一个异常。

我无法获取任何关于可能出现的错误的更多细节。该代码在Word 2003中工作正常,但我需要它在Word 2007中工作。

我是否正在正确地处理Word 2007?


除此之外,我成功地确定了根本问题 - http://support.microsoft.com/default.aspx?scid=kb;en-us;313104 - Kami
2个回答

7

我最终采取了另一种方法。由于查找功能会导致错误,我决定编写搜索/删除代码。以下代码将遇到的所有分节符都删除。

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);
    }
}

对于遇到此问题的谷歌员工,请查看以下链接以解决原始查找问题 - http://support.microsoft.com/default.aspx?scid=kb;en-us;313104。 - Kami

1
晚些时候,我使用的另一种解决方法是,您也可以使用vsto查找和替换,将分节符用“^m”替换为段落,用“^p”替换为段落,或为空字符串。
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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接