我希望我的代码能够复制整个工作表(SOURCE)并将其粘贴到其他工作簿(WHERE_I_WANNA_PASTE_IT)下的其他工作表(TARGET)中并保存。
我收到此错误:
运行= -time错误'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
答案 0 :(得分:6)
一些建议,这应该有用(至少它在我的电脑上,我能够完美地复制你的错误):
FIX 1
不要创建新的Excel应用程序,使用相同的线程;换句话说,删除它:
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Open(path1)
并写下:
Set oBook = Workbooks.Open(path1)
FIX 2
您可以根据需要设置活动工作表,但要明确参考,请使用" ThisWorkbook"所以编译器会很高兴,你没有风险参考另一张表(这总是一个很好的做法,如果你已经知道你的预期参考是什么,永远不会完全信任默认参考,就像在这种情况下): / p>
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进程,在你的笔记本电脑爆炸之前:)