Here is a full example of this (uses a different approach - you need to enable the "Microsoft Scripting Runtime" for this module to work).
This macro looks through a directory with (or without) sub-folders included. It will open each file in the folder, copy the contents from the worksheets of that files to a single sheet.
I was using this module to do something else, but edited it to do what i think you meant to do. Attached book contains this module (run dumpDirectoryDriver to try it out).
enjoy
--
Option Explicit
Public error As String
Sub dumpDirectoryDriver()
Dim fPath As String
Dim incSubFlds As Boolean
Dim fType As String
Dim newBook As Workbook
Dim newSheet As Worksheet
On Error GoTo done
error = ""
fPath = InputBox("Enter folder path and press OK.")
fType = ".xls"
incSubFlds = True
Set newBook = Workbooks.Add
Set newSheet = newBook.Sheets(1)
Application.ScreenUpdating = False
Call dumpDirectory(fPath, fType, incSubFlds, newSheet)
Application.ScreenUpdating = True
newSheet.Activate
Exit Sub
done:
MsgBox (error & ". Operation stopped.")
End Sub
Sub dumpDirectory(myPath As String, fileExtension As String, incSub As Boolean, targetSheet As Worksheet)
Dim fso As FileSystemObject
Dim fld As Folder, subfld As Folder
Dim fil As File
Dim wks As Worksheet
Dim wkb As Workbook
Dim nextOpenRow As Long, lengthOfSection As Long, widthOfSection As Long, n As Long
On Error GoTo done
'initialize'
Set fso = New FileSystemObject
Set fld = fso.GetFolder(myPath)
'open files, dump worksheet contents to target sheet'
For Each fil In fld.Files
If UCase(fil.Name) Like "*" & UCase(fileExtension) & "*" Then
Set wkb = Application.Workbooks.Open(myPath & "\" & fil.Name)
For Each wks In wkb.Worksheets
nextOpenRow = targetSheet.Cells(Rows.Count, 1).End(xlUp).Row + 1
lengthOfSection = wks.Cells(Rows.Count, 1).End(xlUp).Row
widthOfSection = wks.Cells(1, Columns.Count).End(xlToLeft).Column
'align values'
targetSheet.Range(targetSheet.Cells(nextOpenRow, 1), targetSheet.Cells(nextOpenRow + lengthOfSection - 1, widthOfSection).Address) = _
wks.Range(wks.Cells(1, 1).Address, wks.Cells(lengthOfSection, widthOfSection)).Value
Next wks
wkb.Close
End If
Next fil
'pass in the subfolders to the listing routine also
If incSub Then
For Each subfld In fld.SubFolders
Call dumpDirectory(myPath & "\" & subfld.Name, fileExtension, True, targetSheet)
Next subfld
End If
Exit Sub
done:
error = Err.Description
MsgBox (error & ". Operation stopped.")
End Sub
Bookmarks