如何使用宏捕获Word文档中段落的行数?

时间:2019-06-24 15:33:16

标签: vba ms-word

我正在处理Word文档上的间距,我需要根据上一段的行数来更改分页符的位置和空白段落的数量,以使宏输入的​​间距保持不变,以便2个字段可以在同一页面上由ClientName和Date子项输入。

我使用了座席数量来改变间距,但是问题是某些座席的信息要比其他座席占用更多的空间,因此可变长度段落可能具有不同的行数,即使代理商是一样的。这导致宏有时生成空白页,这是我不想要的。 HIPAANumber变量是存储表单上有多少个代理的变量。我在编写选集时查看了这些选项。和Selection.Paragraph。但似乎没有一个选项可以捕获我需要的信息。

With Selection
     If HIPAANumber > 2 And HIPAANumber < 5 Then
            .InsertBreak Type:=wdPageBreak
     End If

 Call ClientNameandDate(ClientName) 'The Sub inputs the Date and Client's Name fields. These fields always take up the same amount of space.
 .TypeParagraph
 If HIPAANumber <= 2 Then
      .InsertBreak Type:=wdPageBreak
 Else
      .TypeParagraph
 End If
End With


Private Sub ClientNameandDate(ClientName)

    Selection.TypeParagraph

    With Selection
        .ParagraphFormat.Alignment = wdAlignParagraphLeft
        .TypeText Text:="_______________________________" 'This code inputs the Date field
        .TypeText Text:=Chr(11)
        .TypeText Text:="Date"
        .TypeParagraph
        .Font.Size = 4
        .TypeText Text:=Chr(11)
        .Font.Size = 12
        .TypeText Text:=vbTab & vbTab & vbTab & vbTab & vbTab & vbTab & "__________________________________________"
        .TypeText Text:=Chr(11)
        .TypeText Text:=vbTab & vbTab & vbTab & vbTab & vbTab & vbTab
        .Font.Bold = True
        .TypeText Text:=UCase(ClientName)

    End With
End Sub

'''

我真的不知道如何在VBA中使用对象,因此,如果有人可以解释如何为此使用对象,我将不胜感激。我认为最简单的方法是捕获具有可变长度的段落中的文本行数,然后在If语句中使用它,但是我不知道如何捕获文本的行数一段。

1 个答案:

答案 0 :(得分:0)

Information属性可以返回行号,如以下代码所示。

Sub CountLinesInTheSelectedParagraph()
    Dim rngFirst As Range, rngLast As Range

    Set rngFirst = Selection.Range
    rngFirst.Expand Unit:=wdParagraph
    rngFirst.Collapse Direction:=wdCollapseStart

    Set rngLast = Selection.Range
    rngLast.Expand Unit:=wdParagraph
    rngLast.Collapse Direction:=wdCollapseEnd

    Debug.Print _
        rngLast.Information(Type:=wdFirstCharacterLineNumber) _
        - rngFirst.Information(Type:=wdFirstCharacterLineNumber) _
        & " lines in the selected paragraph"
End Sub
相关问题