不确定原因,但我的复制和粘贴语句给我一个运行时1004错误("应用程序定义或对象定义错误")
这是有问题的一行:
cs.Range(cs.Cells(2, 1), cs.Cells(lastRow - 1, lastColumn)).Copy _
Destination:=pasteSheet.Range(pasteSheet.Cells(pasteRow + 1, 1))
这是我完整的子程序。我传递文件路径以及当前工作表 - pasteSheet
Sub copyAndPaste(filePath As String, pasteSheet As Worksheet)
Debug.Print "filePath = "; filePath
Dim cb As Workbook
Set cb = Workbooks.Open(filePath, 0, True)
Dim cs As Worksheet
Set cs = cb.Sheets(1)
Dim lastRow As Long
lastRow = cb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
Debug.Print "LastRow = "; lastRow
Dim lastColumn As Long
lastColumn = cb.Sheets(1).Cells(1, Columns.Count).End(xlToLeft).Column
Debug.Print "LastCol = "; lastColumn
Dim pasteRow As Long
pasteRow = pasteSheet.Cells(Rows.Count, 1).End(xlUp).Row
Debug.Print "PasteRow = "; pasteRow
cs.Range(cs.Cells(2, 1), cs.Cells(lastRow - 1, lastColumn)).Copy _
Destination:=pasteSheet.Range(pasteSheet.Cells(pasteRow + 1, 1))
cb.Close False
End Sub
答案 0 :(得分:0)
如果pasteSheet
位于工作簿cb
中,则您已将cb
打开为只读,因此粘贴会失败?否则将pasteSheet
与其工作簿父级一起限定。
根据OP讨论编辑演示
为了说明,我在代码中明确指定了Sub的参数。请注意,这些是我的测试值,您需要确保以此形式提供。请注意,(1)pasteSheet
这里是完全限定的,(2)我已经调整了复制/粘贴行中的(粘贴)语法。
Sub copyAndPaste()
Dim filepath As String
Dim pasteSheet As Worksheet
Set pasteSheet = ThisWorkbook.Sheets("Sheet2") 'provide your values
filepath = "C:\Data\\SOtestdata.xlsx" 'provide your values
Dim cb As Workbook
Set cb = Workbooks.Open(filepath, 0, True)
Dim cs As Worksheet
Set cs = cb.Sheets(1)
Dim lastRow As Long
lastRow = cb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
Debug.Print "LastRow = "; lastRow
Dim lastColumn As Long
lastColumn = cb.Sheets(1).Cells(1, Columns.Count).End(xlToLeft).Column
Debug.Print "LastCol = "; lastColumn
Dim pasteRow As Long
pasteRow = pasteSheet.Cells(Rows.Count, 1).End(xlUp).Row
Debug.Print "PasteRow = "; pasteRow
cs.Range(cs.Cells(2, 1), cs.Cells(lastRow - 1, lastColumn)).Copy _
Destination:=pasteSheet.Range(pasteSheet.Cells(pasteRow + 1, 1), pasteSheet.Cells(pasteRow + 1, 1))
cb.Close False
End Sub