2016-10-13 88 views
0

我試圖在一些VBA代碼中使用Word中的內容對象表中的右側的頁碼。我可以使用GetCrossReferenceItems(wdRefTypeHeading)訪問存儲與這些頁碼關聯的文本的數組,但似乎無法自己獲取頁碼。列出的here的GetCrossReferenceItems常量都不相關。如何使用Excel VBA引用MS Word目錄頁碼?

enter image description here

有沒有參考這些頁碼的方法嗎?謝謝!

回答

1

我不是一個「劇名」,所以這裏是我走過來:

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 

使用類似如下:

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

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

@superfluous,你通過它得到什麼? – user3598756