使用VBA在Word2010中找到选择后的文本

时间:2015-11-05 23:56:24

标签: vba ms-word

我试图删除在找到的所选文本之后立即发生的一组句子(可能是1或更多)。我使用Selection.Find来查找文本,但是我无法找到任何允许我删除的内容,而不是删除选择本身。

以下是代码片段:

        Selection.Find.ClearFormatting
        With Selection.Find
            .Text = req
            .Replacement.Text = ""
            .Forward = True
            .Format = False
            .MatchCase = False
            .MatchWholeWord = True
            .MatchAllWordForms = False
            .MatchSoundsLike = False
            .MatchWildcards = False
        End With

        'execute search
        Selection.Find.Execute

         If Selection.Find.Found Then
            'Found the tag, check for a duplicate
            Selection.Find.Execute
            If Selection.Find.Found Then
               'Found a duplicate
               err = True
               err_req = err_req & " " & req
            Else
                num_updated = num_updated + 1
                'Update the requirements text
                ' TODO: Delete the current requirements text
                Selection.InsertAfter req_text_list(index)
                'Set the requirement style
                Selection.GoTo what:=wdGoToBookmark, Name:="\Para"
                Selection.Style = ActiveDocument.Styles(STYLE_NAME_RQMT)
                Selection.Collapse Direction:=wdCollapseEnd
            End If
        End If

非常感谢任何帮助。谢谢:))

1 个答案:

答案 0 :(得分:0)

不是删除单词,而是用“”替换单词更好更快。我在下面的代码中使用过它。根据您的要求使用它

Sub Wordsearchh()
Dim rWord As Range
Dim Search_Text As String
Dim Next_Word_Rang As Range
Set Next_Word_Rang = ActiveDocument.Range 


For Each rWord In ActiveDocument.Words
    Search_Text = rWord.Text 

    Next_Word_Rang.Start = rWord.End
    Next_Word_Rang.End = ActiveDocument.Range.End
        With Next_Word_Rang.Find 

            .Execute FindText:=Search_Text, Forward:=True

            If .Found = True Then
            .Replacement.Text = ""
            .Execute Replace:=wdReplaceAll
           End If
        End With
Next
End Sub