Consulting

Results 1 to 5 of 5

Thread: array sum

  1. #1

    array sum

    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?

  2. #2
    Site Admin
    Urban Myth
    VBAX Guru
    Joined
    May 2004
    Location
    Oregon, United States
    Posts
    4,940
    Location
    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?

  3. #3
    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

  4. #4
    VBAX Guru Kenneth Hobs's Avatar
    Joined
    Nov 2005
    Location
    Tecumseh, OK
    Posts
    4,956
    Location
    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.
    [vba]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[/vba]

  5. #5
    Site Admin
    Urban Myth
    VBAX Guru
    Joined
    May 2004
    Location
    Oregon, United States
    Posts
    4,940
    Location
    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •