For simplicity, the following code only combines the data from each worksheet in the active workbook. However, it can be amended to include other workbooks as well.
The code loops through each worksheet in the active workbook. For each worksheet, it loops through each row, excluding the header row. For each row, the data is first transferred to an array, and then added to a collection. Then the combined data from the collection is transferred to another array. And, lastly, the contents of the array is transferred to a newly created worksheet.
Again, for simplicity, I have assumed that the data for each sheet contains only two columns. So I have declared currentRow()
as a 1-Row by 4-Column
array. The first two columns will store the worksheet data, and the third and fourth columns will store the corresponding workbook name and sheet name. You'll need to change the second dimension accordingly.
Option Explicit
Sub CombineAllData()
Dim sourceWorkbook As Workbook
Dim currentWorksheet As Worksheet
Dim newWorksheet As Worksheet
Dim currentData() As Variant
Dim currentRow(1 To 1, 1 To 4) As Variant
Dim allData() As Variant
Dim col As Collection
Dim itm As Variant
Dim i As Long
Dim j As Long
Set col = New Collection
Set sourceWorkbook = ActiveWorkbook
For Each currentWorksheet In sourceWorkbook.Worksheets
'get the data from the current worksheet
currentData = currentWorksheet.Range("a1").CurrentRegion.Value
'add each row of data to the collection, excluding the header row
For i = LBound(currentData) + 1 To UBound(currentData)
For j = 1 To 2
currentRow(1, j) = currentData(i, j)
Next j
currentRow(1, 3) = sourceWorkbook.Name
currentRow(1, 4) = currentWorksheet.Name
col.Add currentRow
Next i
Next currentWorksheet
'resize the array to store the combined data
ReDim allData(1 To col.Count, 1 To 4)
'transfer the data from the collection to the array
With col
For i = 1 To .Count
For j = 1 To 4
allData(i, j) = .Item(i)(1, j)
Next j
Next i
End With
'add a new worksheet to the workbook
Set newWorksheet = Worksheets.Add
'transfer the contents of the array to the new worksheet
newWorksheet.Range("a1").Resize(UBound(allData), UBound(allData, 2)).Value = allData
End Sub