0

I am using VBA to loop through each row of a word table and perform a specific calculation. If a cell in a row has a certain value (lets say >= 100), I add another row, right beneath the active row.

My problem: I loop from i to the last row. However, the latter can change during the execution of the loop (by adding more rows). So while the count of the "last row" might be 10 in the beginning, it can be higher at the end. Yet, it seems that VBA only works with the initial value. Is there a way to update the upper limit of the For condition while in the loop (tell VBA to loop longer than initially expected)?

Here is an example of my code:

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

For testing this code, a table needs to be created that contains some value in the cells of the second column (starting from column 2). When the value <100, Test1 appers in the cell to the right, when the value is >=100, a new row is inserted and Test2 appears in a cell of this new row.

Any help would be greatly appreciated.

braX
  • 11,506
  • 5
  • 20
  • 33
Dennis
  • 7
  • 7
  • Very similar question to https://stackoverflow.com/questions/19409644/change-length-of-for-loop-while-in-the-loop And there may be others... –  Jun 29 '20 at 09:40
  • With the solution presented in the link you posted (while loop, instead of for), I was able to get my code working. Thank you very much! – Dennis Jul 04 '20 at 20:14

0 Answers0