[英]Type mimsatch when assigning result of MMult to an array variable
Apologies for the newbie question, but I couldn't find an answer when searching. 为新手问题道歉,但我在搜索时找不到答案。
I'm fairly new to matrix manipulation in VBA. 我对VBA中的矩阵操作相当新。 I keep on getting a type mismatch with the following code. 我继续使用以下代码获得类型不匹配。
Sub matrixtest()
Dim matrix1() As Integer
Dim matrix2() As Integer
Dim matrix3() As Integer
Dim i, j, k As Integer
'populate matrix1
ReDim matrix1(3, 3)
For j = 1 To 3
For i = 1 To 3
matrix1(i, j) = Range("C5").Offset(i - 1, j - 1)
Next i
Next j
'populate matrix2
ReDim matrix2(3, 3)
For j = 1 To 3
For i = 1 To 3
matrix2(i, j) = Range("G5").Offset(i - 1, j - 1)
Next i
Next j
ReDim matrix3(3, 3)
matrix3 = Application.WorksheetFunction.MMult(matrix1, matrix2)
End Sub
If you replace the line 如果你更换线
matrix3 = Application.WorksheetFunction.MMult(matrix1, matrix2)
By 通过
Debug.Print TypeName(matrix3 = Application.WorksheetFunction.MMult(matrix1, matrix2))
The output is: 输出是:
Variant()
Which can't be assigned to an Integer()
. 哪个不能分配给Integer()
。
I would recommend replacing 我建议更换
Dim matrix1() As Integer
Dim matrix2() As Integer
Dim matrix3() As Integer
Dim i, j, k As Integer
by 通过
Dim matrix1, matrix2, matrix3 As Variant 'note lack of ()
Dim i, j, k As Long 'Integer is borderline obsolete in VBA
Variants do a nice job of holding and passing arrays and tend to handle any needed type conversions automatically. 变量可以很好地保存和传递数组,并且可以自动处理任何所需的类型转换。 When dealing with arrays in VBA, I tend to use them almost exclusively. 在VBA中处理数组时,我倾向于几乎完全使用它们。 For one thing, it makes it easy to load arrays from ranges. 首先,它可以轻松地从范围加载数组。
Just use ReDim
to make the variants hold arrays: 只需使用ReDim
使变体保持数组:
ReDim matrix1(1 to 3, 1 to 3) 'doesn't hurt to be explicit about lower bounds
ReDim matrix2(1 to 3, 1 to 3)
'load arrays...
'no need to redim matrix3, just:
matrix3 = Application.WorksheetFunction.MMult(matrix1, matrix2)
There is an even shorter way of doing what you are trying to do: 做你想做的事情有一个更短的方式:
matrix1 = Range("C5:E7").Value
matrix2 = Range("G5:I7").Value
matrix3 = Application.WorksheetFunction.MMult(matrix1, matrix2)
In the above code you don't need to use any preliminary ReDim
. 在上面的代码中,您不需要使用任何初步的ReDim
。 When you want to load the values of a rectangular range into a variant in VBA, you don't need to loop, which is needlessly slow. 当您想要将矩形范围的值加载到VBA中的变体中时,您不需要循环,这是不必要的慢。 Just assign the values in one fell swoop. 只需一举分配值即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.