VB:类似数据透视计数、求和

假设有工作表:A列是订单编号,B列是订单数量。然后在E列取订单编号、F列对订单计数、G列对订单数量求和。

订单编号 数量 E F G
A00001 123 A00001 1 123
A00002 435 A00002 2 559
A00002 124 A00003 2 799
A00003 546      
A00003 253      


VB代码如下(如果不需设置外加条件,直接注释掉if就行):

Sub zz()
    Set d = CreateObject("Scripting.Dictionary")
    Set v = CreateObject("Scripting.Dictionary")
    ar = Range("A1").CurrentRegion
    For i = 2 To UBound(ar)
        d(ar(i, 1)) = d(ar(i, 1)) + 1 '计数
        v(ar(i, 1)) = v(ar(i, 1)) + ar(i, 2) '求和
    Next
    For Each k In d.keys
       ' If d(k) >= 3 Then
            Cells(1 + n, "E") = k
            Cells(1 + n, "F") = d(k)
            Cells(1 + n, "G") = v(k)
            n = n + 1
        'End If
    Next
End Sub

结果也可以用转置来处理

Cells(1, "E").Resize(d.Count) = Application.Transpose(d.keys)
Cells(1, "F").Resize(d.Count) = Application.Transpose(d.items)
Cells(1, "G").Resize(v.Count) = Application.Transpose(v.items)

参考自:http://club.excelhome.net/thread-1280695-1-1.html