Microsoft Office Forums

Go Back   Microsoft Office Forums > >

Reply
 
Thread Tools Display Modes
  #1  
Old 07-27-2017, 08:03 AM
boywonder boywonder is offline use hyperlink in page number in index Windows 7 64bit use hyperlink in page number in index Office 2013
Novice
use hyperlink in page number in index
 
Join Date: Jul 2017
Posts: 1
boywonder is on a distinguished road
Question use hyperlink in page number in index

I use the hyperlinks to the TOC in MS Word, but is there a way to set the page number in the Index area to a hyperlink?
Reply With Quote
  #2  
Old 07-27-2017, 03:18 PM
macropod's Avatar
macropod macropod is offline use hyperlink in page number in index Windows 7 64bit use hyperlink in page number in index Office 2010 32bit
Administrator
 
Join Date: Dec 2010
Location: Canberra, Australia
Posts: 22,536
macropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond repute
Default

Indexes in Word don't support hyperlinks, for the simple reason that a given index entry could potentially reference multiple XE fields on the same page, or to XE fields spanning a range of pages; a hyperlink can only go to one such entry and, given that your document's pagination might change if you change the active printer driver, margins, etc., there is no way for Word to know beforehand which item to link to.

The following macro converts a Word Index to a hyperlinked form, where each hyperlink points to the first corresponding index entry on each explicitly-referenced indexed page.

One consequence of this approach is that the Index will no longer update, so its use would ideally be restricted to documents whose editing has been completed and are not to be viewed on systems using different printer drivers than the one on which the macro is run. That said, if you make edits to the document that change the pages on which the indexed entries occur, simply re-run the macro and the entries will be updated.

Code:
Sub IndexHyperlinker()
' Sourced from: https://www.msofficeforums.com/word/36257-use-hyperlink-page-number-index.html
Application.ScreenUpdating = False
Dim Fld As Field, Rng As Range, StrIdx As String, StrList As String, IdxTxt As String, i As Long, j As Long
StrList = vbCr
With ActiveDocument
  If .Indexes.Count = 0 Then
    If (.Bookmarks.Exists("_INDEX") = False) Or (.Bookmarks.Exists("_IdxRng") = False) Then
      MsgBox "No Index found in this document", vbExclamation: Exit Sub
    End If
  End If
  .Fields.Update
  For Each Fld In .Fields
    With Fld
      Select Case .Type
        Case wdFieldIndexEntry
          StrIdx = Trim(Replace(Replace(Split(.Code.Text, "XE ")(1), ", ", "_"), Chr(34), ""))
          If InStr(StrList, vbCr & StrIdx & ",") = 0 Then
            i = 0: StrList = StrList & StrIdx & "," & i & vbCr
          Else
            i = Split(Split(StrList, vbCr & StrIdx & ",")(1), vbCr)(0)
          End If
          StrList = Replace(StrList, StrIdx & "," & i & vbCr, StrIdx & "," & i + 1 & vbCr)
          i = i + 1: Set Rng = .Code
          With Rng
            .Start = .Start - 1: .End = .End + 1
            .Bookmarks.Add Name:=StrIdx & i, Range:=.Duplicate
          End With
        Case wdFieldIndex: IdxTxt = "SET _" & Fld.Code
        Case wdFieldSet: IdxTxt = Split(Fld.Code, "_")(1)
      End Select
    End With
  Next
  If (.Bookmarks.Exists("_INDEX") = True) And (.Bookmarks.Exists("_IdxRng") = True) Then _
    .Fields.Add Range:=.Bookmarks("_IdxRng").Range, Type:=wdFieldEmpty, Text:=IdxTxt, Preserveformatting:=False
  Set Rng = .Indexes(1).Range
  With Rng
    IdxTxt = "SET _" & Trim(.Fields(1).Code)
    .Fields(1).Unlink
    If Asc(.Characters.First) = 12 Then .Start = .Start + 1
    For i = 1 To .Paragraphs.Count
      With .Paragraphs(i).Range
        StrIdx = Replace(Split(Split(.Text, vbTab)(0), vbCr)(0), ", ", " ")
        .MoveStartUntil vbTab, wdForward: .Start = .Start + 1: .End = .End - 1
        For j = 1 To .Words.Count
          If IsNumeric(Trim(.Words(j).Text)) Then
            .Hyperlinks.Add Anchor:=.Words(j), SubAddress:=GetBkMk(Trim(.Words(j).Text), StrIdx), TextToDisplay:=.Words(j).Text
          End If
        Next
      End With
    Next
    .Start = .Start - 1: .End = .End + 1: .Bookmarks.Add Name:="_IdxRng", Range:=.Duplicate
    .Collapse wdCollapseStart: .Fields.Add Range:=Rng, Type:=wdFieldEmpty, Text:=IdxTxt, Preserveformatting:=False
  End With
End With
Application.ScreenUpdating = True
End Sub

Function GetBkMk(j As Long, StrIdx As String) As String
Dim i As Long: GetBkMk = "Error!"
With ActiveDocument
  For i = 1 To .Bookmarks.Count
    If InStr(.Bookmarks(i).Name, StrIdx) = 1 Then
      If .Bookmarks(i).Range.Information(wdActiveEndAdjustedPageNumber) = j Then _
        GetBkMk = .Bookmarks(i).Name: Exit For
    End If
  Next
End With
End Function
For PC macro installation & usage instructions, see: Installing Macros
For Mac macro installation & usage instructions, see: Word:mac - Install a Macro
__________________
Cheers,
Paul Edstein
[Fmr MS MVP - Word]
Reply With Quote
  #3  
Old 12-31-2025, 07:08 AM
CAA CAA is offline use hyperlink in page number in index Windows 11 use hyperlink in page number in index Office 2021
Novice
 
Join Date: Dec 2025
Posts: 1
CAA is on a distinguished road
Default

Thanks very much for this. I was about halfway to a similar solution when I came across your post and was able to use it to get over the final hurdle. I'm posting my code because my situation is a little different and hopefully other searchers can benefit from both solutions.

My scenario -- receive a docx file from the author; convert to docm and run a bunch of macros; save as a pdf and publish online.

I never need to relink the index in the same doc file so no need to save what was there before. My index entries have all kinds of special chars and sub-entries so I need to handle those. Also, I can rely on the INDEX field always having the switches "INDEX \e " " \c "2" \z "1033" ". I have not tested any other configurations.

A known issue with this approach is that if you have index entries A:C and B:C in that order on the same page, the B:C index hyperlink will point to the A:C bookmark. This is very unlikely to occur in our docs, and handling it in code would add a lot more complexity than value, so we accept it as a limitation.

Code:
Sub MakeBookmarks()
    Dim Fld As Field
    Dim bktext As String
    Dim Rng As Range

    With ActiveDocument
      .Fields.Update
          
        ' Loop through Index fields and turn each one into a bookmark in the form p###xxxxxxxx where ### is the page number and xxxxxxxx is
        ' the text of the sub entry that will appear in the index. Special characters are replaced with underscores.
        For Each Fld In .Fields
            If Fld.Type = wdFieldIndexEntry Then
                bktext = clnText(Fld.Code.Text) ' clean the index entry for use as a bookmark name
                Set Rng = .Range(Fld.Code.Start - 2, Fld.Code.End + 2) ' create a range to use for the bookmark, start and end should be in the visible text
                bktext = Left("p" & Rng.Information(wdActiveEndAdjustedPageNumber) & bktext, 40)
                If Not .Bookmarks.Exists(bktext) Then .Bookmarks.Add bktext, Rng
                'Debug.Print bkText
            End If
        Next
            
    End With
   
End Sub

Function clnText(s As String)
    ' Input is the text from a Word index entry field, return is a string that is suitable for use as a bookmark name
    ' This function extracts the final sub-entry from the input string (everything after the last colon)
    ' and replaces all chars that are not allowed in bookmark names with an underscore
    
    Dim i As Integer
    
    ' first get rid of the XE prefix, quotes and any leading or trailing spaces, chr147 and chr148 are curly quotes
    s = Trim(Replace(Replace(Replace(Replace(s, """", ""), Chr$(147), ""), Chr$(148), ""), " XE ", ""))
    ' if this is a sub-entry, just take the chars after the final :
    If InStrRev(s, ":") > 0 Then s = Trim(Right(s, Len(s) - InStrRev(s, ":")))
    ' replace all remaining non alpha-numeric chars with underscore
    For i = 1 To Len(s)
        If Mid(s, i, 1) Like "[!A-Za-z0-9]" Then Mid(s, i, 1) = "_"
    Next
    clnText = s
End Function

Sub IndexHyperlinker()
' Sourced from: https://www.msofficeforums.com/word/36257-use-hyperlink-page-number-index.html
Dim Rng As Range
Dim StrIdx As String
Dim j As Integer
Dim bktext As String

With ActiveDocument
  Set Rng = .Indexes(1).Range
  With Rng
    .Fields(1).Unlink ' replace index field with its text
    If Asc(.Characters.First) = 12 Then .Start = .Start + 1 ' if first char is a form feed, go to next line
    For i = 1 To .Paragraphs.Count
      With .Paragraphs(i).Range ' each paragraph is one line in the index text
        StrIdx = Split(Split(.Text, vbTab)(0), vbCr)(0) ' extract the index entry from current paragraph
        .MoveStartUntil vbTab, wdForward: .Start = .Start + 1: .End = .End - 1 ' find the page numbers in a comma separated list after the tab char
        For j = 1 To .Words.Count ' loop through the page numbers
          If IsNumeric(Trim(.Words(j).Text)) Then
            bktext = Left("p" & Trim(.Words(j).Text) & clnText(StrIdx), 40) ' reconstruct the name of the bookmark we created at the XE field location
            If ActiveDocument.Bookmarks.Exists(bktext) Then
                .Hyperlinks.Add Anchor:=.Words(j), SubAddress:=bktext, TextToDisplay:=.Words(j).Text
            Else
                Debug.Print "bookmark not found: " & bktext & "*"
            End If
          End If
        Next
      End With
    Next
  End With
End With
End Sub
Reply With Quote
  #4  
Old 01-07-2026, 12:06 PM
Charles Kenyon Charles Kenyon is offline use hyperlink in page number in index Windows 11 use hyperlink in page number in index Office 2021
Moderator
 
Join Date: Mar 2012
Location: Sun Prairie, Wisconsin
Posts: 9,636
Charles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant future
Default

Quote:
My scenario -- receive a docx file from the author; convert to docm and run a bunch of macros; save as a pdf and publish online.
There should be no need to put the macros in the document. Keep them in a separate template. You can attach the template to your document or use it as a global editing template so the macros are available in all documents.
You can attach keyboard shortcuts to your macros, which should be stored in the same template.
Global Templates (Templates in Microsoft Word - one of the Tutorials in the Intermediate Users Guide to Microsoft Word)
Reply With Quote
Reply

Tags
index, page index, toc



Similar Threads
Thread Thread Starter Forum Replies Last Post
use hyperlink in page number in index Add external hyperlink to a calculated number Harleygal17 Excel 4 04-06-2017 11:38 PM
use hyperlink in page number in index Start page number on page 3, go to page not working properly MetroBOS Word 7 01-30-2016 11:31 PM
use hyperlink in page number in index Index Hyperlink Workaround Phil H Word VBA 9 10-30-2014 05:14 AM
Page number with chapter number but not from Heading 1 alpruett Word 5 06-04-2014 02:00 PM
use hyperlink in page number in index Index page number formatting kenelder Word 1 09-06-2013 03:14 PM

Other Forums: Access Forums

All times are GMT -7. The time now is 03:58 PM.


Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2026, vBulletin Solutions Inc.
Search Engine Optimisation provided by DragonByte SEO (Lite) - vBulletin Mods & Addons Copyright © 2026 DragonByte Technologies Ltd.
MSOfficeForums.com is not affiliated with Microsoft