Home > database >  Extend selection until it includes a PageRef field
Extend selection until it includes a PageRef field

Time:09-27

I have a Word document that contains cross-references:

See "Start the machine" on page 15.

The text "Start the machine" is a hyperlink object, and '15' is a PageRef field. I want to use a macro to apply a character style to "Start the machine" on page 15.

I created this macro that finds the hyperlink. My idea was to select the link, and extend the selection until it contains the PageRef.

Sub ExtendCrossref()
    Dim HL As Hyperlink
    For Each HL In ActiveDocument.Hyperlinks
    HL.Range.Select
    Do Until Selection.Fields.Count > 1
        Selection.Range.MoveEnd wdWord, 1
    Debug.Print Selection
    Loop
    Next
End Sub

I can't get Selection.Range.MoveEnd to work: after the loop, the selection remains "Start the machine" when it should be "Start the machine" on. I've also tried Selection.Extend, didn't work either.

How can I add words to the selection?

CodePudding user response:

The problem with your code is that Selection.Range returns a new Range object. The new range object is the one to which the MoveEnd applies. Each time through the loop you regenerate Selection.Range so the range of the Selection is never extended. You need to change to

Selection.MoveEnd wdWord, 1
  • Related