【问题标题】:Loop to add blank lines that repeats until end of the Word document循环添加重复的空白行,直到 Word 文档结束
【发布时间】:2015-12-04 17:44:44
【问题描述】:

我正在尝试编写一个宏来分解某人的一长串地址。基本上,宏需要在每三行之后添加一个空行,并对整个文档重复此过程。我已经开始执行初始操作,但我不知道如何让它重复并在文档末尾停止。我在网上搜索并不断寻找仅适用于 Excel 情况的 while 循环。我不确定如何指定循环何时应在 Word 中结束。

这是我现在拥有的:

Sub AddFix ()

Do
Selection.MoveDown Unit:= wdline, Count:= 3
Selection.InsertParagraph
Loop Until (Selection.End = ActiveDocument.Content.End - 1)

EndSub

如何让这个 sub 处理整个文档?

【问题讨论】:

  • 欢迎来到 SO Peckish... 第一篇文章做得很好。我清理了一些小问题: 不要在标题中使用“标签”。还要确保你问了一个明确的问题。最后,由于这是为将来的访问者提供参考,请避免使用多余的文字。
  • 至于可能的答案:support.microsoft.com/en-us/kb/211455统计文档的行数,除以三,做一个For x = 1 to Count of Lines CODE Next x
  • 我知道我可以通过# of lines 指定一个端点,但我希望能够编写一些无论文档中有多少行都可以执行的东西。到目前为止我还没有在网上找到任何东西。
  • Peckish,您可以使用我的代码来识别流动文档上的总行数,然后通过每一行向后工作以添加您的空白行。

标签: vba ms-word


【解决方案1】:

根据 Chumble 的回答,您将希望后退一步阅读您的文本。

Sub InsertLines()

    Dim lTotalLines As Long
    Dim lCurrentLine As Long

    lTotalLines = ActiveDocument.BuiltInDocumentProperties(wdPropertyLines)

    For lCurrentLine = lTotalLines To 3 Step -3
        Selection.GoTo What:=wdGoToLine, Which:=wdGoToAbsolute, Count:=lCurrentLine
        Selection.InsertParagraph
    Next lCurrentLine

End Sub

【讨论】:

    【解决方案2】:

    这会做你想做的,但是可能有一个更紧凑的解决方案,这正是我能想到的。

    Sub InsertLines()
    
        Dim lTotalLines As Long
        Dim lCurrentLine As Long
        Dim bContinue As Boolean
    
        lTotalLines = ActiveDocument.BuiltInDocumentProperties(wdPropertyLines)
    
        If lTotalLines < 4 Then Exit Sub
    
        lCurrentLine = 4
        bContinue = True
    
        While bContinue
            Selection.GoTo What:=wdGoToLine, Which:=wdGoToAbsolute, Count:=lCurrentLine
            Selection.InsertParagraph
    
            lCurrentLine = lCurrentLine + 3
            lTotalLines = ActiveDocument.BuiltInDocumentProperties(wdPropertyLines)
            If lCurrentLine > lTotalLines Then bContinue = False
        Wend
    
    End Sub
    

    【讨论】:

    • 因为您要添加行,所以您可能希望从头开始并向后工作。否则,每次添加结束目标移动时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    相关资源
    最近更新 更多