excel 复制和粘贴时VBA运行时错误1004

wgeznvg7  于 2023-03-04  发布在  其他
关注(0)|答案(1)|浏览(246)

我正在从一个工作簿/工作表复制和粘贴到另一个工作簿/工作表,虽然它实际上确实复制和粘贴,但我得到了一个运行时错误1004范围类的Pastespecial方法失败。
我还在学习中,非常新,所以我相信有一个更好的方法来编写代码,但下面的代码确实执行任务,我仍然得到错误。我该怎么做才能修复它?

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
uurity8g

uurity8g1#

这应该行得通:

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

相关问题