Looping through directory

DHogg

New Member
Joined
Jan 15, 2013
Messages
28
I have about 20 sheets in a folder on my hard drive, each containing one sheet tab.

I want to write a macro which loops through the directory these are saved in, and copys all of these so 1 workbook with 20 tabs. Is this possible with VBA?
 

Excel Facts

Get help while writing formula
Click the italics "fx" icon to the left of the formula bar to open the Functions Arguments dialog. Help is displayed for each argument.
This is a pretty simple task.

I put something together quickly. I think it will do what you want or be pretty close.

Code:
Sub mergeBooks()
Dim newBook As String
Dim thePath As String
Dim theFile As String
Dim theBook As String


Workbooks.Add
newBook = ActiveWorkbook.Name


thePath = InputBox("Enter source path", "Source Folder", ActiveWorkbook.Path)
If thePath <> "" Then
    ' Set the file specification to match the names of the files to merge
    theFile = Dir(thePath & "\*.xls*")
    While theFile <> ""
        Workbooks.Open thePath & "\" & theFile
        theBook = ActiveWorkbook.Name
        ActiveSheet.Copy after:=Workbooks(newBook).Sheets(Workbooks(newBook).Sheets.Count)
        Workbooks(theBook).Close False
        
        theFile = Dir
    Wend
End If
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,911
Messages
6,122,199
Members
449,072
Latest member
DW Draft

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top