CODE‎ > ‎VBA‎ > ‎

word建立索引

先幫word建立一個巨集檔,然後進入編輯那個巨集檔
把以下程式複製進去

首先決定你要建立幾個關鍵字的索引,從0開始到n-1
然後將關鍵字一一填入陣列裡面,完成後就可以把游標放置到你要放索引的地方再執行那個巨集,得到以下結果


Dim keyword(0 To 3) As String
 
keyword(0) = "Windows"
keyword(1) = "Word"
keyword(2) = "excel"
keyword(3) = "貼上"

 
For i = 0 To 3
 
    Selection.GoTo What:=wdGoToHeading, Which:=wdGoToFirst
    Pages = ""
    Text = keyword(i)
    lastPages = ""
    Do While Selection.Find.Execute(Text) = True
        If lastPages <> Selection.Information(wdActiveEndPageNumber) Then
            lastPages = Selection.Information(wdActiveEndPageNumber)
            If Pages <> "" Then
                Pages = Pages & ", "
            End If
            Pages = Pages & lastPages
        End If
    Loop
    
    Selection.GoTo What:=wdGoToPage, Which:=wdGoToLast
    Line = Text + vbTab + vbTab + Pages + vbCrLf
    ActiveDocument.Content.InsertAfter Line
 
Next i


Comments