匹配时添加并复制行
我正在玩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
问题是如何添加一个新行(见上面的代码),并复制上面的行的全部内容到它。
试着总是在顶部使用Option Explicit
,并声明所有的variables。
码
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