简体   繁体   中英

1004 Error when copying range from one sheet to another Sheet

I am able to copy a range from CopyFrom.xlsx into CopyTo.xlsx using belwo code :

Workbooks("CopyTo.xlsx").Worksheets("Sheet1").Range("B3:B14").Clear
Workbooks("CopyFrom.xlsx").Worksheets("Sheet1").Range("A1:A10").Copy
Workbooks("CopyTo.xlsx").Worksheets("Sheet1").Range("B3:B14").PasteSpecial Paste:=xlPasteValues

However when I place the Clear statement in second place, it gives 1004 error

Workbooks("CopyFrom.xlsx").Worksheets("Sheet1").Range("A1:A10").Copy
Workbooks("CopyTo.xlsx").Worksheets("Sheet1").Range("B3:B14").Clear
Workbooks("CopyTo.xlsx").Worksheets("Sheet1").Range("B3:B14").PasteSpecial Paste:=xlPasteValues

Why does this happen?

Because the .Clear exits the cut/copy mode and sets Application.CutCopyMode = False . If you try to .Paste then there is nothing selected to copy after a .Clear which results in the error you got.

Just avoid any code between .Copy and .Paste to aviod any iterference.

If you do it manually, when copying a range and then clearing another range, the copy will get lost.

So Either you clear after or before the copy and paste. Another way could be Range.Value = Range.Value it's a one step process so won't matter what you do.

First Clear the Range:

Workbooks("CopyTo.xlsx").Worksheets("Sheet1").Range("B3:B14").Clear

Then Copy >> Paste

Workbooks("CopyFrom.xlsx").Worksheets("Sheet1").Range("A1:A10").Copy
Workbooks("CopyTo.xlsx").Worksheets("Sheet1").Range("B3:B14").PasteSpecial Paste:=xlPasteValues

Or, you can directly use:

Workbooks("CopyTo.xlsx").Worksheets("Sheet1").Range("B3:B14").Value = Workbooks("CopyFrom.xlsx").Worksheets("Sheet1").Range("A1:A10"). Value

Which is faster in code run-time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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