-
Summing an Array
I have an array that contains the numbers (1,2,3,4). When I use the code below to sum the array, I get sum[arr(0)] = 1, sum[arr(0)+ arr(1)] = 12, sum[arr(0)+ arr(1) + arr(2)] = 123, sum[arr(0)+ arr(1) + arr(2) + arr(3) ] = 1234. Why are the numbers being appended to each other instead of being summed? Note: I am using arr(index,1) because I have a 2-dimensional array.
================================
If IsMissing(First) Then First = LBound(arr, 1)
If IsMissing(Last) Then Last = UBound(arr, 1)
For index = First To Last
If IgnoreEmpty = False Or Not IsEmpty(arr(index, 1)) Then
countcol1 = countcol1 + 1
sumcol1 = sumcol1 + arr(index, 1)
End If
Next
End If
End If
-
This would happen if you declared sumcol1 or arr as string type variables. The program would interpret the + sign as a string concatenation, instead of mathematic addition.
Change the declarations of the variables, or convert the string to and from numeric values to perform the math, like this:
sumcol1 = Str(Val(sumcol1) + Val(arr(index, 1)))
-
-
<?>
Code:
Private Sub Form_Load()
Dim arr(3)
arr(0) = 1
arr(1) = 2
arr(2) = 3
arr(3) = 4
x = (arr(0) + arr(1) + arr(2) + arr(3))
MsgBox x
End Sub
-
Wayne - I looked at your array file you posted in my earlier message and it makes sense - thanks. Unfortunately it doesn't help in my case. I am trying to work up a sample of what I'm doing in order to post it and hopefully get the problem resolved (i.e. redim the rows of multi-dimensional arrays). Keep an eye out and if you can help, great.