逐个元素地总结两个数组或矩阵

时间:2018-04-11 14:16:28

标签: excel vba excel-vba

我有两个像这样定义的变量:

Per_Mnd = Worksheets("Sheet1").Range("G2:G8").Value
Per_Mnd2 = Worksheets("Sheet2").Range("G2:G8").Value

显然,Per_MndPer_Mnd2都有7行1列。现在我想逐个元素地总结它们,获得另一个7×1数组。我该怎么做?

它们是由矩阵

定义的
Per_Mnd = Worksheets("Sheet1").Range("G2:H8").Value
Per_Mnd2 = Worksheets("Sheet2").Range("G2:H8").Value

如何逐个元素快速总结?

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以简单地评估INDEX公式以返回数组:

Sub Test()
Dim oarr As Variant
Dim Per_Mnd As Variant
Dim Per_Mnd2 As Variant
Per_Mnd = Worksheets("Sheet1").Range("G2:G8").Value
Per_Mnd2 = Worksheets("Sheet2").Range("G2:G8").Value

With Application
    oarr = .Transpose(.Evaluate("INDEX({" & Join(.Transpose(Per_Mnd), ",") & "}+{" & Join(.Transpose(Per_Mnd2), ",") & "},)"))
End With


Debug.Print oarr(3, 1)
End Sub

注意:这仅适用于相同大小的单列数组。

答案 1 :(得分:0)

如果要对矩阵求和,VBA方式为WorksheetFunction.SumProduct

以下面的例子为例,返回60 - > 1*10+2*10+3*10

enter image description here

Public Sub TestMe()

    Dim el1 As Variant
    Dim el2 As Variant
    Dim res As Variant

    el1 = Application.Transpose(Range("A1:A3"))
    el2 = Application.Transpose(Range("B1:B3"))
    Debug.Print WorksheetFunction.SumProduct(el1, el2)

    ReDim res(1 To UBound(el1))
    Dim cnt As Long

    For cnt = LBound(el1) To UBound(el1)
        res(cnt) = el1(cnt) + el2(cnt)
    Next cnt

End Sub

Application.Transpose()的想法是将Range()呈现为一维数组。一旦我们这样做,我们会介绍res(1 to UBound(el1)我们在每个元素上编写产品的地方。或者您甚至可以将SumArray作为函数执行,返回新数组:

Public Function SumArray(arr1 As Variant, arr2 As Variant) As Variant

    ReDim res(1 To UBound(arr1))
    Dim cnt As Long

    For cnt = LBound(arr1) To UBound(arr1)
        res(cnt) = arr1(cnt) + arr2(cnt)
    Next cnt

    SumArray = res

End Function