|
五、汇总当前文件夹及子文件夹下所有excel文件内容
这个代码用的的字典,好处是数据合并是进行了运算.缺点是只能合并两列.
对于有将文件夹下所有EXCEL sheet下的内容合并到一个sheet需求时,做了部分修改。
Public d
Sub 按钮1_Click()
Application.ScreenUpdating = False
ActiveSheet.UsedRange.ClearContents
Cells(1, 1) = "编号"
Cells(1, 2) = "数量"
Set d = CreateObject("scripting.dictionary")
Getfd (ThisWorkbook.path) 'ThisWorkbook.Path是当前代码文件所在路径,路径名可以根据需求修改
Application.ScreenUpdating = True
'If d.Count > 0 Then
'ThisWorkbook.Sheets(1).[a2].Resize(d.Count) = WorksheetFunction.Transpose(d.keys) '如果D.COUNT >65536,就需要调整,不能使用Transpose,因为Transpose 只支持65536以内数据
'ThisWorkbook.Sheets(1).[b2].Resize(d.Count) = WorksheetFunction.Transpose(d.items)
'End If
'd.RemoveAll
End Sub
Sub Getfd(ByVal pth)
Set Fso = CreateObject("scripting.filesystemobject")
Set ff = Fso.getfolder(pth)
For Each f In ff.Files '文件夹下的所有文件,除了文件夹
Rem 具体提取哪类文件,还是需要根据文件扩展名进行处理
If InStr(Split(f.Name, ".")(UBound(Split(f.Name, "."))), "xl") > 0 Then '判断是否为xlms文件 。
If InStr(f.Name, ThisWorkbook.Name) = 0 Then '文件中不包括当前excel
Set wb = Workbooks.Open(f)
For Each sht In wb.Sheets 'sheets中的每个sheet
If WorksheetFunction.CountA(sht.UsedRange) > 1 Then
aa = ThisWorkbook.ActiveSheet.Range("A65536").End(xlUp).Row + 1 'aa是便于将内容依次复制到当前sheet
sht.UsedRange.Copy ThisWorkbook.ActiveSheet.Cells(aa, 1) '将sht内容复制到当前sheet
End If
Next sht
wb.Close False
End If
End If
Next f
For Each fd In ff.subfolders '遍历文件夹下的所有子文件夹
Getfd (fd)
Next fd
End Sub
|
|