Unexplainable Find Behavior

G

Greg

MVP Graham Mayor was proofing a macro that we were
discussing offline. He noted the macro did not function
properly if a STYLEREF field was used. To demostrate I am
providing a bit of code that demonstrates the prolem.

Expected result. Find occurrences of text, if found:
1. Count, 2. Highlight.

Problem. Text created as a result of a STYLEREF Field
results in erratic behaviour. Each occurrence of the find
word generated is counted, but the word "may or may not"
be highlight. The "may or may not" part is even more
puzzling.

STYLEREF text in the header/footer is never highlighted.
STYLEREF text in the main body will be marked. However if
a Textbox containing the same STYLEREF text is present
then the STYLEREF text in the main body is not marked.
Wierd, Wierd, Weird.

Any thoughts on explaining this behavior?

Thanks

Here is the code if you want to experiment for yourself:

Public Sub Test()

Dim oRngStory As Word.Range
Dim strSearch As String

strSearch = InputBox("Type in the word or phrase that you
want to find.")
MakeHFValid
pCounter = 0
For Each oRngStory In ActiveDocument.StoryRanges
Do
SearchAndReplaceInStory oRngStory, strSearch,
strReplace
Set oRngStory = oRngStory.NextStoryRange
Loop Until oRngStory Is Nothing
Next
MsgBox ("Found " & pCounter & " times")
End Sub
Public Sub SearchAndReplaceInStory(ByVal oRngStory As
Word.Range, _
ByVal strSearch As
String, _
ByVal strReplace As
String)

Do Until (oRngStory Is Nothing)
With oRngStory.Find
.ClearFormatting
.Text = strSearch
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
Do While .Execute
With oRngStory
.HighlightColorIndex = wdBrightGreen
.Collapse wdCollapseEnd
End With
pCounter = pCounter + 1
Loop
End With
Set oRngStory = oRngStory.NextStoryRange
Loop
End Sub
Public Sub MakeHFValid()
Dim lngJunk As Long
lngJunk = ActiveDocument.Sections(1).Headers
(1).Range.StoryType
End Sub
 
C

Chad DeMeyer

Without stepping through the code to do a thorough test and debug, my
initial suspicion is that this is a byproduct of the bizarre For Each with
nested Do Loop construction that we are forced to use to make Word find text
in all the storyranges. If you have not already done so, try stepping
through the code one command at a time (F8) and verify that it is searching
the storyranges in the way you expect.

Regards,
Chad
 
G

Greg Maxey

Chad,

Done that several times. The fact that the words are
counted pretty much proves that they are being found.
That's what I think.

Thanks for taking a shot at it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top