这是我第一次编写涉及数组的VBA代码。我有一个问题,MatrixMult函数(计算M1和M2矩阵)无法从MatrixText函数调用。问题在于“MOut = MatrixMult(M1,M2)”行。
当我编译模块时,该行中的“M1”突出显示,消息为“编译错误:类型不匹配:数组或用户定义的类型”。拜托,有人可以帮帮我吗?
Option Compare Database
Option Explicit
Public Function MatrixText() As Double()
Dim M1(), M2(), MOut() As Double
Dim Row1, Col1, Row2, Col2, Iter1, Iter2 As Integer
Rem
Row1 = 5
Col1 = 16
Row2 = 16
Col2 = 5
ReDim MOut(1 To Row1, 1 To Col2)
ReDim M1(1 To Row1, 1 To Col1)
ReDim M2(1 To Row2, 1 To Col2)
Rem
For Iter1 = 1 To Row1
For Iter2 = 1 To Col1
M1(Iter1, Iter2) = Rnd
M2(Iter2, Iter1) = Rnd
Next Iter2
Next Iter1
MOut = MatrixMult(M1, M2)
MatrixText = MOut
End Function
Public Function MatrixMult(ByRef mA() As Double, ByRef mB() As Double) As Double()
Dim ARow, ACol, BRow, Bcol, Iter1, Iter2, Iter3 As Integer
Dim MOutput() As Double
Rem
ARow = UBound(mA, 1)
ACol = UBound(mA, 2)
BRow = UBound(mB, 1)
Bcol = UBound(mB, 2)
If ACol = BRow Then
ReDim MOutput(1 To ARow, 1 To Bcol)
For Iter1 = 1 To ARow
For Iter2 = 1 To Bcol
For Iter3 = 1 To ACol
MOutput(Iter1, Iter2) = MOutput(Iter1, Iter2) + mA(Iter1, Iter3) * mB(Iter3, Iter2)
Next Iter3
Next Iter2
Next Iter1
MatrixMult = MOutput
Else
Rem the size of mA and mB do not match !!!!!!!!!!!!!!!
Rem MatrixMult() = 0
End If
End Function
答案 0 :(得分:1)
此行不符合您的预期:
Dim M1(), M2(), MOut() As Double
事实上确实如此:
Dim M1() As Variant, M2() As Variant, MOut() As Double
您必须将数据类型添加到每个变量。