简体   繁体   中英

How to reference MS Word table of contents page numbers with Excel VBA?

I am trying to use the page numbers to the right-hand side of a table of contents object in Word in some VBA code. I can access the array storing the text associated with these page numbers using GetCrossReferenceItems(wdRefTypeHeading) but cannot seem to get at the page numbers themselves. None of the GetCrossReferenceItems constants listed here seem relevant.

在此处输入图片说明

Is there a way to reference these page numbers? Thanks!

I'm not a "Worder" so here is what I came up to:

Function GetPagesNumber(doc As Document) As Long()
    Dim i As Long
    Dim myRng As Range
    Dim myHeadings As Variant

    With doc
        Set myRng = .Content
        myRng.Collapse Direction:=wdCollapseEnd

        myHeadings = .GetCrossReferenceItems(wdRefTypeHeading)
        ReDim pages(1 To UBound(myHeadings)) As Long
        For i = 1 To UBound(myHeadings)
            myRng.InsertCrossReference ReferenceType:=wdRefTypeHeading, ReferenceKind:=wdPageNumber, ReferenceItem:=i
            With .Paragraphs(ActiveDocument.Paragraphs.count).Range
                myRng.SetRange Start:=.Start, End:=.End - 1
            End With
            pages(i) = CLng(myRng.Text)
        Next i
    End With
    myRng.Delete
    GetPagesNumber = pages
End Function

to be used like follows:

Option Explicit
Sub main()
    Dim myPagesNumber() As Long

    myPagesNumber = GetPagesNumber(ActiveDocument) '<-- store index pages numbers in myPagesNumber 
End Sub

Instead of using;

myHeadings = .GetCrossReferenceItems(wdRefTypeHeading)

You can also use;

Dim myField As Field
Set myField = ActiveDocument.TablesOfContents(1).Range.Fields(1)
myHeadings = Split(myField.Result.Text, Chr(13))

This will return an array of strings, with within the last characters of the array the page number of the heading. Use pgnr = CInt(Right(myHeadings (i), Len(myHeadings (i)) - InStrRev(myHeadings (i), Chr(9)))) to get the pagenumber.

What would be better is to first split myHeadings into rows with Chr(13) as delimiter and then split into columns with Chr(9) as delimiter.

So the whole table of contents in an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM