阵列列上的VBA Sumproduct

时间:2014-12-09 07:10:03

标签: arrays excel vba

在Excel VBA中是否有办法使用Application.WorksheetFunction.Sumproduct来获取2个数组列的sumproduct?例如,如果A和B是两个数组,每个数组有3行3列(VBA数组,而不是Excel数组),是否有一种简单的方法可以获得A的第3列和第2列B的sumproduct?如果是这样,语法是什么? 感谢

2 个答案:

答案 0 :(得分:0)

好的,似乎WorksheetFunction.Index也适用于数组数组。因此,您可以使用WorksheetFunction.Index的组合来获取第3列和第2列,使用WorksheetFunction.Transpose来获取列的1D阵列,然后使用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

答案 1 :(得分:0)

尽管尝试使用WorksheetFunction.SumProduct来执行此操作可能很诱人,但循环使用VBA数组比使用工作表函数更快 。在一个小测试中,我得到的 x40 性能提升超过了其他公布的答案。

这是一个如何做到的简单示例。您应该在输入和错误处理上添加有效性检查。

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