Search text with Content.Find object in Word with

2019-08-13 14:46发布

问题:

I want to search an entire MSWord document for a text with wildcards and recover the strings found.

something like that:

Sub Macro1()
    Dim c As Range
    Set c = ActiveDocument.Contentsdf
    c.Find.ClearFormatting
    c.Find.Replacement.ClearFormatting
    With c.Find
        .Text = "start[abcde]end"
        .Replacement.Text = ""
        .Forward = True
        .wrap = wdFindStop
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = True
        .MatchSoundsLike = False
        .MatchAllWordForms = False '
    End With

    c.Find.Execute
    While c.Find.Found
        Debug.Print c.Find.TextFound
        c.Find.Execute
    Wend
End Sub

but the method c.Find.TextFound does not exists. Is there any way to recover the text without recurring to Selection.Text?

回答1:

Try this.

Sub Sample()
    Dim c As Range
    Dim StartWord As String, EndWord As String

    StartWord = "Start": EndWord = "End"

    Set c = ActiveDocument.Content
    c.Find.ClearFormatting
    c.Find.Replacement.ClearFormatting
    With c.Find
        .Text = StartWord & "*" & EndWord
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = True
        .MatchSoundsLike = False
        .MatchAllWordForms = False '
    End With

    c.Find.Execute
    While c.Find.Found
        Debug.Print c.Text
        '~~> I am assuming that the start word and the end word will only
        '~~> be in the start and end respectively and not in the middle
        Debug.Print Replace(Replace(c.Text, StartWord, ""), EndWord, "")
        c.Find.Execute
    Wend
End Sub