如果你想从 Array(a,b,c) 中实现一个像 Array(a,a+b,a+b+c) 这样的累积数组,那么这个函数就是实现它,如果你想传递开始和结束参数:
Public Sub TestMe()
Dim outputArray As Variant
Dim inputArray As Variant
Dim counter As Long
inputArray = Array(1, 2, 4, 8, 16, 32, 64)
outputArray = generateCumulativeArray(inputArray, 1, 4)
For counter = LBound(outputArray) To UBound(outputArray)
Debug.Print outputArray(counter)
Next counter
outputArray = generateCumulativeArray(inputArray, toValue:=4)
For counter = LBound(outputArray) To UBound(outputArray)
Debug.Print outputArray(counter)
Next counter
End Sub
Public Function generateCumulativeArray(dataInput As Variant, _
Optional fromValue As Long = 0, _
Optional toValue As Long = 0) As Variant
Dim i As Long
Dim dataReturn As Variant
ReDim dataReturn(0)
dataReturn(0) = dataInput(fromValue)
For i = 1 To toValue - fromValue
ReDim Preserve dataReturn(i)
dataReturn(i) = dataReturn(i - 1) + dataInput(fromValue + i)
Next i
generateCumulativeArray = dataReturn
End Function
关于只是对数组求和,这样做的方法是:
您可以使用 WorksheetFunction. 并且可以将数组作为参数传递。因此,您可以获得所有功能,例如Average、Min、Max 等:
Option Explicit
Public Sub TestMe()
Dim k As Variant
k = Array(2, 10, 200)
Debug.Print WorksheetFunction.Sum(k)
Debug.Print WorksheetFunction.Average(k)
End Sub
如果您想要从给定开始到给定结束的总和,最简单的方法可能是创建一个新数组并将其完全求和。在 Python 中这称为切片,在 VBA 中可以手动完成:
Public Sub TestMe()
Dim varArr As Variant
Dim colSample As New Collection
varArr = Array(1, 2, 4, 8, 16, 32, 64)
colSample.Add (1)
colSample.Add (2)
colSample.Add (4)
colSample.Add (8)
Debug.Print WorksheetFunction.Sum(generateArray(varArr, 2, 4))
Debug.Print WorksheetFunction.Sum(generateArray(colSample, 2, 4))
End Sub
Public Function generateArray(data As Variant, _
fromValue As Long, _
toValue As Long) As Variant
Dim i As Long
Dim dataInternal As Variant
Dim size As Long
size = toValue - fromValue
ReDim dataInternal(size)
For i = LBound(dataInternal) To UBound(dataInternal)
dataInternal(i) = data(i + fromValue)
Next i
generateArray = dataInternal
End Function
这个想法是generateArray 函数返回一个新数组。因此,它的完整总和就是您所需要的。它也适用于集合,不仅适用于数组。请注意,使用集合时,它们从索引 1 开始,而数组(通常)从 0 开始。如果您想对数组和集合使用相同的索引,请将 generateArray 函数更改为这个:
Public Function generateArray(data As Variant, _
fromValue As Long, _
toValue As Long) As Variant
Dim i As Long
Dim dataInternal As Variant
Dim size As Long
size = toValue - fromValue
ReDim dataInternal(size)
If IsArray(data) Then
For i = LBound(dataInternal) To UBound(dataInternal)
dataInternal(i) = data(i + fromValue)
Next i
Else
For i = LBound(dataInternal) To UBound(dataInternal)
dataInternal(i) = data(i + fromValue + 1)
Next i
End If
generateArray = dataInternal
End Function
或者在顶部写Option Base 1,数组将从1开始(不建议!)。