'测试了一下没有什么问题,哪一楼的代码?
'14楼附件20W+数据,快排比字典会快点。重复非常非常少字典的优势已经不存在了,,,
Option Explicit
Sub test()
Dim i, m, arr, filename, t, tm
filename = ThisWorkbook.Path & "\test.txt"
If Dir(filename) = vbNullString Then MsgBox filename: Exit Sub
tm = Timer
Call doevent(False)
Open filename For Input As #1
arr = Split(StrConv(InputB(LOF(1), 1), vbUnicode), vbNewLine)
Close #1
ReDim brr(1 To UBound(arr) + 2, 1 To 2)
For i = 0 To UBound(arr, 1)
arr(i) = Replace(arr(i), Space(1), vbNullString)
If InStr(arr(i), vbTab) Then
t = Split(arr(i), vbTab)
If UBound(t) <> 1 Then MsgBox arr(i): Call doevent(True): Exit Sub
m = m + 1
brr(m, 1) = t(0): brr(m, 2) = Val(t(1))
End If
Next
[g1].Resize(m, 2) = brr
Debug.Print "源数据:", Timer - tm
tm = Timer
Call 排序法(brr, m)
Debug.Print "排序:", Timer - tm
tm = Timer
Call 字典法(brr, m)
Debug.Print "字典:", Timer - tm
Call doevent(True)
End Sub
Function 字典法(arr, m)
Dim i, j, cnt, dic
Set dic = CreateObject("scripting.dictionary")
ReDim brr(1 To m, 1 To 2)
For i = 1 To m
If dic.exists(arr(i, 1)) Then
brr(dic(arr(i, 1)), 2) = brr(dic(arr(i, 1)), 2) + arr(i, 2)
Else
cnt = cnt + 1: dic(arr(i, 1)) = i
brr(cnt, 1) = arr(i, 1): brr(cnt, 2) = arr(i, 2)
End If
Next
[d1].Resize(cnt, 2) = brr
End Function
Function 排序法(arr, m)
Dim i, cnt, sum
ReDim brr(1 To m, 1 To 2)
Call qsort(arr, 1, m, 1, 2, 1)
For i = 1 To m
sum = sum + arr(i, 2)
If arr(i, 1) <> arr(i + 1, 1) Then
cnt = cnt + 1: brr(cnt, 1) = arr(i, 1)
brr(cnt, 2) = sum: sum = 0
End If
Next
[a1].Resize(cnt, 2) = brr
End Function
Function qsort(arr, first, last, left, right, key)
Dim i As Long, j As Long, k As Long, x, t
i = first: j = last: x = arr((first + last) \ 2, key)
While i <= j
While arr(i, key) < x: i = i + 1: Wend
While x < arr(j, key): j = j - 1: Wend
If i <= j Then
For k = left To right
t = arr(i, k): arr(i, k) = arr(j, k): arr(j, k) = t
Next
i = i + 1: j = j - 1
End If
Wend
If first < j Then qsort arr, first, j, left, right, key
If i < last Then qsort arr, i, last, left, right, key
End Function
Function doevent(flag As Boolean)
With Application
.DisplayAlerts = flag
.ScreenUpdating = flag
End With
End Function |