简体   繁体   中英

Excel error 1004: Copy area and paste area aren't the same size

I am trying to copy data from many spreadsheets into one sheet. I am copying from ranges A:L, and when the data is pasted from A:L on the summary sheet, it works with no issues. I am trying to paste my data on columns B:M, which is when I receive the 1004 error. I have a slightly modified code from the MSDN site:

I receive the error when I change the With DestSh.Cells(Last + 1, "A") to With DestSh.Cells(Last + 1, "B")

 ' Loop through all worksheets and copy the data to the
    ' summary worksheet.
    For Each sh In ActiveWorkbook.Worksheets
        If sh.Name <> DestSh.Name And sh.Name <> "Pivot Table" And sh.Name <> "Combined" Then

            ' Find the last row with data on the summary
            ' and source worksheets.
            Last = LastRow(DestSh)
            shLast = FindLastRow(sh)

            ' If source worksheet is not empty and if the last
            ' row >= StartRow, copy the range.
            If shLast > 0 And shLast >= StartRow Then
                'Set the range that you want to copy
                Set CopyRng = sh.Range(sh.Rows(StartRow), sh.Rows(shLast))
                StartRow = 2

               ' Test to see whether there are enough rows in the summary
               ' worksheet to copy all the data.
                If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
                   MsgBox "There are not enough rows in the " & _
                   "summary worksheet to place the data."
                   GoTo ExitTheSub
                End If

                ' This statement copies values and formats.
                CopyRng.Copy
                With DestSh.Cells(Last + 1, "A")
                    .PasteSpecial xlPasteValues
                    Application.CutCopyMode = False
                End With

            End If

        End If
    Next

From Domenic:

Try setting your copy range as:

Set CopyRng = Intersect(sh.UsedRange, sh.Range(sh.Rows(StartRow), sh.Rows(shLast)))

Solution:

        If shLast > 0 And shLast >= StartRow Then
            'Set the range that you want to copy
            'Set CopyRng = sh.Range(sh.Rows(StartRow), sh.Rows(shLast))
            'StartRow = 2

            Set CopyRng = Intersect(sh.UsedRange, sh.Range(sh.Rows(StartRow), sh.Rows(shLast)))

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