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

时间:2015-11-26 09:58:07

标签: excel vba excel-vba

我使用下面的宏,然后用"卡号"插入单元格下方的行。

无论我做什么,我都无法超越行。对某些人来说可能相当基本,但最近才发现有用的宏

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

3 个答案:

答案 0 :(得分:0)

这就是我解决这个问题的方法,但我不是那些先进的宏,我相信还有更好的方法。

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

答案 1 :(得分:0)

在这种情况下不要使用OffsetInsert命令总是在选择上方插入行。

此外,如果您使用for each,则无法控制循环的方向,因此最好将for i =step -1一起使用从下到上。

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

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

答案 2 :(得分:0)

正如您可能尝试过的那样,您不能只执行c.EntireRow.Insert,因为它会在上面插入一行,并且会无限地保留在For Each循环中。解决方案是反向循环遍历范围,就像在this answer中完成的那样:

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
相关问题