简体   繁体   中英

VBA Sumproduct on Array Columns

Is there a way in Excel VBA to use Application.WorksheetFunction.Sumproduct to get the sumproduct of 2 array columns? For example, if A and B are two arrays each with 3 rows and 3 columns (VBA arrays, not Excel arrays), is there an easy way to get the sumproduct of the 3rd column of A with the 2nd column of B? If so, what is the syntax? Thanks

While it might be tempting to try and use WorksheetFunction.SumProduct to do this, looping over a VBA array will be much faster than using worksheet functions. In a small test I got about a x40 performance improvement over the other posted answer.

This is a simple example of how you might do it. You should add validity checks on the inputs and error handling.

Function ArraySumProduct(aA As Variant, aB As Variant, col1 As Long, col2 As Long) As Variant
    Dim i As Long
    Dim dSumProduct

    For i = LBound(aA) To UBound(aA)
        dSumProduct = dSumProduct + aA(i, col1) * aB(i, col2)
    Next
    ArraySumProduct = dSumProduct
End Function

OK, seems as if WorksheetFunction.Index works with arrays of arrays also. So you can achieve this with a combination of WorksheetFunction.Index to get the 3rd and 2nd columns and WorksheetFunction.Transpose to get 1D-arrays of the columns and then WorksheetFunction.SumProduct.

Sub test()

 aA = [{1,2, 3;4,5, 6;7,8, 9}]
 aB = [{10, 11,12;13, 14,15;16, 17,18}]

 'aA = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9))
 'aB = Array(Array(10, 11, 12), Array(13, 14, 15), Array(16, 17, 18))

 aCol3of_aA = WorksheetFunction.Index(aA, 0, 3)
 aCol2of_aB = WorksheetFunction.Index(aB, 0, 2)

 aArr1 = WorksheetFunction.Transpose(aCol3of_aA)
 aArr2 = WorksheetFunction.Transpose(aCol2of_aB)

 dSumProduct = WorksheetFunction.SumProduct(aArr1, aArr2)
 '= 3*11 + 6*14 + 9*17 = 270

 MsgBox dSumProduct

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM