As the title says, I am attempting to copy all visible worksheets from a set of workbooks into a single workbook.
All of the workbooks are always in the same directory, but they will vary in file name. I had tried originally using the code below, but I'm running into issues where the 'Next Sheet' line attempts to go to the next sheet in the workbook its copying from, even if there are no more worksheets.
More specifically, my underlying workbooks which I'm trying to combine have a varying number of worksheets; some have one, some have many, and some have many with hidden worksheets too. I am only trying to copy sheets that are visible, and need to be able to handle the situation where a workbook could have one or many sheets.
I had tried a variant of the code below where I would count sheets and go to a separate code if there was one or more than one sheet, but that wasn't working either. Any help is much appreciated, and thank you all for your time.
Sub ConslidateWorkbooks()
Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet
Application.ScreenUpdating = False
FolderPath = "MyPath"
Filename = Dir(FolderPath & "*.xls*")
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy after:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
Application.ScreenUpdating = True
End Sub
ActiveWorkbook
should be the workbook that was opened by theWorkbooks.Open
statement, but if you are interacting with the workbooks while the code is being run,ActiveWorkbook
will be whichever workbook you are looking at when it hits that line. (That's why the use ofActiveWorkbook
,ActiveSheet
,Selection
etc is discouraged.) – YowE3K