Option Explicit
Sub UpdateReportWorksheets()
Const bExt As Boolean = False 'Set True if extension should be part of comparison between Source and Target FileNameExt
Dim sPath As String
Dim oFile As Object, x As Long
Dim aryFiles() As Variant, lFileIndex As Long
Dim sSourceFileName As String, lSFIndex As Long
Dim sTargetFileName As String, lTFIndex As Long
Dim sChunk As String
Dim sSCheck As String
ThisWorkbook.Activate
AddAndNameReportSheet
sPath = "C:\Report"
'Create File Array of all files in sPath
For Each oFile In CreateObject("scripting.filesystemobject").GetFolder(sPath).Files
lFileIndex = lFileIndex + 1: ReDim Preserve aryFiles(1 To lFileIndex): aryFiles(lFileIndex) = oFile.Name
Next
'Find each Target File (Starts with Report-)
For lTFIndex = LBound(aryFiles) To UBound(aryFiles)
If Left(aryFiles(lTFIndex), 7) = "Report-" Then
sTargetFileName = aryFiles(lTFIndex)
'Find Corresponding Source File
sChunk = Mid(sTargetFileName, 8, InStrRev(sTargetFileName, ".") - 8)
If bExt Then sChunk = Mid(sTargetFileName, 8)
For lSFIndex = LBound(aryFiles) To UBound(aryFiles)
sSourceFileName = aryFiles(lSFIndex)
sSCheck = Left(sSourceFileName, InStrRev(sSourceFileName, ".") - 1) 'If you want to ignore extension
If bExt Then sSCheck = aryFiles(lSFIndex)
If sSCheck = sChunk Then
Exit For
Else
sSourceFileName = vbNullString
End If
Next
If sSourceFileName <> vbNullString Then
'Open target files and copy worksheets
Workbooks.Open fileName:=sPath & "\" & sTargetFileName
Workbooks.Open fileName:=sPath & "\" & sSourceFileName, ReadOnly:=True
Sheets(1).Copy Before:=Workbooks(sTargetFileName).Sheets(1)
'Close files
Workbooks(sTargetFileName).Close SaveChanges:=True 'Save Target
Workbooks(sSourceFileName).Close SaveChanges:=False
AddToReport "Updated " & sTargetFileName & " from " & sSourceFileName
Else
AddToReport "No matching source file for " & sTargetFileName
End If
End If
Next
Application.StatusBar = False
End Sub
Sub AddAndNameReportSheet()
Dim sWorksheet As String
sWorksheet = "Report"
On Error Resume Next
Application.DisplayAlerts = False
Worksheets(sWorksheet).Delete
Application.DisplayAlerts = True
On Error GoTo 0
Worksheets.Add(Before:=Sheets(1)).Name = sWorksheet 'After last
End Sub
Sub AddToReport(sItem As String)
Dim lNextReportWriteRow As Long
With ThisWorkbook.Worksheets("Report")
lNextReportWriteRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
.Cells(lNextReportWriteRow, 1).Value = Now()
.Cells(lNextReportWriteRow, 2).Value = sItem
End With
Application.StatusBar = sItem
DoEvents
End Sub