Hi,
Here is the code based on the new information you supplied.
I have attached the updated workbook you supplied too.
Please note:
Currently the code is checking the sheet name if it contains "AO" or "GO". (InStr(1, UCase(
sh.Name)...
You refer to the
sheet title. I initially took it for the sheet name, but if Title is actually the heading of the sheet (as in cell A1), then replace UCase(
sh.Name) with the following: InStr(1, UCase(
sh.Range("A1").Value)... (Adjust the range reference as needed to point to the Title).
Code: Select all
Sub MergeSelectedWorkbooks()
Dim shSummary As Worksheet
Dim rgFiles As Range
Dim rgC As Range
Dim sFileName As String
Dim wb As Workbook
Dim sh As Worksheet
Dim lCnt As Long
Dim sMsg As String
Const sPath = "C:\Users\gg70397\Tracing\Documents\" ' << Change path as needed...
lCnt = 0
Set shSummary = ThisWorkbook.Worksheets("Summary")
Set rgBooks = ThisWorkbook.Sheets("WB Names").Range("A1").CurrentRegion
Set rgFiles = Intersect(rgBooks, rgBooks.Offset(1))
If rgFiles Is Nothing Then
MsgBox "No files were listed on the 'WB Names' sheet!" & vbNewLine & _
"The macro will now quit.", vbExclamation
Application.ScreenUpdating = True
Exit Sub
End If
Application.ScreenUpdating = False
rgFiles.Interior.Color = xlNone
shSummary.UsedRange.Offset(1).Clear
On Error Resume Next
For Each rgC In rgFiles.Cells
sFileName = rgC.Value
Set wb = Workbooks.Open(sPath & sFileName)
If Not wb Is Nothing Then
For Each sh In wb.Sheets
If InStr(1, UCase(sh.Name), "AO") > 0 Or InStr(1, UCase(sh.Name), "GO") > 0 Then
sh.Range("A2", sh.Cells(Rows.Count, "M").End(xlUp)).Copy _
shSummary.Range("A" & Rows.Count).End(xlUp).Offset(1)
End If
Next sh
wb.Close SaveChanges:=False
Else
rgC.Interior.Color = vbRed
lCnt = lCnt + 1
End If
Set wb = Nothing
sFileName = ""
Next rgC
On Error GoTo 0
shSummary.Columns.AutoFit
Application.ScreenUpdating = True
If lCnt > 0 Then
sMsg = "The macro completed its run, but some (or all) files were not found! " & _
"Files not found are marked in red on the 'WB Names' sheet."
MsgBox sMsg, vbExclamation
Else
sMsg = "Data from all files collected."
MsgBox sMsg, vbInformation
End If
End Sub
Destination.xlsm
You do not have the required permissions to view the files attached to this post.