【问题标题】:VBA Sumproduct on Array Columns数组列上的 VBA Sumproduct
【发布时间】:2014-12-09 07:10:03
【问题描述】:

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

【问题讨论】:

  • 什么是 VBA 数组?数组数组还是真正的二维数组?
  • 请尝试将您的问题形象化,以便我们更好地理解您的要求

标签: arrays excel vba


【解决方案1】:

虽然尝试使用 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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多