|
楼主 |
发表于 2023-1-19 20:05
|
显示全部楼层
Sub 合并同名表()
Dim FolderName As String, FileName As String
Dim FolderColl As New Collection, dicFile As Object
Set dicFile = CreateObject("scripting.dictionary") '创建字典
Dim wb模板 As Workbook, wb As Workbook
Dim 模板 As Boolean
FolderName = Dir(ThisWorkbook.Path & "\*", vbDirectory) '调用Dir函数查找本文件下文件的名字,vbDirectory目录或文件夹
Do While FolderName <> "" '循环查找文件,结束时将返回一个空字符串""
If FolderName <> ".." And FolderName <> "." And InStr(FolderName, ".xls") = 0 Then '前两个是虚拟目录,第三个是excel文件,目的:只保留文件夹名字
FolderColl.Add FolderName
End If
FolderName = Dir
Loop
For i = 1 To FolderColl.Count
FileName = Dir(ThisWorkbook.Path & "" & FolderColl.Item(i) & "\*")
Do While FileName <> ""
dicFile(FolderColl.Item(i) & "" & FileName) = FileName
FileName = Dir
Loop
Next
arr = dicFile.keys
Application.DisplayAlerts = False
For i = 1 To dicFile.Count
Debug.Print dicFile.Item(arr(i - 1))
For j = 1 To i - 1
If dicFile.Item(arr(i - 1)) = dicFile.Item(arr(j - 1)) Then
模板 = False
Exit For
Else
模板 = True
End If
Next
If 模板 Or i = 1 Then
Set wb模板 = Workbooks.Open(ThisWorkbook.Path & "" & arr(i - 1))
wb模板.SaveAs ThisWorkbook.Path & "\汇总" & wb模板.Name
r = wb模板.Sheets(1).Range("A" & wb模板.Sheets(1).Rows.Count).End(xlUp).Row + 1
For k = i + 1 To dicFile.Count
If "汇总" & dicFile.Item(arr(k - 1)) = wb模板.Name Then
Set wb = Workbooks.Open(ThisWorkbook.Path & "" & arr(k - 1))
endrow = wb.Sheets(1).Range("A" & wb.Sheets(1).Rows.Count).End(xlUp).Row
wb.Sheets(1).Rows("2:" & endrow).Copy
wb模板.Activate
wb模板.Sheets(1).Rows(r).Select
ActiveSheet.Paste
wb.Close
r = r + endrow - 1
End If
Next
wb模板.Save
wb模板.Close
End If
Next
Application.DisplayAlerts = True
End Sub
这个是原文 |
|