插入新行时动态调整最后一行

时间:2016-10-18 16:11:14

标签: vba excel-vba excel

我正在对一组数据进行循环,需要根据特定条件插入新行。但是,我的循环(基于最后一行)不考虑我插入的这些新行。在我的循环中,我添加了#34; 1"进行调整。谢谢。

Sub myLoop()

Dim lastRow As Integer: lastRow = Cells(Rows.Count, 1).End(xlUp).Row

lastCol = Cells(1, Columns.Count).End(xlToLeft).Column


For x = 1 To lastRow
  If Cells(x, 1).Value = "APHB" Then
    Rows(x).EntireRow.Copy
  End If

  If Cells(x, 1).Value = "APLB" Then
    Rows(x + 1).EntireRow.Insert

    lastRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
  End If
Next x

End Sub

1 个答案:

答案 0 :(得分:2)

你可以试试这样的......

Sub myLoop()
Dim lastRow As Integer, x as Integer

lastRow = Cells(Rows.Count, 1).End(xlUp).Row
x = 1
Do
  If Cells(x, 1) = "APHB" Then
    Rows(x).EntireRow.Copy
  ElseIf Cells(x, 1)= "APLB" Then
    Rows(x + 1).EntireRow.Insert
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
  End If
  x = x + 1
while x < = lastRow

End Sub