【问题标题】:VBA in Excel using If, Copy&PasteExcel中的VBA使用If,复制粘贴
【发布时间】:2021-07-29 08:48:28
【问题描述】:

我是 VBA 的初学者。如果满足某个条件,我想自动复制和粘贴。 如果 G 行是“N”,则从 Range(Cells(Row+1,"h"), Cells(Row,"bg")) 复制并粘贴到 Range(Cells(Row+1,"h"), Cells( Row,"bg")) 并在被替换的行 "bh" 中添加“数据已替换”。 到目前为止,我已经编写了一些代码,每当我实现下面的代码时,都会出现“13”运行时错误。我很迷茫,请帮助我!提前谢谢你。

Sub Sbustitute()

    Dim nRows As Long, LastRow As Long, Row As Long, Column As Range, Color As Long
    nRows = 2
    LastRow = Cells(Rows.Count, "b").End(xlUp).Row
      For Row = LastRow To nRows Step -1
        Set Cell = Cells(Row, "g")
        If Cell = "N" Then
            Range(Cells(Row + 1, "h"), Cells(Row + 1, "bg")).Copy Range(Cells(Row, "h"), Cells(Row, "bg"))
            ActiveSheet.Paste
            Cells(Row, "bh") = "Data substituted" 
        End If
    Next
End Sub

【问题讨论】:

  • 在您的代码中,ActiveSheet.Paste 指令显然是不必要的,因为在使用它将数据复制到剪贴板之前,这不会发生,并且它的存在会导致错误 1004 - 方法粘贴类工作表完成不正确。删除后,代码可以正常工作。类型不匹配错误(13)无法重现。
  • RowRange 对象的属性 - 您不应该使用预先声明的名称作为变量名。
  • @Samuel Everson 谢谢你的回答,但我不完全明白。
  • @MYChoi 这是一个implicit ActiveSheet reference;考虑使用明确的 Worksheet 对象来限定这些成员调用,该对象引用您要使用的工作表:theSheet.CellstheSheet.RowstheSheet.Range(...)
  • @Samuel Everson 谢谢!!!

标签: vba if-statement copy


【解决方案1】:

也许以下就是您所追求的。这个版本不是Range.Copy,而是在两个范围之间分配值。

    Sub Substitute()
        Dim nRows As Long, LastRow As Long, currentRow As Long, Column As Range, Color As Long

        nRows = 2
        LastRow = Cells(Rows.Count, "b").End(xlUp).Row
        For currentRow = LastRow To nRows Step -1
            Set Cell = Cells(currentRow , "g")
            If Cell = "N" Then
                Range(Cells(currentRow + 1, "h"), Cells(currentRow + 1, "bg")).Value = Range(Cells(currentRow , "h"), Cells(currentRow , "bg")).Value
                Cells(currentRow, "bh") = "Data substituted"
            End If
        Next
    End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多