使用相同的工作表名称将数据从工作簿的特定工作表复制到另一个工作表

时间:2017-07-31 08:30:21

标签: excel vba excel-vba

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

paste image

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

1 个答案:

答案 0 :(得分:1)

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

另外,正如@ YowE3K在上面的评论中已经提到的那样,在定义复制的Range时会出现语法错误。

While (file <> "")之后的Set wb = Workbooks.Open(myPath & 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
相关问题