I’m getting consistent bugginess trying to search for the Normal style using a Range if (1) there’s a table in the document, and (2) either there are no Normal paragraphs in the document or the only Normal paragraphs precede the table.
To take a simple example: If I create a new document consisting of nothing but a handful of Body Text paragraphs and a table (with the table positioned several paragraphs down from the start of the document), and then I run the following code:
Dim rngX As Word.Range Dim lngCount As Long Set rngX = ActiveDocument.Range(0, 0) With rngX.Find .Text = "" .Style = "Normal" .Format = True End With With rngX Do While .Find.Execute = True lngCount = lngCount + 1 Debug.Print "Found at " & .Start & ", " & .End .Collapse wdCollapseEnd If lngCount = 3 Then Exit Do End If Loop End With Set rngX = Nothing
the result in the Immediate Window is:
Found at 0, 0 Found at 0, 0 Found at 0, 0
Somehow .Find.Execute is returning True and yet rngX isn’t moving forward to any found target. The code would loop endlessly if not for the “If lngCount = 3” exit line. And what’s worse: If I set up the code so that it’s replacing Normal with another style, Word tends to crash. (During one series of tests, it was pretty consistently crashing the 2nd time I ran the macro — as if the first execution somehow put the document (or Word) in an unstable state, after which the 2nd execution delivered the knockout punch.)
Some further experimentation involving the Selection object leads me to the conclusion that it’s the end-of-row-markers in the table that are causing the problem. They’re “Normal” style but they confuse Range.Find objects.
Further note: If I change one of the paragraphs after the table to Normal style and then run the code, it works perfectly. (Likewise if I start the .Find with the Range already located after the table.)
I realize one possible “solution” is to just make sure none of my documents ever have any “Normal” paragraphs (not counting end-of-row-markers), so I never have any reason to run a procedure that searches for the Normal style. Perhaps another “solution” would be to use the Selection object, although I don’t really know that it’s not also subject to some bugginess in this area.
Is there a more direct solution — i.e., a way to prevent the end-of-row markers from screwing up the Range.Find object?