Word Interop:如何根据查找命令的结果设置插入点?

Word Interop: How do I set an insertion point based on the results of a Find command?

注意:代码基于 Using a macro to replace text where ever it appears in a document

中记录的方法

我的目标是使用 Word Interop Find.Execute 在第一个页眉中找到的单词后立即插入一个新段落。为此,我需要在找到的单词的开头或结尾插入一个插入点(类型 == wdSelectionIP)。

我的假设 is/was 作为使用 Word Interop Find.Execute 在第一页页眉中查找单词的结果,Word 将在以下位置设置一个插入点(类型 == wdSelectionIP)找到的单词的开头或结尾。您可以在我的 SomeEventMethod_Click 方法中看到这一点,即在这种假设下,找到单词后,我导航到行尾,创建一个新的空段落,设置一些属性,然后输入一些文本.

文本已输入,但未跟在第一页页眉中找到的词之后。相反,文本是在最后一页底部的主文本区域(即文档正文)中键入的。

如何根据查找命令的结果设置插入点?

Class 用于报告查找和替换结果

private class ClsFindReplaceResults
{
    bool isFound = false;
    Microsoft.Office.Interop.Word.Selection selection = null;

    public ClsFindReplaceResults(bool isFound, Selection selection)
    {
        this.IsFound = isFound;
        this.Selection = selection;
    }

    public bool IsFound { get => isFound; set => isFound = value; }
    public Selection Selection { get => selection; set => selection = value; }
}

从中调用 FindReplaceAnywhere 方法的事件方法

private void SomeEventMethod_Click(object sender, RibbonControlEventArgs e)
{
    //Find the text 'foo\r'. No replacement. I just want the insertion point
    ClsFindReplaceResults objFindReplaceResults = FindReplaceAnywhere(findText: "foo^p", replaceWithText: null, enumWdStoryType: WdStoryType.wdFirstPageHeaderStory);

    if (objFindReplaceResults.IsFound)
    {
        objFindReplaceResults.Selection.EndKey(WdUnits.wdStory);
        objFindReplaceResults.Selection.TypeParagraph();
        objFindReplaceResults.Selection.Font.Size = 9;
        objFindReplaceResults.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphJustify;
        objFindReplaceResults.Selection.ParagraphFormat.SpaceAfter = 6f;
        objFindReplaceResults.Selection.TypeText("new paragraph that should appear after 'foo^p'");
    }
}

FindReplaceAnywhere 方法

private ClsFindReplaceResults FindReplaceAnywhere(string findText, string replaceWithText, WdStoryType enumWdStoryType)
{
    bool found = false;
    object wfrFindText = findText;
    object wfrMatchCase = true;
    object wfrMatchWholeWord = true;
    object wfrMatchWildCards = false;
    object wfrMatchSoundsLike = false;
    object wfrMatchAllWordForms = false;
    object wfrForward = true;
    object wfrWrap = WdFindWrap.wdFindContinue;
    object wfrFormat = false;
    object wfrReplaceWith = replaceWithText;
    object wfrReplace = null;

    if (wfrReplaceWith == null)
    {
        wfrReplace = WdReplace.wdReplaceNone;
    }
    else
    {
        wfrReplace = WdReplace.wdReplaceOne;
    }

    object wfrMatchKashida = false;
    object wfrMatchDiacritics = false;
    object wfrMatchAlefHamza = false;
    object wfrMatchControl = false;

    Globals.ThisAddIn.Application.Selection.Find.ClearFormatting();
    Globals.ThisAddIn.Application.Selection.Find.Replacement.ClearFormatting();

    //Fix the skipped blank Header/Footer problem as provided by Peter Hewett. Don't know what the heck this does
    WdStoryType junk = Globals.ThisAddIn.Application.ActiveDocument.Sections[1].Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.StoryType;

    Microsoft.Office.Interop.Word.Range workingStoryRange = null;

    foreach (Microsoft.Office.Interop.Word.Range storyRange in Globals.ThisAddIn.Application.ActiveDocument.StoryRanges)
    {
        if (storyRange.StoryType != enumWdStoryType)
        {
            continue;
        }

        workingStoryRange = storyRange;

        do
        {
            // Find and replace text in the current story
            found = workingStoryRange.Find.Execute(FindText: ref wfrFindText, MatchCase: ref wfrMatchCase, MatchWholeWord: ref wfrMatchWholeWord, MatchWildcards: ref wfrMatchWildCards, MatchSoundsLike: ref wfrMatchSoundsLike, MatchAllWordForms: ref wfrMatchAllWordForms, Forward: ref wfrForward, Wrap: ref wfrWrap, Format: ref wfrFormat, ReplaceWith: ref wfrReplaceWith, Replace: ref wfrReplace, MatchKashida: ref wfrMatchKashida, MatchDiacritics: ref wfrMatchDiacritics, MatchAlefHamza: ref wfrMatchAlefHamza, MatchControl: ref wfrMatchControl);

            // The call to SearchAndReplaceInStory above misses text that is contained in a StoryType/StoryRange nested in a different 
            // StoryType /StoryRange. While this won't occur with a nested StoryType/StoryRange in the wdMainTextStory StoryRange, it 
            // will occur in header and footer type StoryRanges. An example is textbox that is located in a header or footer. The fix 
            // makes use of the fact that Textboxes and other Drawing Shapes are contained in a document’s ShapeRange collection. 
            // Check the ShapeRange in each of the six header and footer StoryRanges for the presence of Shapes. If a Shape is found, 
            // check each Shape for the presence of the text, and finally, if the Shape contains text we set our search range to that 
            // Shape's .TextFrame.TextRange. 
            switch (workingStoryRange.StoryType)
            {
                // Case 6 , 7 , 8 , 9 , 10 , 11
                case Microsoft.Office.Interop.Word.WdStoryType.wdEvenPagesHeaderStory:
                case Microsoft.Office.Interop.Word.WdStoryType.wdPrimaryHeaderStory:
                case Microsoft.Office.Interop.Word.WdStoryType.wdFirstPageHeaderStory:
                case Microsoft.Office.Interop.Word.WdStoryType.wdEvenPagesFooterStory:
                case Microsoft.Office.Interop.Word.WdStoryType.wdPrimaryFooterStory:
                case Microsoft.Office.Interop.Word.WdStoryType.wdFirstPageFooterStory:

                    if (workingStoryRange.ShapeRange.Count > 0)
                    {
                        foreach (Microsoft.Office.Interop.Word.Shape shape in workingStoryRange.ShapeRange)
                        {
                            if (shape.TextFrame.HasText != 0)
                            {
                                found = shape.TextFrame.TextRange.Find.Execute(FindText: ref wfrFindText, MatchCase: ref wfrMatchCase, MatchWholeWord: ref wfrMatchWholeWord, MatchWildcards: ref wfrMatchWildCards, MatchSoundsLike: ref wfrMatchSoundsLike, MatchAllWordForms: ref wfrMatchAllWordForms, Forward: ref wfrForward, Wrap: ref wfrWrap, Format: ref wfrFormat, ReplaceWith: ref wfrReplaceWith, Replace: ref wfrReplace, MatchKashida: ref wfrMatchKashida, MatchDiacritics: ref wfrMatchDiacritics, MatchAlefHamza: ref wfrMatchAlefHamza, MatchControl: ref wfrMatchControl);
                            }
                        }
                    }

                    break;

                default:
                    break;
            }

            workingStoryRange = workingStoryRange.NextStoryRange;

        } while (workingStoryRange != null);
    }

    return new ClsFindReplaceResults(found, Globals.ThisAddIn.Application.Selection);
}

问题中的代码是在 Range 对象上搜索,因此选择不会改变。只需使用 Range 作为新内容的 "target"。

问题中的代码非常复杂,很难准确理解发生了什么......但简单来说:

bool found = workingStoryRange.Find.Execute(FindText: ref wfrFindText, MatchCase: ref wfrMatchCase, 
  MatchWholeWord: ref wfrMatchWholeWord, MatchWildcards: ref wfrMatchWildCards, MatchSoundsLike: ref wfrMatchSoundsLike, 
  MatchAllWordForms: ref wfrMatchAllWordForms, Forward: ref wfrForward, Wrap: ref wfrWrap, Format: ref wfrFormat, 
  ReplaceWith: ref wfrReplaceWith, Replace: ref wfrReplace, MatchKashida: ref wfrMatchKashida, 
  MatchDiacritics: ref wfrMatchDiacritics, MatchAlefHamza: ref wfrMatchAlefHamza, MatchControl: ref wfrMatchControl);

if (found)
{
  //Work with a duplicate of the original range so as not to "destroy" it
  //may not be needed, but included for "in case"
  Word.Range rngFound = workingStoryRange.Duplicate;
  //go to the end - the point just after the found content
  rngFound.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
  rngFound = "\nText in new paragraph.";
  rngFound.Font.Size = 9
  rngFound.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphJustify;
  rngFound.ParagraphFormat.SpaceAfter = 6f;
}

注意:为这种格式创建 style 会更正确。然后可以根据需要在一个步骤中应用格式。 A款有以下优点

  • 如果以后要更改格式,更改样式定义是一件简单的事情 - 在一个地方,一个动作 - 而不是需要在文档中查找和更改每个格式实例
  • 使用样式应用格式减少了内存管理量,尤其是 "scratch files" Word 用来维护 "Undo list"。畜栏:撤消列表更短。