VBA:将1x1matrix转换为整数
我有一个来自以下的1×1数组:
Dim wbottom As Variant wbottom = WorksheetFunction.MMult(WorksheetFunction.transpose(e), wtop)
我想获得数组中的数字。 wbottom(0,0)和wbottom(1,1)给出“下标超出范围”。 当我试图用MsgBox打印出数字时,ReDim-ming什么都不给。 我该如何解决?
如果得到的matrix是1×1,则得到的数组是1维的,唯一有效的下标是1.见下文,其中A1:E1
和A3:A7
包含1×5和5x1matrix的值(以便乘法结果为1×1matrix):
Sub mmultTest() Dim v As Variant v = WorksheetFunction.MMult(Range("A1:E1"), Range("A3:A7")) Debug.Print LBound(v) Debug.Print UBound(v) Debug.Print v(1) End Sub
输出如下:
1 1 55
你可以试试
wbottom = WorksheetFunction.SumProduct(e, wtop)
将一列转换成一行,然后乘以一列得到一个1x1matrix给你一个1x1matrix,其唯一元素是两列的点积。 SumProduct
函数SumProduct
是点积,不需要转置然后解压值。
为了testing这个,我设置了一个工作表
AB ------ 1 4 2 5 3 6
然后运行以下代码:
Sub test() Dim A As Range, B As Range, product As Variant Set A = Range("A1:A3") Set B = Range("B1:B3") With Application.WorksheetFunction product = .MMult(.Transpose(A), B) 'what you have Debug.Print TypeName(product) Debug.Print product(1) product = .SumProduct(A, B) Debug.Print TypeName(product) Debug.Print product End With End Sub
与结果输出:
Variant() 32 Double 32