I'm looping through a Word Document in VBA. Through each pass I'd like to search for a different word, so each pass needs to start at the beginning of the file. The current method I'm using is this, but it appears to search for the first word, and when it gets to the end of the file, moves to the second word, and searches only at the end of the file and so on with the rest of the words.
'my array of words is called myKeywords
For x = LBound(myKeywords) To UBound(myKeywords)
PageNumbers(x) = ""
'start from start of file here somehow.
With oWord.Selection.Find
.ClearFormatting()
.Text = myKeywords(x)
.Wrap = False
.Forward = True
Do While .Execute = True
If PageNumbers(x) = "" Then
PageNumbers(x) = oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
Else
PageNumbers(x) = PageNumbers(x) & ", " & oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
End If
Loop
End With
Next
Any insight is appreciated.
Edit 1
I have read through this, and I don't see anything that could help me. Wrap looks like it would help, but if I set wrap = True, I get the error "Value out of range", and I don't see how .wrap could set anything out of range.
Edit 2
I tried setting a range and resetting it at the end of the loop, but no success so far.
'my array of words is called myKeywords
Range = oWord.Selection
For x = LBound(myKeywords) To UBound(myKeywords)
PageNumbers(x) = ""
'start from start of file here somehow.
With Range.Find
.ClearFormatting()
.Text = myKeywords(x)
.Wrap = False
.Forward = True
Do While .Execute = True
If PageNumbers(x) = "" Then
PageNumbers(x) = oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
Else
PageNumbers(x) = PageNumbers(x) & ", " & oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
End If
Loop
'I've also tried several other variations of Range = other things to get this to work.
Range = Range.Select
End With
Next
Edit 3
'my array of words is called myKeywords
Range = oWord.ActiveDocument.Range(Start:=oWord.Selection.Start, [End]:=oWord.Selection.End)
For x = LBound(myKeywords) To UBound(myKeywords)
'start from start of file here somehow.
With oWord.Selection.Find
PageNumbers(x) = ""
.ClearFormatting()
.Text = myKeywords(x)
.Wrap = False
.Forward = True
Do While .Execute = True
If PageNumbers(x) = "" Then
PageNumbers(x) = oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
Else
PageNumbers(x) = PageNumbers(x) & ", " & oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
End If
Loop
Range.Select()
End With
Next