复制粘贴VBA问题

时间:2018-07-05 18:28:50

标签: vba excel-vba excel

我正在尝试编写一个宏,该宏占用一张纸的一部分,然后在另一张纸上粘贴值。我知道使用select并不理想。但是我不知道怎么做。在过去,如果我没有事先选择表格,则会遇到超出范围的错误。在宏中,我之前定义了y,但是我得到了一个

  

1004应用程序定义或对象定义的错误

y = Sheets("sheet1").Range("B1", Range("B2").End(xlDown)).Count
Sheets("Bucket12").Select
Sheets("Bucket12").Range("C2", Range("C2").End(xlDown)).Copy
Sheets("upload").Range(Cells(y, 2)).PasteSpecial xlPasteValues
Sheets("Bucket12").Range("E2", Range("E2").End(xlDown)).Copy
Sheets("upload").Range(Cells(y, 3)).PasteSpecial xlPasteValues
Sheets("Bucket12").Range("G2", Range("G2").End(xlDown)).Copy
Sheets("upload").Range(Cells(y, 5)).PasteSpecial xlPasteValues
Application.CutCopyMode = False

1 个答案:

答案 0 :(得分:3)

问题是Range()需要两个参数-Cell1Cell2-您只给它一个参数,这会引发错误1004。

相反,只需使用.Cells()

y = Sheets("sheet1").Range("B1", Range("B2").End(xlDown)).Count
Sheets("Bucket12").Select
Sheets("Bucket12").Range("C2", Range("C2").End(xlDown)).Copy
Sheets("upload").Cells(y, 2).PasteSpecial xlPasteValues
Sheets("Bucket12").Range("E2", Range("E2").End(xlDown)).Copy
Sheets("upload").Cells(y, 3).PasteSpecial xlPasteValues
Sheets("Bucket12").Range("G2", Range("G2").End(xlDown)).Copy
Sheets("upload").Cells(y, 5).PasteSpecial xlPasteValues
Application.CutCopyMode = False

更好的是,让我们完全避免使用SelectCopyPaste

y = Sheets("Sheet1").Cells(Sheets("Sheet1").Rows.Count, 2).End(xlUp).Row

Dim sht1 As Worksheet, sht2 As Worksheet, lastrow As Long

Set sht1 = ThisWorkbook.Worksheets("Bucket12")
Set sht2 = ThisWorkbook.Worksheets("upload")

lastrow = sht1.Cells(sht1.Rows.Count, 3).End(xlUp).Row
sht2.Range(sht2.Cells(y, 2), sht2.Cells(lastrow + y - 2, 2)).Value = _
sht1.Range(sht1.Cells(2, 3), sht1.Cells(lastrow, 3)).Value

lastrow = sht1.Cells(sht1.Rows.Count, 5).End(xlUp).Row
sht2.Range(sht2.Cells(y, 3), sht2.Cells(lastrow + y - 2, 3)).Value = _
sht1.Range(sht1.Cells(2, 5), sht1.Cells(lastrow, 5)).Value

lastrow = sht1.Cells(sht1.Rows.Count, 7).End(xlUp).Row
sht2.Range(sht2.Cells(y, 5), sht2.Cells(lastrow + y - 2, 5)).Value = _
sht1.Range(sht1.Cells(2, 7), sht1.Cells(lastrow, 7)).Value

请注意-确定数据输入的最后行时,最好使用xlUpxlDown