vbams-wordword-2007

Selecting word text in a for loop


I created this code to search through my word document and find the word APPENDIX3, and if found, delete it and the space before it (section break in this case). It then subtracts the number 3 by 1 and goes back to the top of the for loop and searches for APPENDIX2 and deletes the stuff I wanted. It loops through 3 times, ending at APPENDIX1. The only problem is that it only deletes the APPENDIX3 stuff. If I rerun the Macro it will delete APPENDIX2 and only APPENDIX2. On so on. It is incrementing but the selection does not appear to be cleared. Any suggestions as to how I can modify my code to loop through and select different text each time?

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

Solution

  • Figured it out. I needed to either go to the top of the page within the loop instead of before the loop, or I had to wrap the text search during find. Updated script looks like this:

    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