3

使用 Word 互操作 API,我有一个文档,我从中删除了以特定颜色突出显示的文本。归结起来,逻辑是这样的:

if(range.HighlightColorIndex == WdColorIndex.wdYellow)
{
    range.Delete();
}

对于一些我注意到range.HighlightColorIndex返回值的文档:999999.

通过查看WdColorIndex枚举(这是属性的类型),我看到枚举是使用在 from toHighlightColorIndex区间内分配了一个值的元素实现的,这并没有解释返回的数字。-116999999

此外,通过使用 Word,我注意到一些奇怪的行为。创建一个带有两条黄色高亮线的新文档——第一条包含文本和超链接,第二条只包含文本:

  • 在第一次保存和关闭文档之前,Word 会在逐个选择它们时将每一行识别为以黄色突出显示。
  • 保存、关闭并重新打开文档后,Word 不再将包含文本和超链接的行识别为突出显示,而仅包含文本的行仍被识别为突出显示。

打开文档后 Word 的高亮识别截图如下:

可能的单词突出显示错误

从这项研究来看,这似乎是 Word 中的一个错误,但我想确保我没有在这里遗漏任何东西 - 所以,基本上,有没有人知道这是预期的行为还是错误,以及进一步,什么在给定情况下使用 Word Interop 时,一个合理的方法是处理它?

对于这种情况,我正在运行 Office 2010 和 Word 互操作 API 版本 14。

4

1 回答 1

2

Word 使用值 999999 来指示当前选择包含多个相应的格式。

在您的示例中,超链接表示为包含突出显示的运行的 Word 字段(按 Alt-F9 切换代码视图)。重新打开文档后,该字段本身没有应用突出显示。这不一定是 Word 中的错误,只是(超链接)字段的行为不记得字段级别的格式。

但是,您的实际任务似乎是从文档中删除突出显示的文本。这通常可以使用Range.FindWord 的对象更好地完成:

range.Find.ClearFormatting();
range.Find.ClearAllFuzzyOptions();
range.Find.Highlight = 1;
range.Find.Replacement.ClearFormatting();
range.Find.Replacement.Text = "";
range.Find.Wrap = Word.WdFindWrap.wdFindContinue;
range.Find.Execute(Replace: Word.WdReplace.wdReplaceAll);

这是一个完整的示例程序,您可以使用它来删除突出显示:

using System;
using System.Linq;
using Word = Microsoft.Office.Interop.Word;


class Program
{
    static void Main(string[] args)
    {
        var fileName = args[0];

        var wordApp = new Word.Application();
        wordApp.Visible = true;
        var document = wordApp.Documents.Open(fileName);
        RemoveHighlightingEverywhere(document);
    }

    static void RemoveHighlightingEverywhere(Word.Document document)
    {
        foreach (Word.Range storyRange in document.StoryRanges)
        {
            var range = storyRange;
            while (range != null)
            {
                RemoveHighlightingFromRange(range);

                if (range.ShapeRange.Count > 0)
                {
                    foreach (Word.Shape shape in range.ShapeRange)
                    {
                        if (shape.TextFrame.HasText != 0)
                        {
                            RemoveHighlightingFromRange(
                                shape.TextFrame.TextRange);
                        }
                    }
                }
                range = range.NextStoryRange;
            }
        }
    }

    static void RemoveHighlightingFromRange(Word.Range range)
    {
        range.Find.ClearFormatting();
        range.Find.ClearAllFuzzyOptions();
        range.Find.Highlight = 1;
        range.Find.Replacement.ClearFormatting();
        range.Find.Replacement.Text = "";
        range.Find.Wrap = Word.WdFindWrap.wdFindContinue;
        range.Find.Execute(Replace: Word.WdReplace.wdReplaceAll);
    }
}
于 2012-12-21T13:46:29.533 回答