Macro to pull multiple files from a directory


Here's the situation.

I have a directory file that has multiple spreadsheets. Each spreadsheet has 3 worksheets within it.
On the second worksheet title "SST" there is data from columns A-I, and a varying amount of rows.

I need a macro that will extract the data from the SST worksheets of all excel files within the directory, and then populate that into a single worksheet.

Who is Participating?
SiddharthRoutConnect With a Mentor Commented:

Try this. Paste this in a module in the TARGET Excel file where the data has to be imported. This code assumes the following.

1) The file from which the data needs to be extracted is in C:\Temp\
2) The TARGET Excel file is NOT in the folder C:\Temp\
3) The sheet name where you want to import data is called SHEET1 in the TARGET Excel file
4) All sheets are called SST in the files from where the data needs to be extracted.
5) The Column From where the data needs to be extracted is Col A
6) The Destination Col is again Col A in SHEET1

Please amend the above assumptions in the code below before running it :)

Sub Sample()
    Dim wb As Workbook
    Dim ws1 As Worksheet, ws2 As Worksheet
    Dim i As Long, LastRowWs1 As Long, LastRowWs2 As Long
    Dim foundfile As String, pathoffiles As String
    Set ws1 = ActiveWorkbook.Sheets("Sheet1")
    '~~> Change path of the directory here
    pathoffiles = "C:\Temp\"
    foundfile = Dir(pathoffiles & "*.xls") '<~~~  .xlsx of 2007/2010
    Do While Len(foundfile) <> 0
        LastRowWs1 = ws1.Range("A" & Rows.Count).End(xlUp).Row
        Set wb = Workbooks.Open(pathoffiles & foundfile)
        Set ws2 = wb.Sheets("SST")
        LastRowWs2 = ws2.Range("A" & Rows.Count).End(xlUp).Row
        ws2.Range("A1:A" & LastRowWs2).Copy ws1.Range("A" & LastRowWs1)
        wb.Close savechanges:=False
        foundfile = Dir

    Set ws2 = Nothing
    Set wb = Nothing
End Sub

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.