首页 文章

调试 . 在一张纸上复制可变数量的单元格并粘贴到另一张纸中

提问于
浏览
1

代码的目标是将Sheet2中的n行和3列单元格复制到Sheet1中的最后一个空行 . 我尝试使用范围内的单元格属性进行复制,但这一行给出了运行时错误“1004”(应用程序定义或对象定义的错误) .

怎么能纠正这个?

Private Sub CommandButton1_Click()
    Dim sum As Integer
    n = 7
    Sheets("Sheet2").Range(Cells(11, 15), Cells((11 + n), 18)).Copy
    With Sheets("Sheet1").Range("A500").End(xlUp).Offset(1, 0)
        .PasteSpecial xlPasteFormats
        .PasteSpecial xlPasteValues
    End With
End Sub

1 回答

  • 0

    将范围对象作为Range属性的参数传递时经常捕获人的一个[问题]是,如果需要指定工作表对象(这是一个好习惯),则需要为所有范围/单元格属性指定它使用 .

    (来源/更多阅读:http://excelmatters.com/referring-to-ranges-in-vba/

    你可以使用:

    With Sheets("Sheet2")
        .Range(.Cells(11, 15), .Cells((11 + n), 18)).Copy
    End With
    

    要么:

    Sheets("Sheet2").Range(Sheets("Sheet2").Cells(11, 15), Sheets("Sheet2").Cells((11 + n), 18)).Copy
    

    代替:

    Sheets("Sheet2").Range(Cells(11, 15), Cells((11 + n), 18)).Copy
    

    或者您可以像这样构建范围:

    Sheets("Sheet2").Range("O11:R" & (11 + n)).Copy
    

    编辑代码:

    Private Sub CommandButton1_Click()
    Dim sum As Integer
    n = 7
    Sheets("Sheet2").Range("O11:R" & (11 + n)).Copy 'Edited Line
    With Sheets("Sheet1").Range("A500").End(xlUp).Offset(1, 0)
        .PasteSpecial xlPasteFormats
        .PasteSpecial xlPasteValues
    End With
    End Sub
    

相关问题