本例的靓点:字典+数组,两种不同的处理方式; 较好地表达了,字典,数组,的应用方法. 仔细体会一下,字典+数组,的不同运用. '方法一,是Long_III版的(有注释). Private Sub CommandButton1_Click() Dim ds Dim i&, irow&, m&, m1&, s& Dim arr, Xarr(), Yarr() Dim aa As Double aa = Timer Range("f:i").ClearContents '清除f:i列的内容 Application.ScreenUpdating = False Set ds = CreateObject("scripting.dictionary") m = 1 For j = 1 To 4 '在A~D列里做一个循环 irow = Cells(65536, j).End(xlUp).Row arr = Range(Cells(1, j), Cells(irow, j)) '用数组取单元格的值 On Error Resume Next For i = 1 To irow If arr(i, 1) <> "" Then ds.Add arr(i, 1), m If Err.Number = 0 Then ReDim Preserve Xarr(1 To 2, 1 To m) Xarr(1, m) = arr(i, 1) Xarr(2, m) = Choose(j, "A", "B", "C", "D") m = m + 1 Else s = ds(arr(i, 1)) Xarr(2, s) = Xarr(2, s) & Choose(j, "A", "B", "C", "D") '出现重复的时候就统计它的列数 End If Err.Clear '清除错误数字 End If Next Next On Error GoTo 0 '重新恢复错误捕捉功能,以后出现错误还是会报错 '重新统计各种出现情况的次数 ds.RemoveAll '清除字典里的所有数据 m1 = 1 On Error Resume Next '此过程与上一个过程极其相似 For i = 1 To m - 1 ds.Add Xarr(2, i), m1 If Err.Number = 0 Then ReDim Preserve Yarr(1 To 2, 1 To m1) Yarr(1, m1) = Xarr(2, i) Yarr(2, m1) = 1 m1 = m1 + 1 Else s = ds(Xarr(2, i)) Yarr(2, s) = Yarr(2, s) + 1 '次数就是加1的效果 End If Err.Clear Next On Error GoTo 0 [f1].Resize(m - 1, 2) = Application.WorksheetFunction.Transpose(Xarr) '计算各个数在ABCD列中的出现情况 [h1].Resize(m1 - 1, 2) = Application.WorksheetFunction.Transpose(Yarr) '计算各种出现情况的次数 Application.ScreenUpdating = True MsgBox "Total:=" & Format(Timer - aa, "0.00") & "s" End Sub '方法二,是本人所写.代码相对容易理解. Sub tiger744990() Dim dic As Object, i&, n&, arr, Xarr, str As String, j As Byte Dim aa As Double aa = Timer Set dic = CreateObject("Scripting.Dictionary") Application.ScreenUpdating = False With dic For j = 1 To 4 With Sheet1 n = .Cells(65536, j).End(xlUp).Row: arr = .Range(.Cells(1, j), .Cells(n, j)) End With For i = 1 To n If Len(arr(i, 1)) <> 0 Then str = Choose(j, "A", "B", "C", "D") If Not .exists(arr(i, 1)) Then .Add arr(i, 1), str Else .Item(arr(i, 1)) = .Item(arr(i, 1)) & str End If End If Next Next Xarr = .Items Sheet1.[f:i].ClearContents Sheet1.[f1].Resize(.Count, 1) = WorksheetFunction.Transpose(.keys) Sheet1.[g1].Resize(.Count, 1) = WorksheetFunction.Transpose(.Items) .RemoveAll For i = 0 To UBound(Xarr) If Not .exists(Xarr(i)) Then .Add Xarr(i), 1 Else .Item(Xarr(i)) = .Item(Xarr(i)) + 1 Next Sheet1.[h1].Resize(.Count, 1) = WorksheetFunction.Transpose(.keys) Sheet1.[i1].Resize(.Count, 1) = WorksheetFunction.Transpose(.Items) End With Application.ScreenUpdating = True Set dic = Nothing MsgBox "Total:=" & Format(Timer - aa, "0.00") & "s" End Sub
ulXkLYST.rar
(26.64 KB, 下载次数: 1743)
[此贴子已经被作者于2007-11-22 13:08:28编辑过] |