This is the first time for me to write VBA code involving arrays. I have a problem that MatrixMult function (which calculates M1 and M2 matrices) can not be called from MatrixText function. The problem is in "MOut = MatrixMult(M1, M2)" line.
When I compile the module, the "M1" in that line is highlighted and the message is, "Compile error: Type mismatch: array or user-defined type expected." Please, anybody can help me?
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
This line does not do what you expect:
Dim M1(), M2(), MOut() As Double
In fact it does:
Dim M1() As Variant, M2() As Variant, MOut() As Double
You must add the data type to each variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.