合并excel分为两种情况:1、将多个excel文件合并在一个excel中的不同sheet中。2、将多个excel文件合并在一个excel文件的一个sheet中。

1、将多个excel的文件合并在一个excel文件的不同sheet中。

(1)首先,我们在Epan下的vb文件夹中创建4个excel文件,明明如下。

合并多个Excel-LMLPHP

(2)打开命名为allExcel文件,按alt+F11调出vb编辑接口

合并多个Excel-LMLPHP

(3)点击ThisWorkBook,并粘贴如下代码:


  1. Private Sub hb()
  2. Dim hb As Object, kOne As Boolean, tabcolor As Long
  3. Set hb = Workbooks.Add
  4. Application.DisplayAlerts = False
  5. For i = hb.Sheets.Count To 2 Step -1
  6. hb.Sheets(i).Delete
  7. Next
  8. Dim FileName As String, FilePath As String
  9. Dim iFolder As Object, rwk As Object, Sh As Object
  10. Set iFolder = CreateObject("shell.application").BrowseForFolder(0, "请选择要合并的文件夹", 0, "")
  11. If iFolder Is Nothing Then Exit Sub
  12. FilePath = iFolder.Items.Item.Path
  13. FilePath = IIf(Right(FilePath, 1) = "\", FilePath, FilePath & "\")
  14. FileName = Dir(FilePath & "*.xls*")
  15. Do Until Len(FileName) = 0
  16. If UCase(FilePath & FileName) <> UCase(ThisWorkbook.Path & "\" & ThisWorkbook.Name) Then
  17. Set rwk = Workbooks.Open(FileName:=FilePath & FileName)
  18. tabcolor = Int(Rnd * 56) + 1
  19. With rwk
  20. For Each Sh In .Worksheets
  21. Sh.Copy After:=hb.Sheets(hb.Sheets.Count)
  22. hb.Sheets(hb.Sheets.Count).Name = FileName & "-" & Sh.Name
  23. hb.Sheets(hb.Sheets.Count).Tab.ColorIndex = tabcolor
  24. If Not kOne Then hb.Sheets(1).Delete: kOne = True
  25. Next
  26. .Close True
  27. End With
  28. End If
  29. Set rwk = Nothing
  30. FileName = Dir
  31. Loop
  32. Application.DisplayAlerts = True
  33. End Sub

(3)按F5运行,会弹出让你选择要合并的文件夹的窗口

合并多个Excel-LMLPHP

(4)代码执行结果如下:

合并多个Excel-LMLPHP

2、将多个excel文件合并在一个excel文件的一个sheet中。

(1)打开allExcel调出VB编程接口,粘贴如下代码


  1. sub 合并当前目录下所有工作簿的全部工作表()
  2. dim mypath, myname, awbname
  3. dim wb as workbook, wbn as string
  4. dim g as long
  5. dim num as long
  6. dim box as string
  7. application.screenupdating = false
  8. mypath = activeworkbook.path
  9. myname = dir(mypath & "\" & "*.xls")
  10. awbname = activeworkbook.name
  11. num = 0
  12. do while myname <> ""
  13. if myname <> awbname then
  14. set wb = workbooks.open(mypath & "\" & myname)
  15. num = num + 1
  16. with workbooks(1).activesheet
  17. .cells(.range("a65536").end(xlup).row + 2, 1) = left(myname, len(myname) - 4)
  18. for g = 1 to sheets.count
  19. wb.sheets(g).usedrange.copy .cells(.range("a65536").end(xlup).row + 1, 1)
  20. next
  21. wbn = wbn & chr(13) & wb.name
  22. wb.close false
  23. end with
  24. end if
  25. myname = dir
  26. loop
  27. range("a1").select
  28. application.screenupdating = true
  29. msgbox "共合并了" & num & "个工作薄下的全部工作表。如下:" & chr(13) & wbn, vbinformation, "提示"
  30. end sub

(2)按F5运行代码,选择要合并的文件,效果如下

合并多个Excel-LMLPHP

04-26 21:42