Excel多表合并之vba实现

需求

保留列名,复制每一个excel里的数据,合并到一个excel

操作步骤

1、将要合并的文件放在“明细表”文件夹下,复制过来就好。

2、在这个目录下创建一个“多表合并”的EXCEL文件。

3、双击打开“多表合并.xls”

4、同时按 ALT + F11,

5、点“插入”--“模块”,将下列代码拷贝进入,并保存。

VBA源代码:

Sub 合并工作表()
Dim MyPath, MyName, AWbName, t
Dim Wb As Workbook, WbN As String
Dim G As Long
Dim Num As Long
Dim BOX As String
t = Timer
'Application.ScreenUpdating = False
MyPath = ActiveWorkbook.Path
MyName = Dir(MyPath & "\明细表\" & "*.xls")
AWbName = ActiveWorkbook.Name
Num = 0
Do While MyName <> ""
If MyName <> AWbName Then
Set Wb = Workbooks.Open(MyPath & "\明细表\" & MyName)
Num = Num + 1
With Workbooks(1).ActiveSheet
.Cells(.Range("A65536").End(xlUp).Row + 2, 1) = Left(MyName, Len(MyName) - 4)
For G = 1 To Sheets.Count
Wb.Sheets(G).UsedRange.Copy .Cells(.Range("A65536").End(xlUp).Row + 1, 1)
Next
WbN = WbN & Chr(13) & Wb.Name
Wb.Close False
End With
End If
MyName = Dir
Loop
Range("A1").Select
'Application.ScreenUpdating = True
MsgBox "报表汇总完毕,用时" & Timer - t & "秒!。共合并了" & Num & "张表。 "

End Sub

 

 

5、运行宏程序。

 

点击下载EXCEL  VBA  多表合并宏程序VBA

发表评论