功能模仿Excel MMULT

时间:2015-10-01 16:15:59

标签: vba excel-vba excel

我想创建模拟用于乘法矩阵的标准Excel MMULT函数的函数。我的代码是:



Function MatrixMultiplication(Matrix1 As Range, Matrix2 As Range)

Dim m1() As Long, m2() As Long, m3() As Long
m1 = Matrix1
m2 = Matrix2

If Matrix1 Is Nothing Or Matrix2 Is Nothing Then GoTo Err1
If UBound(m1, 2) <> UBound(m2, 1) Then GoTo Err2

ReDim m3(UBound(m1, 1), UBound(m2, 2))

For i = LBound(m1) To UBound(m1, 1)
    For j = LBound(m2) To UBound(m1, 2)
        For k = 1 To UBound(m1, 2)
        m3(i, j) = m3(i,j)+ m1(i, k) * m2(k, i)
        Next k
    Next j
Next i

Dim Matrix3 As Range

Set Matrix3 = Range(ActiveCell.Address, ActiveCell.Offset(UBound(m1, 1) - 1, UBound(m2, 2) - 1))

Matrix3 = m3

Set MatrixMultiplication = Matrix3

Err1:
    Selection.Cells(0, 0).Value = CVErr(xlErrNull)
Err2:
    Selection.Cells(0, 0).Value = CVErr(xlErrNA)

End Function
&#13;
&#13;
&#13;

不知怎的,它不起作用。它应该作为CSE功能。谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

这是一个有效的版本。一个有点微妙的观点是,如果你传递它在范围内给出的数组,那么你需要将它们转换为常规数组。请注意函数开头附近的两行:

Function MatrixProduct(A As Variant, B As Variant) As Variant
    'Assumes that A,B are 1-based variant arrays
    'Or ranges containing such things.
    'Little error checking is done

    Dim m As Long, n As Long, p As Long, i As Long, j As Long, k As Long
    Dim C As Variant

    If TypeName(A) = "Range" Then A = A.Value
    If TypeName(B) = "Range" Then B = B.Value
    m = UBound(A, 1)
    p = UBound(A, 2)
    If UBound(B, 1) <> p Then
        MatrixProduct = "Not Defined!"
        Exit Function
    End If
    n = UBound(B, 2)

    ReDim C(1 To m, 1 To n)
    For i = 1 To m
        For j = 1 To n
            For k = 1 To p
                C(i, j) = C(i, j) + A(i, k) * B(k, j)
            Next k
        Next j
    Next i
    MatrixProduct = C
End Function

这可以直接在电子表格中使用,也可以直接在VBA代码中使用。它几乎肯定比内置的MMULT慢,所以我不太确定它有多么有用。