Search code examples
excelvbaruntime-error

VBA runtime error 1004 when copy and pasting


I am copying and pasting from one workbook/sheet to another workbook/sheet and although it actually does copy and paste, I am getting a runtime error 1004 Pastespecial method of range class failed.

I am still learning and very new so I am sure there is a better way to write the code but the code below does perform the task and I still get the error. What could I do to fix it?

Sub CopyWorksheet()

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


    '## Open both workbooks first:
    Set x = Workbooks.Open("C:\Users\KimBush\Documents\NP Credentials Project\Greater than 30 days    project\Macro Testing\NPPIndependentStatusReport")
    Set y = Workbooks.Open("C:\Users\KimBush\Documents\NP Credentials Project\Greater than 30 days project\Macro Testing\DKC-IKC NP Credentialing Update Testing")


    'Now, copy what you want from x:
    x.Sheets("Sheet1").Range("A1:P10781").Copy

    Set ws1 = x.Sheets("Sheet1")
    Set ws2 = y.Sheets("Source")

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

    'Now, paste to y worksheet:
    y.Sheets("Source").Range("A1").PasteSpecial

    'Close x:
    'x.Close

End Sub

Solution

  • This should work:

    Sub CopyWorksheet()
    
        Dim x As Workbook
        Dim y As Workbook
        Dim ws1 As Worksheet
        Dim ws2 As Worksheet
    
        '## Open both workbooks first:
        Set x = Workbooks.Open("C:\Users\KimBush\Documents\NP Credentials Project\Greater than 30 days    project\Macro Testing\NPPIndependentStatusReport")
        Set y = Workbooks.Open("C:\Users\KimBush\Documents\NP Credentials Project\Greater than 30 days project\Macro Testing\DKC-IKC NP Credentialing Update Testing")
    
        Set ws1 = x.Sheets("Sheet1")
        Set ws2 = y.Sheets("Source")
    
        ws1.Cells.copy Destination:=ws2.Range("A1")
    
        '...
    
    End Sub