首页 > 解决方案 > For循环的Word VBA更新计数器

问题描述

我正在使用 VBA 循环遍历单词表的每一行并执行特定的计算。如果一行中的一个单元格具有某个值(假设 >= 100),我会在活动行的正下方添加另一行。

我的问题:我从 i 循环到最后一行。但是,后者可以在循环执行期间更改(通过添加更多行)。因此,虽然“最后一行”的计数一开始可能是 10,但最后可能会更高。然而,VBA 似乎只适用于初始值。有没有办法在循环中更新 For 条件的上限(告诉 VBA 循环的时间比最初预期的要长)?

这是我的代码示例:

Sub Table_Test()

Dim t1 As Table
Dim x As Double
Dim i As Integer
Dim Rows As Row
Dim lastRow As Integer

Set t1 = ActiveDocument.Tables(1)
lastRow = Val(ActiveDocument.Tables(1).Rows.Count) 'Since .Rows.Count is read only, I thought that by declaring my own variable, this could be the solution

MsgBox lastRow 'Just for debugging purpose

For i = 2 To lastRow 'I start from row 2, since row 1 contains the header

x = Val(t1.Cell(i, 2).Range.Text)

If x < 100 Then
    t1.Cell(i, 3).Range.Text = "Test1"
Else 'if x >= 100, execute the following code
    t1.Rows.Add BeforeRow:=t1.Rows(i + 1) 'Adds a row beneath the currently active row
    i = i + 1 'Adds "1" to the i counter so that in the next loop, the newly created row is not considered
    t1.Cell(i, 3).Range.Text = "Test2" 'writes "Test2" into cell of newly added row
    lastRow = lastRow + 1 'Adds "1" to the lastRow count
    MsgBox lastRow 'Just for debugging purpose
End If
Next i

End Sub

为了测试此代码,需要创建一个表,其中包含第二列的单元格中的一些值(从第 2 列开始)。当值 <100 时,Test1 出现在右边的单元格中,当值 >=100 时,插入一个新行,Test2 出现在这个新行的一个单元格中。

任何帮助将不胜感激。

标签: vbams-word

解决方案


推荐阅读