WorksheetFunction.Sum
将使用范围或二维数组。它出错是因为您传递给它一个 3 维数组。
所以,这行得通
Public Function funtest(a As Double) As Double
Dim z As Long, j As Long, i As Long
Dim matrix() As Double
ReDim matrix(0 To 3, 0 To 4)
For j = LBound(matrix, 1) To UBound(matrix, 1)
For i = LBound(matrix, 2) To UBound(matrix, 2)
matrix(j, i) = a
Next i, j
funtest = Application.WorksheetFunction.Sum(matrix)
End Function
注意我稍微修改了您的声明,请参阅答案末尾的注释。
要对高维数组求和,您需要进行一些循环。
一种选择(可能适合也可能不适合您的总体要求)是声明您的数组略有不同,如所谓的Jagged Array
.
Public Function funtest2(a As Double) As Double
Dim z As Long, j As Long, i As Long
Dim matrix() As Variant
Dim InnerMatrix(0 To 4, 0 To 4) As Double
' Dimension Jagged Array
ReDim matrix(0 To 4)
For i = LBound(matrix, 1) To UBound(matrix, 1)
matrix(i) = InnerMatrix
Next
'Load Data into matrix
For z = LBound(matrix) To UBound(matrix)
For j = LBound(matrix(z), 1) To UBound(matrix(z), 1)
For i = LBound(matrix(z), 2) To UBound(matrix(z), 2)
matrix(z)(j, i) = a
Next i, j, z
' Sum matrix
For z = LBound(matrix) To UBound(matrix)
funtest2 = funtest2 + Application.WorksheetFunction.Sum(matrix(z))
Next
End Function
这是一个二维数组。然后Sum
依次将其应用于每个内部数组。这样,至少您只循环一个维度,而不是全部三个。
请注意Dim
,Integer
您必须指定所有As Type
的,否则变量默认为Variant
在您的代码中z
,并且j
将是Variants
此外,在 32 位操作系统上使用Integer
而不是Long
实际上会适得其反:Long
's 会稍微快一些。