Search text with Content.Find object in Word with VBA and recover the text found

[亡魂溺海] 提交于 2019-12-11 09:42:21

问题


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



回答2:


I've been searching for a way to print a certain number of pages as long as it has a certain word.

Basically I have 3 files and I have to print them and organize them by shifts. Each of them as the words Shift 1 2 and 3 on them. I managed to put them all printing at once but I want to print Shift 1 from the first file, shift 2 from the second file, and so on till shift 3 of file 5. I just need a macro code that will search the word "shift 1" in the file and print only the pages that contain that word. Then is basically applying the same code to all the files, changing 1 to 2 and to 3.

Correct me if I'm wrong.



来源:https://stackoverflow.com/questions/11480421/search-text-with-content-find-object-in-word-with-vba-and-recover-the-text-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!