【问题标题】:How to insert a single blank row ABOVE and not below specific repeated row [duplicate]如何在特定重复行上方而不是下方插入单个空白行[重复]
【发布时间】:2015-11-26 09:58:06
【问题描述】:

我使用下面的宏,它在单元格下方插入带有“卡号”的行

无论我做什么,我都无法让它超过行。对某些人来说可能很基础,但最近才发现宏有多大用处

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
  • 谢谢,试过了 - 但是当我运行它并关闭 excel 时它进入了尾旋

标签: vba excel


【解决方案1】:

正如您可能尝试过的那样,您不能只做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

【讨论】:

  • AGold 的加分项 - 你的天才!非常感谢
【解决方案2】:

在这种情况下不要使用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

【讨论】:

    【解决方案3】:

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

    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
    

    【讨论】:

    • 使用Step -1从下到上会更容易,避免添加多行! ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 2018-08-10
    • 1970-01-01
    相关资源
    最近更新 更多