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

时间:2015-06-02 18:33:31

标签: excel vba excel-vba

代码的目标是将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 :(得分:0)

当将范围对象作为Range属性的参数传递时,经常捕获人的一个[问题]是,如果需要指定工作表对象(这是一个好习惯),则需要为所有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
相关问题