2017-07-31 40 views
0

我似乎無法讓我的代碼正常工作。我有7個生產力文件,我需要從標題爲worktracker的表中複製數據,並將這些文件粘貼到masterfile中的工作跟蹤表中。我遇到運行時錯誤1004 方法object_Worksheet的範圍失敗。有人可以建議嗎?非常感謝!將數據從工作簿的特定工作表複製到另一個具有相同工作表名稱的數據

paste image

私人小組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 
+0

能否請您粘貼您的實際代碼到的問題 - '範圍(小區(2,1)(LASTROW,lastcolumn)) .Copy'是無效的語法,因此代碼不會運行。所以你不會得到該代碼的1004錯誤。並告訴我們(實際)代碼的哪一行會給出錯誤。 – YowE3K

+0

謝謝YowE3K ...我用{}粘貼了代碼...對不起,我仍然在這個 – agatha

+0

這條線說'Range(Cell(2,1)(lastrow,lastcolumn))。Copy'仍然存在 - 是那真的是你的真實代碼? – YowE3K

回答

1

您需要完全限定所有對象,一個舒適而簡便的方法,是用嵌套With語句來單獨每個Workbook

另外,由於@ 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 
+0

嗨Shai Rado ...我複製你的代碼,並根據你的建議將它放到代碼中......但它似乎只是複製頭部而不是從單元格A4的條目:W4以上?對不起還是真的新編碼vba – agatha

+0

@agatha檢查你的lastRow變量值 –

+0

謝謝!我對如何更新代碼實際上感到不知所措......我剛剛從在線教程中複製了代碼 – agatha

相關問題