Getting the headings from a Word document

后端 未结 7 1192
挽巷
挽巷 2020-11-30 04:11

How do I get a list of all the headings in a word document by using VBA?

7条回答
  •  天命终不由人
    2020-11-30 04:39

    Following Wikis comment on VonC answer, here is the code that worked for me. It makes the function faster.

    Public Sub CopyHeadingsInNewDoc()
        Dim docOutline As Word.Document
        Dim docSource As Word.Document
        Dim rng As Word.Range
    
        Dim astrHeadings As Variant
        Dim strText As String
        Dim longLevel As Integer
        Dim longItem As Integer
    
        Set docSource = ActiveDocument
        Set docOutline = Documents.Add
    
        ' Content returns only the
        ' main body of the document, not
        ' the headers and footer.
        Set rng = docOutline.Content
        astrHeadings = _
         docSource.GetCrossReferenceItems(wdRefTypeHeading)
    
        For intItem = LBound(astrHeadings) To UBound(astrHeadings)
            ' Get the text and the level.
            strText = Trim$(astrHeadings(intItem))
            intLevel = GetLevel(CStr(astrHeadings(intItem)))
    
            ' Add the text to the document.
            rng.InsertAfter strText & vbNewLine
    
            ' Set the style of the selected range and
            ' then collapse the range for the next entry.
            rng.Style = "Heading " & intLevel
            rng.Collapse wdCollapseEnd
        Next intItem
    End Sub
    
    Private Function GetLevel(strItem As String) As Integer
        ' Return the heading level of a header from the
        ' array returned by Word.
    
        ' The number of leading spaces indicates the
        ' outline level (2 spaces per level: H1 has
        ' 0 spaces, H2 has 2 spaces, H3 has 4 spaces.
    
        Dim strTemp As String
        Dim strOriginal As String
        Dim longDiff As Integer
    
        ' Get rid of all trailing spaces.
        strOriginal = RTrim$(strItem)
    
        ' Trim leading spaces, and then compare with
        ' the original.
        strTemp = LTrim$(strOriginal)
    
        ' Subtract to find the number of
        ' leading spaces in the original string.
        longDiff = Len(strOriginal) - Len(strTemp)
        GetLevel = (longDiff / 2) + 1
    End Function
    

提交回复
热议问题