简体   繁体   中英

VBa Copy error “We cant paste because the copy and paste area are not the same size”

Please help me debug this code. I am compiling a report from 100 files. This code works for almost all the files but for some this error pops up. The format for all the files is the same only the row count differs

sh.Range("A2:H" & lastRow).Copy 
Destination:=wb1.Worksheets("MainSheet").Range("A" & mainrow)

A2&last row = A2:H17408
"A" & mainrow=A1033559

There are multiple reasons to get this error message 1. When you are pasting merged cells to non-merged cells or visa-versa. 2. When you applied a filter to sheet, and tried to paste which is not same size as copied data.

your code is too limited to be sure of a 100% correct answer, as we do not see how you have defined your variables. However, assuming they are correctly defined, it is better to use this:

Dim ws as worksheet
Set ws = wb1.Sheets("MainSheet")

' Range goes from columns A to H with mainrow and LastRow as variable rows
ws.Range(ws.Cells(mainrow, 1), ws.Cells(LastRow, 8)).Value = sh.Range(sh.Cells(mainrow, 1), sh.Cells(LastRow, 8)).Value

instead of a copy-paste. Apart from that, make sure mainrow and LastRow are defined correctly. When in doubt, add this part of your code in an edited question, so we can have a look at it.

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