Graham, Paul,
Thanks for reacting!
I knew that I should have used ranges, but before I wrote my message I was using this:
HTML Code:
With Selection.Find
.ClearFormatting
.MatchWholeWord = True
.MatchCase = False
.ClearHitHighlight
.ClearAllFuzzyOptions
.Wrap = wdFindContinue ' needed because we don't start from first page
.Style = "Heading " & CStr(level)
Do While .Execute(FindText:=formStr)
If Selection.Paragraphs(1).Range.ListFormat.ListString = headingNumber Then
Set myRange = Selection.Paragraphs(1).Range.Duplicate
headingFound = True
Exit Do
End If
DoEvents
Loop
End With
This works, but as expected, using selection instead of ranges, the page usually ends up somewhat shifted,
after restoring the original range of the selected text.
I tried using a range instead, but then the following didn't work as desired:
HTML Code:
myRange.Paragraphs(1).Range.ListFormat.ListString
That was until I realized (thanks to you) that I should use .Parent when using ranges:
HTML Code:
.Parent.Paragraphs(1).Range
So the following works now, without the page shifting:
HTML Code:
With ActiveDocument.Range.Find
.ClearFormatting
.MatchWholeWord = True
.MatchCase = False
.ClearHitHighlight
.ClearAllFuzzyOptions
.Wrap = wdFindContinue ' needed because we don't start from first page
.Style = "Heading " & CStr(level)
Do While .Execute(FindText:=formStr)
Set myRange = .Parent.Paragraphs(1).Range
If myRange.ListFormat.ListString = headingNumber Then
headingFound = True
Exit Do
End If
DoEvents
Loop
End With
In the above, I use the heading level and heading number which were extracted from the string obtained
from the following string array:
HTML Code:
.GetCrossReferenceItems(wdRefTypeHeading)
This list provides the full header, inclusive the heading number, as single strings per header.
I search this list for all headings with text that contain my highlighted text, and created a Form that pops up when there is more than 1 match.
If there is only 1 header with the exact same text as my selection, then it is automatically selected (no Form shows), and I perform the heading search for the bookmark insertion using that heading number as reference instead of using the header text.
Both methods above work, but although it doesn't move the page, the 2nd method with the range is very slightly but noticeably slower than the selection method (I have a large document of about 700 pages here).
Thanks again for forcing me to think again about using ranges!
p.s. I do the bookmark creation an hyperlink insertion after that. If an existing bookmark exists, I first check its range, to see if it corresponds to that of the header just found. If a bookmark exists, but has different range, then I create a new bookmark by adding a simple index (1,2,...) to the bookmark name.