|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
不知道理解的对不对,仅供参考。
- Sub 汇总()
- Dim numb%, fil As String, filename As String, wb As Workbook, sht As Worksheet, t
- Dim n%, m%, k%, j%, arr, brr, crr(), i%, num%
- Dim dic1 As Object, dic2 As Object
- t = Timer
- Set dic1 = CreateObject("Scripting.Dictionary")
- Set dic2 = CreateObject("Scripting.Dictionary")
- With ThisWorkbook.Worksheets("汇总")
- Application.ScreenUpdating = False
- .Cells.Clear '全部清除
- ' .Range("A1") = "http://club.excelhome.net/thread-1472164-1-1.html" '原帖地址
- filename = Dir(ThisWorkbook.Path & "\*.xls") '取得代码工作簿所在文件夹下的文件名
- Do While filename <> ""
- If filename <> ThisWorkbook.Name Then
- ' numb = .Range("A1").CurrentRegion.Rows.Count + 1
- fil = ThisWorkbook.Path & "" & filename '获取对应路径下的文件
- Set wb = GetObject(fil)
- Set sht = wb.Worksheets("汇总")
- If .Range("A2") = "" Then
- arr = sht.Range("A4").CurrentRegion
- .Range("A1").Resize(UBound(arr, 1), UBound(arr, 2)) = arr
- Erase arr '清空数组
- Else
- n = .Cells(.Rows.Count, 2).End(3).Row '获取当前表中最后一行的行号
- arr = .Range("A4:BB" & n)
- m = sht.Cells(sht.Rows.Count, 2).End(3).Row '获取提取数据表中最后一行的行号
- brr = sht.Range("A4:BB" & m)
- For k = 1 To UBound(arr, 1) '先将汇总表人名写入字典中
- dic1(arr(k, 2)) = k '将数组元素装入字典中,并将对应条目值取对应序号
- Next
- 'For j = 1 To UBound(brr, 1) '再将待汇总表中的人名写入字典中
- ' dic2(brr(j, 2)) = ""
- 'Next
- ReDim crr(1 To UBound(brr, 1), 1 To UBound(brr, 2))
- For j = 1 To UBound(brr, 1)
- If Not dic1.Exists(brr(j, 2)) Then
- i = i + 1
- For k = 1 To UBound(brr, 2)
- crr(i, k) = brr(j, k)
- Next
- Else
- num = dic1.Item(brr(j, 2))
- For k = 4 To UBound(brr, 2)
- arr(num, k) = arr(num, k) + brr(j, k)
- Next
- End If
- Next
- Rem 将数组重新写入单元格
- .Range("A4").Resize(UBound(arr, 1), UBound(arr, 2)) = arr
- .Range("A4").Offset(UBound(arr, 1)).Resize(UBound(crr, 1), UBound(crr, 2)) = crr
- Erase brr '清空数组以备后续使用
- End If
- wb.Close False
- End If
- 'Else
- ' filename = Dir '没有Else此句,运行到代码工作簿时进入无限循环而死机!
- 'End If '也可以将end if 写在wb.Close False后面,就可以少一句filename = Dir
- dic1.RemoveAll
- dic2.RemoveAll '清空字典后续重新使用
- Erase arr
- Erase crr '清空crr数组后续重新使用
- i = 0 'i恢复0值后续重新使用
- filename = Dir
- Loop
- Application.ScreenUpdating = True
- End With
- MsgBox Format(Timer - t, "0.000 s")
- End Sub
复制代码 |
|