drpdrpdrp
New Member
- Joined
- Sep 9, 2021
- Messages
- 22
- Office Version
- 2019
- 2016
- Platform
- Windows
Hi All,
How can I make the following structure faster or simpler? Simple running cumulative sum of elements in an array returning an array of the same size. I've heard using For Each should make things faster but the lag I'm noticing with the structure below is noticeable on a few arrays per sheet (arrays are 100,000 rows each).
Function CumulativeSum(myArray As Variant) As Variant
Dim result() As Variant
Dim element As Variant
Dim i As Long
' Resize the result array to match the size of input array
ReDim result(1 To UBound(myArray))
' Initialize the cumulative sum variable
Dim sum As Double
sum = 0
i = 1
' Loop through each element in the array using For Each
For Each element In myArray
' Convert the element to a number (assuming the array contains numbers)
element = Val(element)
' Calculate cumulative sum
sum = sum + element
' Store the cumulative sum in the result array
result(i) = sum
i = i + 1
Next element
' Return the array of cumulative sums
CumulativeSum = result
End Function
How can I make the following structure faster or simpler? Simple running cumulative sum of elements in an array returning an array of the same size. I've heard using For Each should make things faster but the lag I'm noticing with the structure below is noticeable on a few arrays per sheet (arrays are 100,000 rows each).
Function CumulativeSum(myArray As Variant) As Variant
Dim result() As Variant
Dim element As Variant
Dim i As Long
' Resize the result array to match the size of input array
ReDim result(1 To UBound(myArray))
' Initialize the cumulative sum variable
Dim sum As Double
sum = 0
i = 1
' Loop through each element in the array using For Each
For Each element In myArray
' Convert the element to a number (assuming the array contains numbers)
element = Val(element)
' Calculate cumulative sum
sum = sum + element
' Store the cumulative sum in the result array
result(i) = sum
i = i + 1
Next element
' Return the array of cumulative sums
CumulativeSum = result
End Function