循环以添加重复的空行,直到Word文档的结尾

时间:2015-12-04 17:44:45

标签: vba ms-word word-vba

我试图写一个宏来为某人分解一长串地址。基本上,宏需要在每三行后添加一个空行并对整个文档重复此过程。我已经采取了初步行动,但我无法弄清楚如何让它重复并在文档的最后停止。我已经在线搜索并继续查找仅适用于Excel中的情况的循环。我不确定如何指定循环何时应在Word中结束。

这就是我现在所拥有的:

Sub AddFix ()

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

EndSub

如何让这个子工作完整整个文档?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-1)

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

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