【问题标题】:copying active sheet into another workbook: Copy Method of Range class failed将活动工作表复制到另一个工作簿:范围类的复制方法失败
【发布时间】:2019-07-08 21:46:41
【问题描述】:

我希望我的代码复制整个工作表(SOURCE)并将其粘贴到其他工作簿(WHERE_I_WANNA_PASTE_IT)下的其他工作表(TARGET)中并保存。

我收到此错误:

Run=-time error '1004': Range 类的复制方法失败

在这一行:

CurrentSheet.Cells.Copy Destination:=oSheet.cells 

代码:

Public Const path1 As String = "C:\Where_I_WANNA_PASTE_IT.xlsb"
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
Dim CurrentSheet As Object

Sub copyNpaste

Set CurrentSheet = ActiveSheet
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Open(path1)
Set oSheet = oBook.Worksheets("TARGET")

'Deleting what's on "TARGET" first
oSheet.cells.delete

'This is where the Error happens.
CurrentSheet.Cells.Copy _
Destination:=oSheet.Cells

oBook.Save
oBook.Close

Set oExcel = Nothing
Set oBook = Nothing
Set oSheet = Nothing
Set CurrentSheet = Nothing

End Sub

【问题讨论】:

  • 我无法重现您的错误。您使用后期绑定是否有原因?
  • 试试这个,看看它是否有效。 CurrentSheet.Cells.CopySpecial

标签: vba excel copy-paste worksheet


【解决方案1】:

一些建议,这应该可以工作(至少在我的电脑上可以,我能够完美地复制你的错误):

修复 1

不要创建新的 Excel 应用程序,使用相同的线程;换句话说,删除这个:

Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Open(path1)

并写下:

Set oBook = Workbooks.Open(path1)

修复 2

您可以在需要时设置活动工作表,但要清楚参考,使用“ThisWorkbook”这样编译器会很高兴并且您不会冒险引用其他工作表(这始终是一个好习惯,永远不要如果您已经知道预期的参考是什么,则完全信任默认参考,就像在这种情况下一样):

Set CurrentSheet = ThisWorkbook.ActiveSheet

还有一个建议……

放置一个错误处理程序:如果方法失败,您会发现有一堆开放式 Excel 线程(检查一下,您将拥有与运行代码失败一样多的线程。这是我将如何编写完整的代码(包括建议):

Public Const path1 As String = "C:\yourfile.xlsb"
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
Dim CurrentSheet As Object

Sub copyNpaste()

Set oBook = Workbooks.Open(path1)
Set oSheet = oBook.Worksheets("TARGET")
Set CurrentSheet = ThisWorkbook.ActiveSheet

On Error GoTo ESCAPE 'if the code fails, we go to "Escape" and at least we close the file

'Deleting what's on "TARGET" first
oSheet.Cells.Delete

'This is where the Error happens.
CurrentSheet.Cells.Copy _
Destination:=oSheet.Cells

oBook.Save

ESCAPE:

oBook.Close

Set oExcel = Nothing
Set oBook = Nothing
Set oSheet = Nothing
Set CurrentSheet = Nothing

End Sub

注意

打开您的任务管理器 (Ctrl+Alt+Del) 并转到进程...在您的笔记本电脑爆炸之前,每次运行代码失败时关闭您可能留下的所有 EXCEL.EXE 进程:)

【讨论】:

    猜你喜欢
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多