使用vba读取目录

时间:2017-07-31 15:20:24

标签: arrays vba ms-word tableofcontents

我试图在不读取页码的情况下阅读word文档中的目录。我想读取表并将其保存到数组中。编码不是我的强项,如果这个问题针对的是错误的区域,请提前道歉。我有以下代码,我发现内联,它读取表格和页码,但我无法弄清楚如何只读取表格。

Dim sourceDocument As Document
Set sourceDocument = ActiveDocument

Dim myField As Field
For Each myField In sourceDocument.TablesOfContents(1).Range.Fields
    Debug.Print myField.result.Text ', Chr(13), "-") & " " & " Type: " & myField.Type

   DoEvents
Next

我很感激任何帮助。

谢谢,

罗比

1 个答案:

答案 0 :(得分:0)

这应该可以帮助你:

Public Function GetTOCItems(Optional ByVal fromDocument As Document = Nothing) As Variant

    If fromDocument Is Nothing Then _
        Set fromDocument = ActiveDocument

    Dim toc As TableOfContents
    Set toc = fromDocument.TablesOfContents(1)

    toc.IncludePageNumbers = False

    Dim tocText As Variant
    tocText = toc.Range.Text

    toc.IncludePageNumbers = True

    GetTOCItems = Split(tocText, Chr(13))

End Function

你可以这样称呼它:

Dim tocItems as Variant
tocItems = GetTOCItems