Word VBA将段落缩进与标题文本匹配

时间:2016-08-23 16:17:52

标签: vba ms-word word-vba

如何将段落与编号标题的文本部分对齐? 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

我知道CharacterUnitLeftIndent,CharacterUnitFirstLineIndent,FirstLineIndent等属性,但经过几个小时的实验和实验。在线搜索无法弄清楚如何以编程方式实现此目的。我知道如何测试标题样式以及如何引用以下段落,所以只需要知道如何正确缩进。

1 个答案:

答案 0 :(得分:1)

要使用宏来完成此操作,您必须检查文档中的每个段落,并检查它是否是"标题"样式。如果是,则选择第一个制表位的值,将其设置为后续段落的缩进。

  

UPDATE1:以下代码的早期版本将段落设置为Document级别第一个制表位,并且未准确抓取Heading样式的制表符集。下面的代码更新准确地确定了每个Heading缩进制表位。

     

UPDATE2:我在第一份文档中使用的示例文本原文:

enter image description here

自动执行第一行缩进到前一标题的标签级别的代码是第一个示例中的原始Sub

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

结果如下所示(手动添加红线以显示对齐方式): enter image description here

如果希望整个段落缩进与标题样式对齐,则代码将修改为:

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

结果文本如下所示: enter image description here