vbanewbie365
New Member
- Joined
- Feb 26, 2023
- Messages
- 19
- Office Version
- 365
- Platform
- Windows
Hi friends,
So P45Cal helpfully posted some code that merged tables across several sheets and workbooks into a master table. the code read as below. As a VBA noob, I'm wondering how to adjust the code to only search specific sheets rather than all sheets. To be specific in my workbooks, I have several sheets which contain non-relevant information to the destination table, but the code currently searches all sheets and thus includes these title sheets. How can i specify the code to search only sheets that I choose, ideally by searching by sheet name as I'm not too confident in indexing the sheets etc. Any help is much appreciated!
So P45Cal helpfully posted some code that merged tables across several sheets and workbooks into a master table. the code read as below. As a VBA noob, I'm wondering how to adjust the code to only search specific sheets rather than all sheets. To be specific in my workbooks, I have several sheets which contain non-relevant information to the destination table, but the code currently searches all sheets and thus includes these title sheets. How can i specify the code to search only sheets that I choose, ideally by searching by sheet name as I'm not too confident in indexing the sheets etc. Any help is much appreciated!
VBA Code:
Sub blah()
Dim rngHdr As Range, HdrsToCopy As Range, DestRow As Range
Dim AllHeaders()
ReDim AllHeaders(0 To 0)
With ThisWorkbook
Set DestSheet = .Sheets.Add(after:=.Sheets(.Sheets.Count))
End With 'thisworkbook
With DestSheet
Set DestRow = .Cells(.Rows.Count, "A").End(xlUp).Offset(1) 'or any other column.
End With 'DestSheet
filenames = Application.GetOpenFilename("Excel files,*.xls*", MultiSelect:=True)
If IsArray(filenames) Then
For Each fName In filenames
Set WkBk = Workbooks.Open(fName)
For Each sht In WkBk.Sheets
rowscount = sht.UsedRange.Rows.Count - 1
For Each cll In sht.Rows(1).SpecialCells(xlCellTypeConstants, xlTextValues).Cells
NewHeader = False
HeaderColumn = 0
For i = LBound(AllHeaders) To UBound(AllHeaders)
If AllHeaders(i) = cll.Value Then
HeaderColumn = i
Exit For
End If
Next i
If HeaderColumn = 0 Then
If UBound(AllHeaders) = 0 Then ReDim AllHeaders(1 To UBound(AllHeaders) + 1) Else ReDim Preserve AllHeaders(1 To UBound(AllHeaders) + 1)
AllHeaders(UBound(AllHeaders)) = cll.Value
HeaderColumn = UBound(AllHeaders)
NewHeader = True
End If
If NewHeader Then DestSheet.Cells(1, HeaderColumn).Value = AllHeaders(HeaderColumn)
cll.Offset(1).Resize(rowscount).copy DestRow.Offset(, HeaderColumn - 1)
Next cll
Set DestRow = DestRow.Offset(rowscount)
Next sht
WkBk.Close False
Next fName
End If
End Sub