【问题标题】:Word 2007 Remove section breakWord 2007 删除分节符
【发布时间】:2012-12-06 23:42:26
【问题描述】:

我有一个 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 的正确方法?

【问题讨论】:

标签: c# replace ms-word ms-office


【解决方案1】:

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

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

【讨论】:

【解决方案2】:

回归较晚,但​​我使用的另一个解决方案是,您也可以使用 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-25
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 2015-03-12
    • 2016-08-21
    • 1970-01-01
    相关资源
    最近更新 更多