简体   繁体   English

复制粘贴VBA问题

[英]Copy Paste VBA Issue

I am trying to write a macro that takes parts of one sheet and paste values on the next. 我正在尝试编写一个宏,该宏将一张纸的一部分粘贴到下一张纸上。 I know using select isn't ideal. 我知道使用select并不理想。 But i Don't know how to do it other wise. 但是我不知道怎么做。 In the past i have got a out of range error if i was not selecting the sheet before hand. 在过去,如果我没有事先选择表格,则会遇到超出范围的错误。 In the macro i have y defined earlier but I am getting an 在宏中,我早先定义了,但是我得到了

1004 application-defined or object-defined error 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

The issue is that Range() expects two arguments - Cell1 and Cell2 - you're only giving it one argument, which is throwing error 1004. 问题是, Range()需要两个参数- Cell1Cell2 -你只给它一个说法,这是抛出错误1004。

Instead, just use .Cells() : 相反,只需使用.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

Better yet, let's avoid Select , Copy and Paste altogether: 更好的是,让我们完全避免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

As another note - it's better to use xlUp than xlDown when determining your lastrow for data entry. 另一个要注意的是-确定数据输入的xlDown时,最好使用xlUpxlDown

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM