Add Book1.xls, Book2.xls to "C:\test\"
Situation:
Add the following code lines to the command button:
1. First, we declare two variables of type String, a Worksheet object and one variable of type Integer.
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer2. Turn off screen updating and displaying alerts.
Application.ScreenUpdating = False3. Initialize the variable directory. We use the Dir function to find the first *.xl?? file stored in this directory.
Application.DisplayAlerts = False
directory = "c:\test\"Note: The Dir function supports the use of multiple character (*) and single character (?) wildcards to search for all different type of Excel files.
fileName = Dir(directory & "*.xl??")
4. The variable fileName now holds the name of the first Excel file found in the directory. Add a Do While Loop.
Do While fileName <> ""Add the following code lines (at 5, 6, 7 and 8) to the loop.
Loop
5. There is no simple way to copy worksheets from closed Excel files. Therefore we open the Excel file.
Workbooks.Open (directory & fileName)6. Import the sheets from the Excel file into import-sheet.xls
For Each sheet In Workbooks(fileName).WorksheetsExplanation: the variable total holds track of the total number of worksheets of import-sheet.xls. We use the Copy method of the Worksheet object to copy each worksheet and paste it after the last worksheet of import-sheets.xls.
total = Workbooks("import-sheets.xls").Worksheets.count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("import-sheets.xls").Worksheets(total)
Next sheet
7. Close the Excel file.
Workbooks(fileName).Close8. The Dir function is a special function. To get the other Excel files, you can use the Dir function again with no arguments.
fileName = Dir()Note: When no more file names match, the Dir function returns a zero-length string (""). As a result, Excel VBA will leave the Do While loop.
9. Turn on screen updating and displaying alerts again (outside the loop).
Application.ScreenUpdating = True10. Test the program.
Application.DisplayAlerts = True
Result:
.