'假设运行代码之前Wb1就已经手动打开
Sub test()
Dim copySht As Worksheet, afterSht As Worksheet
Set copySht = Workbooks("Wb1.xls").Sheets("sheet1")
Set afterSht = ThisWorkbook..Sheets("sheet2")
copySht.Copy after:=afterSht
End Sub
'假设运行代码之前Wb1没打开,需要用代码代开
Sub test2()
dim wb as Workbook
Dim copySht As Worksheet, afterSht As Worksheet
Set wb = Workbooks.Open("D:\wb1.xls")
Set copySht = wb.Sheets("sheet1")
Set afterSht = ThisWorkbook.Sheets("sheet2")
copySht.Copy after:=afterSht
End Sub
追问Run-time error '1004'
Method 'Copy' of object '_Worksheet' failed
你知道是啥问题吗
追答这个是说工作表的复制方法失败,需要看具体的情况。这段代码我本机上运行没问题,最好截个图看看
追问![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/8cb1cb1349540923d1c2c6c39758d109b2de49e7?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)
追答因为你这段代码是直接在放在excel程序中的,所以你没必要创建新的excel程序对象,你前面那么多代码都是多余的,而且另外创建了个excel程序的话不知道是否是引起这个问题的原因(没有测试)。你完全可以修改为:
Sub InputERP_Click()
Dim wb As Workbook, ERP_Path
Dim copySht As Worksheet, afterSht As Worksheet
ERP_Path = Application.GetOpenFilename(fileFilter:="Excel 97-2003 工作簿(*.xls),*.xls")
If ERP_Path = False Then Exit Sub
Set wb = Workbooks.Open(ERP_Path)
Set copySht = wb.Sheets("sheet1")
Set afterSht = ThisWorkbook.Sheets("sheet2")
copySht.Copy after:=afterSht
End Sub
这段代码亲测没问题。