Kem
Kem

Reputation: 31

How to detect if the previous heading in the document is heading 1 or heading 7 through VBA

My templates contain Heading 1 to 5 for normal text and Appendix headings (based on heading 7, 8 and 9).

The table and figure captions are different: based on Heading 1 or Appendix.

Works fine. But ... for now I have two buttons in the ribbon to insert the table caption:

Same for figure caption.

There must be a way to detect the previous main heading (heading 1 or heading 7 or outlinelevel 1 or 7), so I only need one button to insert a table (or figure) caption. But I just can't find it.

Upvotes: 0

Views: 197

Answers (2)

Timothy Rylatt
Timothy Rylatt

Reputation: 7860

Word contains a hidden bookmark that you can use to get the range of the current heading level. By testing the outline level of the first paragraph in that range you can determine whether you are in an appendix.

Sub TestIsAppendix()
   If IsAppendix(Selection.Range) Then MsgBox "In appendix"
End Sub

Public Function IsAppendix(ByVal para As Range) As Boolean
   Dim headingBlock As Range
   Set headingBlock = para.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
   Select Case headingBlock.Paragraphs.Item(1).OutlineLevel
      Case 7 To 9
         IsAppendix = True
      Case Else
         IsAppendix = False
   End Select
End Function

Upvotes: 0

freeflow
freeflow

Reputation: 4355

There is no specific property in Word that will return the previous level with outline level x. You will need to create a macro that loops backwards from the current paragraph until it finds outline level 1 or outline level 7.

Here are two examples of a function that return true if a preceding heading level was outline level 7 and false if it was outline level 1. The code compile without error and have no findings when inspected with the RubberDuck code inspector.

Option Explicit

'Recursive function

Public Function IsAppendixR(ByVal ipPara As Range) As Boolean

    Select Case ipPara.Paragraphs.Item(1).OutlineLevel
    
        Case 1
            IsAppendixR = False

        Case 7
            IsAppendixR = True

        Case Else
            IsAppendixR = IsAppendixR(ipPara.Previous)
            
    End Select
    
End Function


' Loop version
Public Function IsAppendixL(ByVal ipPara As Range) As Boolean

    Do
        Select Case ipPara.Paragraphs.Item(1).OutlineLevel
    
            Case 1
                IsAppendixL = False
                Exit Function
                
            Case 7
                IsAppendixL = True
                Exit Function

            Case Else
                ipPara.Previous
                
        End Select
        
    Loop
    
End Function

Upvotes: 0

Related Questions