Hi all,
I have a folder with four files (e.g. Max, Peter, John, Marc). These workbooks each contain 12 worksheets all named identically (months of the year). Is it possible to have all the sheets named "January" copied from the four files into a new workbook? The sheets in this new workbook should be named after the original file, e.g. worksheet "January" from workbook "Max" is named "Max" in the new workbook. Eventually I want to have 12 new workbooks each containing the sheets Max, Peter, John and Marc.
I tried to put a code together from what I found on the internet. Unfortunately, it does not work and stops after one copied sheet with no renaming.
Any help is appreciated!
I have a folder with four files (e.g. Max, Peter, John, Marc). These workbooks each contain 12 worksheets all named identically (months of the year). Is it possible to have all the sheets named "January" copied from the four files into a new workbook? The sheets in this new workbook should be named after the original file, e.g. worksheet "January" from workbook "Max" is named "Max" in the new workbook. Eventually I want to have 12 new workbooks each containing the sheets Max, Peter, John and Marc.
I tried to put a code together from what I found on the internet. Unfortunately, it does not work and stops after one copied sheet with no renaming.
Any help is appreciated!
VBA Code:
Sub test()
Dim sFolder As String
Dim sFile As String
Dim wbSource As Workbook
Dim wbMaster As Workbook
sFolder = "B:\IT-DL\" 'remember trailing backslash
'set up the master workbook
Set wbMaster = ThisWorkbook
On Error GoTo errHandler 'reset application setting on error
Application.ScreenUpdating = False
'loop through all excel files in folder
sFile = Dir(sFolder & "*.xls*")
Do Until sFile = ""
'open the source workbook
If sFile <> wbMaster.Name Then 'don't process the master workbook
Set wbSource = Workbooks.Open(sFolder & sFile)
'copy the first worksheet
wbSource.Worksheets("January").Copy.PasteSpecial xlPasteAllUsingSourceTheme, After:=wbMaster.Sheets(wbMaster.Sheets.Count)
wbMaster.Worksheets("January").Name = Left(wbSource.Name, Len(wbSource.Name) - 4)
wbSource.Close SaveChanges:=False
Application.CutCopyMode = False
End If
'get the next file
sFile = Dir()
Loop
'tidy up
Set wbSource = Nothing
Set wbMaster = Nothing
errHandler:
Application.ScreenUpdating = True
End Sub