Excel VBA函数定义
合并所有工作簿
直接合并
Sub 合并当前目录下所有工作簿的全部工作表() Dim MyPath, MyName, AWbName Dim Wb As Workbook, WbN As String Dim G As Long Dim Num As Long Dim BOX As String Application.ScreenUpdating = False MyPath = ActiveWorkbook.Path MyName = Dir(MyPath & "\" & "*.xlsx") 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 #赋值语句:激活Sheet的A列最后一个单元格赋值为MyName去掉‘.xls’的部 .Cells(.Range("B305536").End(xlUp).Row + 2, 1) = Left(MyName, Len(MyName) - 4) For G = 1 To Sheets.Count Wb.Sheets(G).UsedRange.Copy .Cells(.Range("B305536").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 "共合并了" & Num & "个工作薄下的全部工作表。如下:" & Chr(13) & WbN, vbInformation, "提示" End Sub
只取第一个Sheet的 Header后合并所有的 Sheet
Sub 多语言文件合并() Dim MyPath, MyName, AWbName Dim Wb As Workbook, WbN As String Dim G As Long Dim Num As Long Dim BOX As String flag = 0 Application.ScreenUpdating = False MyPath = ActiveWorkbook.Path MyName = Dir(MyPath & "\" & "*.xlsx") 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 ' Workbooks(n) 为取工作簿 的写法 .Cells(.Range("B305536").End(xlUp).Row + 2, 1) = Left(MyName, Len(MyName) - 4) ' 赋值语句:激活Sheet的A列最后一个单元格 赋值为 (MyName去掉‘.xls’的部分) Left 截取字符串 去掉了'.xls' For G = 2 To Sheets.Count ' #嵌套循环体:遍历文件的所有Sheets 跳过第一个Sheet If flag = 0 Then Wb.Sheets(G).Range("a1", Wb.Sheets(G).Cells.SpecialCells(xlCellTypeLastCell)).Copy .Cells(.Range("B305536").End(xlUp).Row + 1, 1) flag = 1 Else Wb.Sheets(G).Range("a3", Wb.Sheets(G).Cells.SpecialCells(xlCellTypeLastCell)).Copy .Cells(.Range("B305536").End(xlUp).Row + 1, 1) End If Next WbN = WbN & Chr(13) & Wb.Name Wb.Close False End With End If MyName = Dir Loop Range("A1").Select Application.ScreenUpdating = True MsgBox "共合并了" & Num & "个工作薄下的全部工作表。如下:" & Chr(13) & WbN, vbInformation, "提示" End Sub