2016-10-18 6 views
0

データのセットに対してループを実行しており、特定の基準に基づいて新しい行を挿入する必要があります。しかし、私のループ(最後の行に基づく)は、私が挿入したこれらの新しい行を考慮していません。私のループでは、調整を行うために「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 
+2

は、ボトムアップの代わりに、トップダウンから作業してください。すなわち、 'for x = lastRow to 1 step -1' –

+1

forループ終了は、初期化時にセットされ、変更することはできません。ステップ-1を使用してボトムアップからDoループまたはループを使用する必要があります。 –

+0

@ScottCraner doループが機能することを私に見せてもらえますか?ありがとう。 –

答えて

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 
関連する問題