将活动 sheet 复制到另一个工作簿:范围 class 的复制方法失败

copying active sheet into another workbook: Copy Method of Range class failed

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

我收到此错误:

Run=-time error '1004': Copy Method of Range class failed

这一行:

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

几个建议,这应该有效(至少在我的电脑上有效,我能够完美地复制你的错误):

修复 1

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

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

并写下:

Set oBook = Workbooks.Open(path1)

固定 2

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

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 您可能在每次失败时离开的进程 运行 您的代码,然后再执行笔记本电脑爆炸 :)