如何插入一个空白行上面而不是下面特定的重复行

我使用下面的macros,它插入单元格下方的“卡号”

无论我做什么,我都无法把它放在行的上面。 对于一些人来说可能是相当基本的,但最近才发现macros是多么有用

Sub Insert() Dim c As Range For Each c In Range("A1:A5000") If c.Value Like "*Card Number:*" Then c.Offset(1, 0).EntireRow.Insert End If Next c End Sub 

正如你可能试过的,你不能只是做c.EntireRow.Insert因为它会在上面插入一行,它将永远保持在For Each循环中。 解决的办法是通过反向循环范围,就像在这个答案中做的那样:

 Sub InsertRev() Dim c As Range Set rng = ActiveSheet.Range("A1:A5000") For dblCounter = rng.Cells.Count To 1 Step -1 Set c = rng(dblCounter) If c.Value Like "*Card Number:*" Then c.EntireRow.Insert End If Next dblCounter End Sub 

在这种情况下不要使用“ Offset ,“ Insert命令总是在select上方插入行。

此外,如果你使用for each ,你不能控制你的循环的方向,所以最好使用for i = step -1从下到上。

为什么? 因为如果你从第i行插入一个新行,那么我将成为第i + 1行,你将在下一个循环中testing它,并继续添加行!

 Sub Insert_Rows() Dim i As Long For i = 5000 To 1 Step -1 If Cells(i, "A").Value Like "*Card Number:*" Then Cells(i, "A").EntireRow.Insert End If Next i End Sub 

这是我将如何解决这个问题,但我并不是先进的macros,我相信有一个更好的方法。

 Sub Insert() For i = 1 To 5000 If Cells(i, "A") Like "*Card Number:*" Then ' loop trough 5000 cells in column A Rows(i + 1).Insert 'insert bottom row first so it doesn't mess with row numbers Rows(i - 1).Insert 'then you can insert upper row i = i + 1 'jump over the next row as it now contains the card number for sure End If Next i End Sub