I have two issues with this code:
- I want to copy a specific sheet, rather than all sheets in the workbooks
- Some of the source workbooks have a macro in them, this throws a 'Excel Security Notice' which interrupts the execution of the code and all worksheets don't copy over
Issue 1 target behaviour: I want to select files from a folder and have a specific worksheet copied over into my reporting template. This worksheet is always in tab position 1 and always contains "current and closed".
With the below code I have found online, it functions, but brings all worksheets from the source workbooks, including hidden sheets. I only want either the first tab, or the tab containing "current and closed" to be copied over.
Issue 2 target behaviour: I want the code to ignore/evade the security notice so that the migration of source worksheets that have a macro in them is uninterrupted. I don't mind if the macro in the source workbooks is disabled as they aren't required in the consolidated reporting workbook
Thanks for your collective brain power!
Sub mergeFiles() 'Merges all files in a folder to a main file. 'https://professor-excel.com/merge-excel-files-combine-workbooks-one-file/#Method_4_Merge_files_with_a_simple_VBA_macro
'Define variables:
Dim numberOfFilesChosen, i As Integer
Dim tempFileDialog As FileDialog
Dim mainWorkbook, sourceWorkbook As Workbook
Dim tempWorkSheet As Worksheet
Set mainWorkbook = Application.ActiveWorkbook
Set tempFileDialog = Application.FileDialog(msoFileDialogFilePicker)
'Allow the user to select multiple workbooks
tempFileDialog.AllowMultiSelect = True
numberOfFilesChosen = tempFileDialog.Show
'Loop through all selected workbooks
For i = 1 To tempFileDialog.SelectedItems.Count
'Open each workbook
Workbooks.Open tempFileDialog.SelectedItems(i)
Set sourceWorkbook = ActiveWorkbook
'Copy each worksheet to the end of the main workbook
For Each tempWorkSheet In sourceWorkbook.Worksheets
tempWorkSheet.Copy after:=mainWorkbook.Sheets(mainWorkbook.Worksheets.Count)
Next tempWorkSheet
'Close the source workbook without saving changes in the source workbooks
sourceWorkbook.Close savechanges:=False
Next i
End Sub
For Each tempWorkSheet In sourceWorkbook.Worksheets
and change thetempWorkSheet
in the next line tosourceWorkbook.Worksheets(1)
. – BigBenFor Each tempWorkSheet In sourceWorkbook.Worksheets
and theNext tempWorkSheet
. – BigBen