Option Explicit
Sub Compile360Data()
'Put this code in a standard module in a new workbook.
'This code will not change any source data but the first and second sheets in
'the workbook containing it will be cleared each time the code is run
'Requirements:
' I have a folder called Data in this extension C:\Documents
' There are 12 sub-folder (Jan, Feb, Mar,.., Dec) in the folder Data.
' Every sub-folder (Jan, Feb, Mar,.., Dec) has 30 files (a1, a2, a3, a4, …a30)
'
' I need to build a database (one tab) with the information from all the 30
' files of every sub folder. In other words, I need to put the information
' of every single file (30*12) in one file.
Dim sFileBasePath As String
Dim sFilePathNameExt As String
Dim sFileNameExt As String
Dim lMonthIndex As Long
Dim lFileIndex As Long
Dim wks As Worksheet
Dim lDataWriteRow As Long
Dim lCopyOffsetRow As Long
Dim lReportWriteRow As Long
Dim lDataRowCount As Long
'Clear data from this workbook
With ThisWorkbook
.Worksheets(1).Cells.Clear
.Worksheets(2).Cells.Clear
.Worksheets(2).Range("A1").Resize(1, 2).Value = Array("Data Rows", "File Path Name Ext")
End With
sFileBasePath = "C:\Documents\Data" 'Trailing slash needed
lDataWriteRow = Cells(Rows.Count, 1).End(xlUp).Row
lCopyOffsetRow = 0
For lMonthIndex = 1 To 12
For lFileIndex = 1 To 30
sFilePathNameExt = sFileBasePath & Format(DateSerial(1, lMonthIndex, 1), "mmm") & "" & "a" & lFileIndex & ".xlsx"
Workbooks.Open Filename:=sFilePathNameExt, ReadOnly:=True
sFileNameExt = ActiveWorkbook.Name
For Each wks In Workbooks(sFileNameExt).Worksheets
'Convert to Values - uncomment next 2 rows if any formulas in data cells
ActiveSheet.UsedRange.Cells.Copy
ActiveSheet.UsedRange.Cells.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
'End Convert to Values
lDataRowCount = wks.Range("A1").CurrentRegion.Rows.Count - 1
wks.Range("A1").CurrentRegion.Offset(lCopyOffsetRow, 0).Copy _
Destination:=ThisWorkbook.Sheets(1).Cells(lDataWriteRow, 1)
With ThisWorkbook.Sheets(1)
lDataWriteRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
lCopyOffsetRow = 1
End With
With ThisWorkbook.Sheets(2)
lReportWriteRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
.Cells(lReportWriteRow, 1).Value = lDataRowCount
.Cells(lReportWriteRow, 2).Value = sFilePathNameExt & " " & wks.Name
End With
Next
Workbooks(sFileNameExt).Close SaveChanges:=False
Next
Next
End Sub