2022-05-26 excel-VBA程式碼-快速合併多個工作表
阿新 • • 發佈:2022-05-26
前提:
先新建一個excel工作表,命名為“合併表”。
被合併的多個工作表的表頭欄位相同,並且被合併的工作表與合併後的“合併表”檔案要在同一目錄下。
Excel軟體與wps軟體,都是點選<開發工具> --> <VB編輯器> --> <插入> --> <模組> ,將VBA程式碼複製進去,然後點選<執行> --> <執行子過程>。
Sub 合併工作表() Dim MyPath, MyName, AWbName Dim Wb As Workbook, WbN As String Dim G As LongDim 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 .Cells(.Range("B65536").End(xlUp).Row + 2, 1) = Left(MyName, Len(MyName) - 4) For G = 1 To Sheets.Count Wb.Sheets(G).UsedRange.Copy .Cells(.Range("B65536").End(xlUp).Row + 1, 1) Next WbN = WbN & Chr(13) & Wb.Name Wb.Close False End With End If MyName = DirLoop Range("B1").Select Application.ScreenUpdating = True MsgBox "共合併了" & Num & "個工作薄下的全部工作表。如下:" & Chr(13) & WbN, vbInformation, "提示" End Sub