Last active
January 16, 2018 20:59
-
-
Save finsterthecat/b32e4ccb65da8a9f101c9163d8deba56 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
' Alt-F11 in Word to get into VBA mode | |
' Then Insert>>Module | |
' Paste this in and Run | |
Public Sub CreateOutline() | |
Dim docOutline As Word.Document | |
Dim docSource As Word.Document | |
Dim rng As Word.Range | |
Dim astrHeadings As Variant | |
Dim strText As String | |
Dim intLevel As Integer | |
Dim intItem 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) | |
Set regex = CreateObject("vbscript.regexp") | |
regex.Global = True | |
regex.pattern = "\d+\.\d+\s" | |
For intItem = LBound(astrHeadings) To UBound(astrHeadings) | |
' Get the text and the level. | |
strText = Trim$(astrHeadings(intItem)) | |
intLevel = GetLevel(CStr(astrHeadings(intItem))) | |
If (intLevel = 2) Then | |
' Add the text to the document. | |
rng.InsertAfter regex.Replace(strText, "") & vbNewLine | |
' Set the style of the selected range and | |
' then collapse the range for the next entry. | |
' Another option for Style "Heading " & intLevel | |
rng.Style = "Normal" | |
rng.Collapse wdCollapseEnd | |
End If | |
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 intDiff 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. | |
intDiff = Len(strOriginal) - Len(strTemp) | |
GetLevel = (intDiff / 2) + 1 | |
End Function | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment