Using the SUM function in vb6 to sum elements in an array

I need to sum over a subset of elements in an array of doubles. As a simple example, consider an array of 10 elements:

Dim Array(1 To 10) As Double 

where each element is assigned a specific value. Is there a function in VB that sums up the first 5 elements? Obviously, this can be solved with a loop, but is there a single-line solution? I would like to save my code. I tried using SUM, but to no avail.

Thanks!

+4
source share
1 answer

No, in VB6 there is no built-in summing function that does what you want, but you can easily write:

 Public Function SumRange(ByRef dblArray() As Double, Optional ByVal StartRange As Long = -1, Optional ByVal Length As Long = -1) '-1 on StartRange indicates start at low bound If StartRange = -1 Then StartRange = LBound(dblArray) End If '-1 on Length indicates to span all elements to the end of the array If Length = -1 Then Length = UBound(dblArray) - StartRange - 1 End If Dim dTotal As Double Dim lNdx As Long For lNdx = StartRange To StartRange + Length - 1 dTotal = dTotal + dblArray(lNdx) Next lNdx SumRange = dTotal End Function 

Remember that I did not check this, so watch out for typos. It can be used as follows:

 dResult = SumRange(myArray) 'summ all dResult = SumRange(myArray, 3) 'sum all starting at offset 3 dResult = SumRange(myArray, , 2) 'sum the the first 2 elements dResult = SumRange(myArray, 2, 4) 'sum a range start at 2 and with length of 4 

You can change the method to use another optional boolean value to indicate whether you will tolerate (ignore) outside the bounds. At the moment, the error will be repaired if you ask to summarize more elements than existing ones in the array.

+3
source

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


All Articles