0
votes

I am trying to write some code that will search through all the stories including headers, footers, footnotes etc and then stop at each occurrence so the user can make a decision about it (it may or may not change), then click a button again to move to the next occurrence (like Word's Find Next).

I am aware there is some pretty tricky code for performing a search and replace using the range object and I have that code working for another part of this project, but what I can't do is make it search and stop at the selected text, then carry on looking in the different stories, it just stops at the end of the main document.

The code below looks as though it should work but even if the footnote for example has the text to be searched for, it is ignoring it. I have done a thorough search of this site and others and have found several examples for search and replace, but none for search and stop/select.

Any advice gratefully received - thank you.

Sub TestSelection()

    Dim rngStory As Range
    Dim docDocument As Document

    Set docDocument = ActiveDocument

    With docDocument
        For Each rngStory In .StoryRanges
           Select Case rngStory.StoryType
                Case 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
                    Debug.Print rngStory.StoryType

                    With Selection.Find
                    .ClearFormatting
                        .Text = "XYZ"
                        .Replacement.Text = ""
                        .Forward = True
                        .Wrap = wdFindStop
                        .Format = True
                        .MatchCase = False
                        .MatchWholeWord = False
                        .MatchWildcards = False
                        .MatchSoundsLike = False
                        .MatchAllWordForms = False
                    End With
                    Selection.Find.Execute

                        If Selection.Find.Found = True Then
                            Exit Sub
                        End If

                    End Select

        Next rngStory
    End With
End Sub
1

1 Answers

0
votes

Whether this is your problem in this case I don't know, but while your loop iterates over all the ranges returned by StoryRanges, it does not process the entire document. It only includes the first part of each story. (So, for example, if there are several sections in your document, it will only include the header & footer from the first section).

You need to use the NextStoryRange method in order to access the entire story. Look that up in VBA help for an example loop construct. (It's a horrible API - just as bad as Range.Find!).

Also, be aware that executing a search will change the selection, so Selection.Find will suddenly be searching in the last result, rather than the entire range.