How to add two matrices in VBA?

I want to know how I can add two matrices in 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")

where A = [1, 2, 3, 4, 5] and B = [2, 3, 4, 5, 6] I want to get C = A + B, which is [3, 5, 7, 9, 11]

+4
source share
1 answer

Not sure, but closest you would get:

Edit2: Including Transposeboth below returns a 1D array.

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

You can also use MMULT WorksheetFunctionto get what you want.

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

The above works because your values ​​are in the worksheet.
If you need a clean VBA solution, you have to go in cycles.

+2
source

Source: https://habr.com/ru/post/1693442/


All Articles