[excel] Copy from one workbook and paste into another

I have written the following code and continually see pastespecial method of class has failed. I have tried to overcome this issue, but nothing seems to work. I am trying to copy an entire sheet from one workbook, and paste it into another:

Set x = Workbooks.Open(" path to copying book ")
Workbooks.Open(" path to copying book ").Activate
Range("A1").Select
'Cells.Select
Selection.Copy
Set y = Workbooks.Open("path to pasting book")
Workbooks.Open("Path to pasting book").Activate

With y
    Sheets("sheetname").Cells.Select
    Range("A1").PasteSpecial
    'Sheets("sheetname").PasteSpecial
    .Close
End With

With x
    .Close
End With

This question is related to excel vba

The answer is


You copied using Cells.
If so, no need to PasteSpecial since you are copying data at exactly the same format.
Here's your code with some fixes.

Dim x As Workbook, y As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet

Set x = Workbooks.Open("path to copying book")
Set y = Workbooks.Open("path to pasting book")

Set ws1 = x.Sheets("Sheet you want to copy from")
Set ws2 = y.Sheets("Sheet you want to copy to")

ws1.Cells.Copy ws2.cells
y.Close True
x.Close False

If however you really want to paste special, use a dynamic Range("Address") to copy from.
Like this:

ws1.Range("Address").Copy: ws2.Range("A1").PasteSpecial xlPasteValues
y.Close True
x.Close False

Take note of the : colon after the .Copy which is a Statement Separating character.
Using Object.PasteSpecial requires to be executed in a new line.
Hope this gets you going.