Link to home
Start Free TrialLog in
Avatar of KnutsonBM
KnutsonBMFlag for United States of America

asked on

Macro to pull multiple files from a directory

Question:
Hello

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.

attached is some code that doesn't work, but is what I'm working with.

thanks
Brandon


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
    Loop

    Set ws2 = Nothing
    Set wb = Nothing
End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Dave
Dave
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Brandon the code that I gave you above was for another question :)

You will have to slightly amend it for this question.

1) Could you confirm the path where the files are kept.
2) Which office version are you using?
3) Is the data in Col A or in other columns as well?

Dave: I see that you have already replied and I am not ignoring your post :)

Sid
Avatar of KnutsonBM

ASKER

awsome. amazing. fabulous.
KnutsonBM: I will pretend that you missed my post in error :D

Sid
Thanks KnutsonBM :)


>KnutsonBM: I will pretend that you missed my post in error :D
Sid, but you hadn't actually proferred a solution - you'd asked for more information

Cheers

Dave
>>>Sid, but you hadn't actually proferred a solution - you'd asked for more information

Absolutely! which was missed by the author by mistake ;)

Sid