VBA Word 宏 - 在 table 末尾插入 table 行创建无限循环

VBA Word macro - inserting table rows at end of table creates infinite loop

我正在编写一组宏来格式化文档中的一系列 table。其中一部分需要在每个 table 的末尾插入一个新行 - 但是,当我尝试使用 For Each <table> in ActiveDocument.Tables 来做到这一点时,它最终会在第一个 [=] 的底部插入无限多行=24=]。 这两个潜艇都会进入无限循环:

Sub insertBottomRow1()
    Dim theTable As Table
    Dim theNewRow As Row
    For Each theTable In ActiveDocument.Tables
        Set theNewRow = theTable.Rows.Add
        'Other row formatting
    Next theTable
End Sub

Sub insertBottomRow2()
    Dim theTable As Table
    Dim theNewRow As Row
    For Each theTable In ActiveDocument.Tables
        theTable.Rows.Last.Select
        Selection.InsertRowsBelow
        Set theNewRow = theTable.Rows.Last
        'Other row formatting
    Next theTable
End Sub

我有一个类似的子,它使用相同的结构在 table 的顶部插入一行,并且不会进入无限循环。

Sub insertTopRow()
    Dim theTable As Table
    Dim theNewRow As Row
    For Each theTable In ActiveDocument.Tables
        Set theNewRow = theTable.Rows.Add(theTable.Rows.First)
        'Other row formatting
    Next theTable
End Sub

我做了一些实验(向添加的行添加计数器,并通过调试器单步执行),崩溃的两个子程序似乎正在重新选择第一个 table 而不是移动到下一个 table。

如有任何帮助,我们将不胜感激。谢谢。

我不确定为什么你的 for each 会永远持续下去,但如果你遇到这样的问题,你可以轻松地将它转换为普通的 for 循环:

Sub insertTopRow()
    Dim theTable As Table
    Dim theNewRow As Row
    Dim i As Integer

    For i = 1 to ActiveDocument.Tables.Count
        Set theTable = ActiveDocument.Tables(i)
        Set theNewRow = theTable.Rows.Add(theTable.Rows.First)
        'Other row formatting
    Next i
End Sub

 Sub insertBottomRow()
    Dim theTable As Table
    Dim theNewRow As Row
    Dim i As Integer

    For i = 1 to ActiveDocument.Tables.Count
        Set theTable = ActiveDocument.Tables(i)
        Set theNewRow = theTable.Rows.Add
        'Other row formatting
    Next i
End Sub

您可能还想确认它是一个无限循环,您随时可以通过按 Ctrl + Pause/Break 来中断正在执行的代码。

如果“其他行格式对于顶行和底行相同”,则另一个提示是组合这些函数。您可以只创建一个布尔参数并在 'Set theNewRow =' 行周围有一个 if/else 语句。