2
votes

How can I align a paragraph with just the text portion of a numbered heading? e.g:

1.1.2   This Is A Numbered Heading
        This is the aligned text I'm trying to achieve
This is aligned to the numbers not the text

2.4 This Is Another Example
    This is where the text should be

I'm aware of the CharacterUnitLeftIndent, CharacterUnitFirstLineIndent, FirstLineIndent etc properties but after a few hours experimentation & searching online can't figure out how to achieve this programmatically. I know how to test for the heading style and how to refer to the following paragraph so just need to know how to get the indent right.

1

1 Answers

2
votes

To use a macro to accomplish this, you have to check each paragraph in your document and check to see if it is a "Header" style. If so, then pick off the value of the first tab stop to set as the indent for the subsequent paragraphs.

UPDATE1: the earlier version of the code below set the paragraphs to the Document level first tab stop, and did not accurately grab the tabstop set for the Heading styles. The code update below accurately determines each Heading indent tab stop.

UPDATE2: the sample text original I used in shown in this first document:

enter image description here

The code that automatically performs a first line indent to the tab level of the preceding heading is the original Sub from the first example:

Option Explicit

Sub SetParaIndents1()
    Dim myDoc As Document
    Set myDoc = ActiveDocument

    Dim para As Paragraph
    Dim firstIndent As Double   'value in "points"
    For Each para In myDoc.Paragraphs
        If para.Style Like "Heading*" Then
            firstIndent = myDoc.Styles(para.Style).ParagraphFormat.LeftIndent
            Debug.Print para.Style & " first tab stop at " & _
                        firstIndent & " points"
        Else
            Debug.Print "paragraph first line indent set from " & _
                        para.FirstLineIndent & " to " & _
                        firstIndent
            para.FirstLineIndent = firstIndent
        End If
    Next para

    '--- needed to show the changes just made
    Application.ScreenRefresh

End Sub

And the results looks like this (red lines added manually to show alignment): enter image description here

If you want the entire paragraph indented in alignment with the heading style, the code is modified to this:

Option Explicit

Sub SetParaIndents2()
    Dim myDoc As Document
    Set myDoc = ActiveDocument

    Dim para As Paragraph
    For Each para In myDoc.Paragraphs
        If para.Style Like "Heading*" Then
            '--- do nothing
        Else
            para.Indent
        End If
    Next para

    '--- needed to show the changes just made
    Application.ScreenRefresh

End Sub

And the resulting text looks like this: enter image description here