【问题标题】:Add and copy row when matching匹配时添加和复制行
【发布时间】:2017-07-04 12:45:01
【问题描述】:

我正在使用 Excel 2016 中的宏。我想要的是在包含文本“名称”的行下添加一行,如果是这种情况,请复制其下的行内容。到目前为止我尝试了什么:

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

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

【问题讨论】:

  • 好的,你的问题是……?

标签: vba excel


【解决方案1】:

尽量在顶部始终使用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   

【讨论】:

  • 谢谢!添加新行有效。复制上一行的内容不会。
  • @CitizenSP “不工作”是什么意思?你有错误吗?是复制错误的行吗?什么都不复制?
  • @CitizenSP 刚刚测试了几次,它适用于我的文件
猜你喜欢
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
  • 2011-01-18
  • 2022-12-19
  • 2016-03-15
  • 2013-04-06
  • 1970-01-01
  • 2012-01-02
相关资源
最近更新 更多