如何在VBA中添加两个矩阵?

时间:2018-02-10 01:10:20

标签: vba excel-vba excel

我想知道如何在VBA中添加两个矩阵:

Sub add_two_matrices()
Dim A As Variant
Dim B as Variant
A = ActiveWorkbook.Sheets("Location_of_A").Range("A1: A5")
B = ActiveWorkbook.Sheets("Location_of_B").Range("A1: A5")

其中A = [1,2,3,4,5]和B = [2,3,4,5,6] 我想获得C = A + B,即[3,5,7,9,11]

1 个答案:

答案 0 :(得分:2)

不确定,但最接近的是:

Edit2:在下面合并Transpose将返回1D数组。

Dim c, i As Integer
c = Evaluate("Transpose(Location_of_A!A1:A5)+Transpose(Location_of_B!A1:A5)")

'/* loop to check the values */
For i = LBound(c) To UBound(c)
    Debug.Print c(i)
Next

您也可以使用MMULT WorksheetFunction来获得所需内容。

Dim a, b, c, i As Integer

With Application
    a = .Transpose(Sheets("Location_of_A").Range("A1:A5"))
    b = .Transpose(Sheets("Location_of_B").Range("A1:A5"))
    c = .WorksheetFunction.MMult(Array(1, 1), Array(a, b))
End With

'/* loop to check values */
For i = LBound(c) To UBound(c)
    Debug.Print c(i)
Next

以上是有效的,因为您的值在工作表中 但是,如果您需要纯VBA解决方案,则必须循环。