VBA:总结矩阵

时间:2012-09-12 03:15:24

标签: excel excel-vba matrix vba

为什么这个功能不起作用?

在Excel中输入=funtest(2.1),它会给我#VALUE!

Public Function funtest(a As Double) As Double

Dim z, j, i As Integer
Dim matrix(3, 3, 3) As Double

For z = 0 To 3 Step 1
For j = 0 To 3 Step 1
For i = 0 To 3 Step 1

matrix(z, j, i) = a

Next i, j, z

funtest = Application.WorksheetFunction.Sum(matrix)

End Function

3 个答案:

答案 0 :(得分:3)

WorksheetFunction.Sum可以使用范围或2维数组。它错误,因为你传递的是一个三维数组。

所以,这是有效的

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依次应用于每个内部数组。这样,至少你只循环一个维度,而不是全部三个维度。

关于DimInteger的说明 您必须指定所有As Type,否则变量默认为Variant
在您的代码zj中将Variants

此外,使用Integer而不是Long实际上在32位操作系统上会产生效果:Long的速度会稍快一些。

答案 1 :(得分:0)

当你说“我正试图解决(3,3,3)矩阵的简单情况时,我会用字面意思来理解你,每个元素等于一些双,a”。这样就可以了:

Public Function funtest(a As Double) As Double
   funtest = 4*4*4*a
End Function

答案 2 :(得分:-1)

首先,当你得到#VALUE!时,这意味着存在错误,这可能意味着使用无效的矩阵。

要回答您的问题,您的代码无效,因为您的语法不正确。以下函数根据值创建矩阵。

Function FQ_matrix_create(StartValue As Double, Interval As Double,
nrow As Long, ncol As Long) As Double()
Dim M() As Double
' Creates matrix with sequential element values with given row and
' column sizes. Fills matrix row-wise with numbers.
' - set Interval = 0 for constant element values
' - error input arguments nrow and ncol are not positive integers

要使用值SUM:

Function FQ_matrix_element_sum(M() As Double, SumOption As
MatrixDirection) As Double()
' Returns the sum of elements of matrix M, either row or column wise
' - Rowwise sum returns a horizontal 1xNcol matrix
' - Columnwise sum returns a vertical 1 xNrow matrix
' - Element sum (all elements) returns a 1x1 matrix
' - error if M is not a matrix
' - error if SumOption is not 1 (nRowWiseSum) or 2 (nColWiseSum) or
3 (nElementSum)

为了帮助您了解Excel VBA中的Matrix,这是一个很好的资源:http://finaquant.com/download/matrixvectorvba

具体来说,请查看网站上的PDF下载。