2017-05-20 46 views

回答

1

把它放在ThisWorkbook中,修改路徑和文件名,它應該做,你想要什麼。它將採用第一個文件的所有數據集。要修改數據範圍,您可以將var「FirstDataSet」鏈接到單元格,它將從那裏開始或保存它複製的最後一行。這個問題在本網站上被問及幾百次回答。

Public Sub Data() 
Dim wbk As Workbook 
Dim Filename As String 
Dim Path As String 
Dim sht, msht As Worksheet 
Dim lRowFile, lRowMaster As Long 
Dim FirstDataSet As Integer 

On Error Resume Next 

Path = "C:\Users\User\Desktop\Files\" 
Filename = "1.xlsx" 

    Set wbk = Workbooks.Open(Path & Filename) 

    Set sht = Workbooks(Filename).Worksheets(1) 'First Sheet in File 
    Set msht = ThisWorkbook.Worksheets(1) 'First Sheet in Master 

    lRF = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row 'Last Row in File 
    lRM = msht.Cells(Rows.Count, 2).End(xlUp).Row 'Last Row in Master 
    FirstDataSet = 2 'First Data Set in File 

    For i = FirstDataSet To lRF 
     lRM = msht.Cells(Rows.Count, 2).End(xlUp).Row 'Last Row in Master 
     msht.Range("B" & lRM + 1).Value = sht.Range("A" & i).Value 'ID 
     msht.Range("C" & lRM + 1).Value = sht.Range("B" & i).Value 'Name 
     msht.Range("E" & lRM + 1).Value = sht.Range("C" & i).Value 'Store 
     msht.Range("F" & lRM + 1).Value = sht.Range("D" & i).Value 'Product Code 
     msht.Range("I" & lRM + 1).Value = sht.Range("F" & i).Value 'Brand 
     msht.Range("J" & lRM + 1).Value = sht.Range("G" & i).Value 'Form 
     msht.Range("K" & lRM + 1).Value = sht.Range("H" & i).Value 'Days 
     msht.Range("L" & lRM + 1).Value = sht.Range("I" & i).Value 'Category 
     'msht.Range("M" & lRM + 1).Value = sht.Range("K" & i).Value 'Sales 
    Next i 
    'This 
    sht.Range("K2:AV" & lrF).Copy _ 
    Destination:= msht.Range("K2") 
    wbk.Close True 
End Sub 
+0

@ UGP ..謝謝你的幫助! – jhovyn

+0

我已經嘗試過上面的代碼。我遇到的問題是:1.在我的數據源文件中,它只複製了A5:K5行2.數據粘貼在我的「主文件」中的B2上。:(: – jhovyn

+0

因此它應該將所有數據集粘貼到主文件現在我沒有看到B2的錯誤,在你的例子中它是一樣的,你可以通過編輯for循環中的行來調整數據的放置位置,對列的名稱有一個註釋 – UGP

相關問題