匹配时添加和复制行

时间:2017-07-04 12:45:01

标签: excel vba excel-vba

我正在Excel 2016中使用Macros。我想要的是在包含文本“name”的行下添加一行,如果是这样的话,请复制它下面的行内容。到目前为止我尝试了什么:

Sub InsertNewRow()
    Dim c As Range
    Set Rng = ActiveSheet.Range("A1:H654")
    For dblCounter = Rng.Cells.Count To 1 Step -1
        Set c = Rng(dblCounter)
        If c.Value Like "*Name*" Then
            c.EntireRow.Insert

    End If
    Next dblCounter
End Sub

excel2016 macro

问题是如何添加新行(参见上面的代码)并将上面行的全部内容复制到其中。

1 个答案:

答案 0 :(得分:2)

尝试始终使用顶部的Option Explicit,并声明所有变量。

<强> 代码

Option Explicit

Sub InsertNewRow()

    Dim c As Range, Rng As Range
    Dim dblCounter As Long

    Set Rng = ActiveSheet.Range("A1:H654")
    For dblCounter = Rng.Cells.Count To 1 Step -1
        Set c = Rng(dblCounter)
        If c.Value Like "*Name*" Then
            c.Offset(1).EntireRow.Insert ' insert a row below
            c.EntireRow.Copy Destination:=Range("A" & c.Row + 1) ' copy the contents from the row above
        End If
    Next dblCounter

End Sub