在for循环中选择单词文本

时间:2014-04-11 00:46:27

标签: word-vba word-2007

我创建了这个代码来搜索我的word文档并找到单词APPENDIX3,如果找到,删除它和它之前的空格(在这种情况下是分节符)。然后它将数字3减去1并返回到for循环的顶部并搜索APPENDIX2并删除我想要的东西。它循环3次,结束于APPENDIX1。唯一的问题是它只删除APPENDIX3的东西。如果我重新运行宏,它将删除APPENDIX2,只删除APPENDIX2。等等。它正在递增,但选择似乎没有被清除。有关如何修改我的代码以循环并每次选择不同文本的任何建议吗?

Sub RemoveAppendices()
Dim i As Integer
Application.ScreenUpdating = False
Selection.HomeKey Unit:=wdStory
'Cntr = 3
'For i = 1 To 3
For i=3 to 1 step -1
    With Selection.Find
        .ClearFormatting
        .Text = "APPENDIX" & Cntr
        If Selection.Find.Execute Then
            Selection.Select
            Selection.Delete
            With Selection
                .EndKey Unit:=wdStory
                .TypeBackspace
                .Delete
            End With
        End If
    End With
    'Cntr = Cntr - 1

Next i
End Sub

1 个答案:

答案 0 :(得分:0)

想出来。我需要在循环内而不是在循环之前转到页面顶部,或者我必须在查找期间包装文本搜索。更新后的脚本如下所示:

Sub RemoveAppendices()
Dim i As Integer
For i = 3 To 1 Step -1
    'Selection.HomeKey Unit:=wdStory 'this would also work but I like wrap better
    With Selection.Find
        .Wrap = wdFindContinue
        .Text = "APPENDIX" & i
        .MatchWholeWord = True
        .MatchCase = True
        If Selection.Find.Execute Then
            Selection.Select
            Selection.Delete
            With Selection
                .EndKey Unit:=wdStory
                .TypeBackspace
                .Delete
            End With
        End If
    End With
Next i
End Sub