PDA

View Full Version : array sum



fmg.mdq
01-20-2009, 09:58 AM
Hi guys!
i having an issue when i tried to sum two arrays.
Example:
Sub suma_arrays()
Dim arr1(1 To 2, 1 To 2) As Variant
Dim arr2(1 To 2, 1 To 2) As Variant
Dim arr3(1 To 2, 1 To 2) As Variant
arr1(1, 1) = 1
arr1(1, 2) = 2
arr1(2, 1) = 3
arr1(2, 2) = 4
arr2(1, 1) = 1
arr2(1, 2) = 2
arr2(2, 1) = 3
arr2(2, 2) = 4
arr3 = arr2+arr1
End Sub
but excel shows me that types didn't match!
Any ideas?

Zack Barresse
01-20-2009, 11:28 AM
Hi there, welcome!

How exactly do you want to add these? Just add all elements? You have a 2x2 array (two of them), so you'll need to define just exactly what you want to add. With the example shown, what should be the expected results? 20?

fmg.mdq
01-20-2009, 11:40 AM
ok you are right, i expect to obtain a 2x2 array, i know i can do ti with a for but i want to know if there some excel function to do it faster!
result
arr3(1, 1) = 2
arr3(1, 2) = 4
arr3(2, 1) = 6
arr3(2, 2) = 8

Kenneth Hobs
01-20-2009, 11:45 AM
While one could add the elements in a For loop using LBound and Ubound a bit similar to what I did in this For loop, I just used the ArrayAdd() and related routines in the link.
Sub suma_arrays()
Dim arr1(1 To 2, 1 To 2) As Variant
Dim arr2(1 To 2, 1 To 2) As Variant
Dim arr3() As Variant
arr1(1, 1) = 1
arr1(1, 2) = 2
arr1(2, 1) = 3
arr1(2, 2) = 4
arr2(1, 1) = 1
arr2(1, 2) = 2
arr2(2, 1) = 3
arr2(2, 2) = 4

'Add module from: http://home.pacbell.net/beban/
arr3 = ArrayAdd(arr2, arr1)
Dim i As Integer, j As Integer
For i = 1 To 2
For j = 1 To 2
Debug.Print "arr3(" & i & "," & j & ")", arr3(i, j)
Next j
Next i
End Sub

Zack Barresse
01-20-2009, 12:41 PM
And what of the results? Do you want to keep it in an array? Shall you sum all of the results together? Please explain more.