【问题标题】:How do you capture the number of lines in a paragraph in a word document using a macro?如何使用宏捕获 word 文档中段落中的行数?
【发布时间】:2019-11-06 10:53:17
【问题描述】:

我正在处理 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 语句中使用它,但我不知道如何捕获文本的行数一个段落。

【问题讨论】:

  • 段落格式可能是一种控制分页符的简单方法。您之前是否尝试过保持下一个、保持行在一起和分页,但排除了段落格式作为解决方案?
  • 我的建议是使用 Word 的内部 STYLE 功能来解决这个问题。第一个字段/段落的段落样式,第二个段落样式。第一个应该有段落格式“保持与下一个”以及“保持行在一起”。第二个将具有“Keep with Next”但将具有“Keep together”。无论如何,这将确保两个段落保持在同一页面上。不需要宏...

标签: vba ms-word


【解决方案1】:

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

【讨论】:

  • 谢谢你。在测试代​​码时,它始终输出比段落中的行数少 1,因此我只是将其加 1 以获得段落中的行数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
相关资源
最近更新 更多