c# - Word 2007 删除分节符

标签 c# replace ms-word ms-office

我有一个 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 was unhandled by user code

External component has thrown an exception.

我没有得到关于错误可能是什么的任何进一步细节。该代码在 Word 2003 中运行良好,但我需要它在 Word 2007 中运行。

我是否遵循了 word 2007 的正确方法?

最佳答案

我最终采用了不同的方法。由于单词查找功能导致错误,我决定编写搜索/删除代码。以下代码删除它遇到的所有分节符。

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

关于c# - Word 2007 删除分节符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13955478/

相关文章:

c# - 将 UIImage 转换为字节数组

java - 替换字符串中最后一次出现的字符

根据相邻列的值替换多列的值

JavaScript http 正则表达式

ms-word - 仅使用分隔字段名称的原始 MailMerge

.net - 使用 open xml sdk 代码,如何调整表格(在 ms word 文档中)以适应页边距?

c# - 2d 10 :00:00 to TimeSpan in C#

c# - 用逗号打印偶数,除了最后一个在 C# 中不起作用

c# - Visual Studio Tools for Unity 插件不起作用

ms-word - Word文件转换器