将工作簿的特定工作表中的数据复制到具有相同工作表名称的另一个工作表中

我似乎无法让我的代码工作。 我有7个生产力文件,我需要复制标题为worktracker的表中的数据,并将其粘贴到masterfile中的工作跟踪表中。 我得到运行时错误1004方法object_Worksheet的范围失败。 有人可以build议吗? 非常感谢!

粘贴图像

Private Sub CommandButton1_Click()

Dim file As String Dim myPath As String Dim wb As Workbook Dim rng As Range Dim lastrow As Long, lastcolumn As Long Dim wbMaster As Workbook Set wbMaster = Workbooks("WorkTracker_Master.xlsm") Set rng = wbMaster.Sheets("WorkTracker").Range("A4:W4") myPath = "\\BMGSMP1012\GBDMC_Team$\GBDM_ContentManagement\+CM_Reports\Productivity Reports\FY18\" file = Dir(myPath & "*.xls*") While (file <> "") Set wb = Workbooks.Open(myPath & file) lastrow = wb.Worksheets("WorkTracker").Cells(Rows.Count, 1).End(xlUp).Row lastcolumn = wb.Worksheets("WorkTracker").Cells(1, Columns.Count).End(xlToLeft).Column Range(Cell(2, 1)(lastrow, lastcolumn)).Copy Application.DisplayAlerts = False ActiveWorkbook.Close erow = WorkTracker.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row ActiveSheet.Paste Destination = Worksheets("WorkTracker").Range(Cells(erow, 1), Cells(erow, 4)) wb.Close SaveChanges:=True Set wb = Nothing file = Dir Wend Application.CutCopyMode = False End Sub 

您需要完全限定所有对象,这是一种舒适而简单的方法,即使用嵌套的With语句来分隔每个Workbook

另外,由于@ YowE3K在上面的注释中已经提到过,所以在定义复制的Range时会出现语法错误。

Set wb = Workbooks.Open(myPath & file)后,尝试下面的代码,在While (file <> "")循环中:

 With wb.Worksheets("WorkTracker") lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row lastcolumn = .Cells(1, .Columns.Count).End(xlToLeft).Column .Range(.Cells(2, 1), .Cells(lastrow, lastcolumn)).Copy End With With wbMaster.Worksheets("WorkTracker") ' get first empty row in column "A" erow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row ' paste in the first empty row .Range("A" & erow).PasteSpecial End With wb.Close SaveChanges:=True Set wb = Nothing