How to delete a section using excel-vba to create a word document

吃可爱长大的小学妹 提交于 2019-12-06 15:30:18

This appears as a question about Find/Replace but more correctly is a question about Find, then do something at the site of the found text. Its a common requirement when the replacement criteria isn't covered by the options of the find/Replace. The requirement is addressed by the pattern below..

    With <Range>
        With .Find
            <setup find criteria for find>
            .wrap = wdFindStop ' This is essential
        End with
        Do while .Find.Found
            <do your actions here>
            <use .duplicate if you want to do something with the found range
            <e.g. to delete the paragraph with the found text
            .duplicate.paragraphs(1).range.delete
            <move the found range to after the end of the found range>
            .collapse direction:=wdcollapseend
            .moveend unit:=wdCharacter, count:=1
            .find.execute ' must include this to find next instance

        loop

    End with <range>

Translating this pattern into code gives

Sub DeleteParasWithText(this_doc As Word.Document, this_find_text As String)

    With this_doc.content
            With .Find
                .ClearFormatting
                .Replacement.ClearFormatting
                .text = this_find_text
                .Wrap = wdFindStop
                .Format = False
                .MatchCase = False
                .MatchWholeWord = False
                .MatchByte = False
                .MatchWildcards = False
                .MatchSoundsLike = False
                .MatchAllWordForms = False
                .Execute

            End With

            Do While .Find.Found
                ' In the OP case we just want to delete the paragraph
                ' containing the found text
                .Duplicate.Paragraphs(1).Range.Delete
                .Collapse Direction:=wdCollapseEnd
                .Move unit:=wdCharacter, Count:=1
                .Find.Execute
            Loop

        End With
End Sub

In presenting this I'd also like to acknowledge @Macropod as I derived this pattern from a number of find/replace examples he has presented in the past.

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