要求:多个子表数据格式需一致
- 新建一个空文件夹,将需要合并的子表放在空文件夹中
- 在文件夹中新建一个空的excel文件
- 打开空的excel,右键Sheet1,点击查看代码
- 将以下代码粘贴到代码框中
1 Sub 合并当前目录下所有工作簿的全部工作表() 2 3 Dim MyPath, MyName, AWbName 4 5 Dim Wb As Workbook, WbN As String 6 7 Dim G As Long 8 9 Dim Num As Long 10 11 Dim BOX As String 12 13 Application.ScreenUpdating = False 14 15 MyPath = ActiveWorkbook.Path 16 17 MyName = Dir(MyPath & "\" & "*.xls") 18 19 AWbName = ActiveWorkbook.Name 20 21 Num = 0 22 23 Do While MyName <> "" 24 25 If MyName <> AWbName Then 26 27 Set Wb = Workbooks.Open(MyPath & "\" & MyName) 28 29 Num = Num + 1 30 31 With Workbooks(1).ActiveSheet 32 33 .Cells(.Range("B65536").End(xlUp).Row + 2, 1) = Left(MyName, Len(MyName) - 4) 34 35 For G = 1 To Sheets.Count 36 37 Wb.Sheets(G).UsedRange.Copy .Cells(.Range("B65536").End(xlUp).Row + 1, 1) 38 39 Next 40 41 WbN = WbN & Chr(13) & Wb.Name 42 43 Wb.Close False 44 45 End With 46 47 End If 48 49 MyName = Dir 50 51 Loop 52 53 Range("B1").Select 54 55 Application.ScreenUpdating = True 56 57 MsgBox "共合并了" & Num & "个工作薄下的全部工作表。如下:" & Chr(13) & WbN, vbInformation, "提示" 58 59 End Sub
- 点击运行按钮或按F5运行
- 关闭窗口,查看Excel中合并的数据,删除重复的表头即可
原文地址:https://www.cnblogs.com/yachyu/p/10708345.html
时间: 2024-10-09 08:54:53