简体   繁体   English

阵列列上的VBA Sumproduct

[英]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? Excel VBA中是否有一种方法可以使用Application.WorksheetFunction.Sumproduct来获取2个数组列的sumproduct? 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? 例如,如果A和B是两个分别具有3行3列的数组(VBA数组,而不是Excel数组),是否有一种简单的方法来获取A的第三列与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. 尝试使用WorksheetFunction.SumProduct进行尝试虽然很诱人,但在VBA数组上循环比使用工作表函数快得多。 In a small test I got about a x40 performance improvement over the other posted answer. 在一个小型测试中,我得到的性能比其他发布的答案提高了x40

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. 好的,似乎WorksheetFunction.Index也可以与数组的数组一起使用。 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. 因此,您可以结合使用WorksheetFunction.Index来获取第三和第二列,以及WorksheetFunction.Transpose来获取列的一维数组,然后结合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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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