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

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

我得到这个错误:

运行=时间错误“1004”:范围类的复制方法失败

在这一行上:

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 

几个build议,这应该工作(至less它在我的电脑上,我能够完美地复制你的bug):

修正1

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

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

并写下这个:

 Set oBook = Workbooks.Open(path1) 

修正2

你可以在你想要的时候设置你的活动工作表,但是要用参考清楚地说明,使用“ThisWorkbook”,这样编译器会很高兴,而且你不用担心引用另一个工作表(这总是一个很好的做法,默认引用,如果你已经知道你的期望引用是什么,在这种情况下):

 Set CurrentSheet = ThisWorkbook.ActiveSheet 

和一个SUGGESTION …

把一个error handling程序:如果方法失败,你会发现一堆开放的Excel线程(检查出来,你会有尽可能多的,你已经失败了你的代码运行,这是我如何写完整的代码(build议包括):

 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 

注意

打开你的任务pipe理器(Ctrl + Alt + Del),并进入进程…closures所有的EXCEL.EXE进程,你可能已经离开,每次运行你的代码失败之前,你的笔记本电脑爆炸:)