1. '功能:不同表头Excel文件合并
    2. '作者:E精精
    3. '下载:公众号- Excel办公实战
    4. '-------------------------------------------------------------------
    5. Sub ComData()
    6. Dim sPath As String
    7. '选择文件夹
    8. With Application.FileDialog(msoFileDialogFolderPicker)
    9. If .Show Then
    10. sPath = .SelectedItems(1)
    11. sPath = sPath & IIf(VBA.Right(sPath, 1) = "\", "", "\")
    12. Else
    13. End
    14. End If
    15. End With
    16. Dim file As String, ShtCount As Long
    17. Dim dTitle As Object, dData As Object
    18. Dim Sht As Worksheet, wb As Workbook
    19. file = Dir(sPath & "*.xl*")
    20. Set dTitle = CreateObject("Scripting.dictionary")
    21. Set dData = CreateObject("Scripting.dictionary")
    22. Dim ShtName As String, wbName As String
    23. t = Timer
    24. '标题和数据分别装入字典备用
    25. Application.ScreenUpdating = False
    26. Do While Len(file) > 0
    27. Set wb = Workbooks.Open(sPath & file, False, True)
    28. For Each Sht In wb.Worksheets
    29. ShtCount = ShtCount + 1
    30. arr = Sht.Range("A1").CurrentRegion.Value
    31. ShtName = Sht.Name '工作表名称
    32. wbName = Split(wb.Name, ".")(0) '文件名
    33. dData(wbName & "|" & ShtName) = arr
    34. For i = 1 To UBound(arr, 2)
    35. If Not dTitle.exists(arr(1, i)) Then
    36. k = k + 1
    37. dTitle(arr(1, i)) = k
    38. End If
    39. Next
    40. Next
    41. wb.Close 0
    42. file = Dir
    43. Loop
    44. Application.ScreenUpdating = True
    45. Dim brr()
    46. '+2 文件名+表名
    47. ReDim brr(1 To 100000, 1 To dTitle.Count + 2)
    48. For Each eve In dData.keys()
    49. arr = dData(eve)
    50. For i = 2 To UBound(arr)
    51. n = n + 1
    52. tp = Split(eve, "|")
    53. brr(n, 1) = tp(0) '文件名
    54. brr(n, 2) = tp(1) '表名
    55. For j = 1 To UBound(arr, 2)
    56. brr(n, dTitle(arr(1, j)) + 2) = arr(i, j)
    57. Next
    58. Next
    59. Next
    60. '写入汇总表,没有的自己建一个
    61. With Sheets("汇总表")
    62. .Cells.Clear
    63. .Range("A1:B1") = Array("文件名", "表名")
    64. .Range("C1").Resize(1, dTitle.Count) = dTitle.keys()
    65. .Range("A2").Resize(n, dTitle.Count + 2) = brr
    66. End With
    67. MsgBox "汇总完成!共汇总:" & ShtCount & "个表!" _
    68. & vbCrLf & "用时:" & Format(Timer - t, "0.00s")
    69. End Sub