对一个数组提取非重复元素进行求和
Function UniqueSum(ByVal ArraySource, ByVal IndexColumn As Integer, ByVal SumColumn As Integer) As Variant 'IndexColumn refers to the column of ArraySource that you want to extract unique items 'SumColumn refers to the column which stored values that you want to do sum Dim arr() Dim i, x, k As Long, ds As Object Set ds = CreateObject("scripting.dictionary") 'create a dictionary to extract unique items x = 1 'use to record the index of unique item For i = 1 To UBound(ArraySource, 1) On Error Resume Next ds.Add ArraySource(i, IndexColumn), x If Err.Number = 0 Then 'no duplicate ReDim Preserve arr(1 To 2, 1 To x) 'make it as horizonal array arr(1, x) = ArraySource(i, IndexColumn) arr(2, x) = ArraySource(i, SumColumn) x = x + 1 Else 'found duplicated item k = CLng(ds.Item(ArraySource(i, IndexColumn))) 'get the index If arr(2, k) = "#Err" Or TypeName(ArraySource(i, SumColumn)) = "String" Then arr(2, k) = "#Err" Else arr(2, k) = arr(2, k) + ArraySource(i, SumColumn) 'make summarization End If End If Err.Clear: On Error GoTo 0 Next i UniqueSum = Application.Transpose(arr) 'transpose horizonal array to vertical End Function |