我正在尝试在VBA中使用Excel内置函数SumProduct,但不断收到错误。代码段如下所示
Dim X As Variant
'x is input value, given as Range
X = x.Value
Dim Y() As Double
ReDim Y(1 To N)
'filling Y with whatever values
Dim i As Long
For i = 1 To UBound(Y)
Y(i) = 2
next i
Result = WorksheetFunction.SumProduct(X,Y)
但是,这段代码会返回 #Value ,我想这是因为X是Variant而Y是Double类型(所以类型不匹配)。
有没有办法将此变体转换为double(数组)?我已经尝试将X声明为Double,然后循环遍历输入范围本身,但不知道如何“访问”输入范围中的每个元素。
有什么建议吗?
由于
答案 0 :(得分:2)
Y需要是2D变体数组。 (我建议你直接用所需的形式构建Y.)试试这个:
Function Result()
Dim X As Variant
'rng is input value, given as Range. You can't have x and X in VBA due to case-insensitivity
X = rng.Value
N = UBound(X, 1) - LBound(X, 1) + 1 'Should really declare N before using it
Dim Y As Variant 'Changed type here
ReDim Y(1 To N, 1 To 1) 'We need a 2D variant
'filling Y with whatever values
Dim i As Long
For i = 1 To UBound(Y)
Y(i, 1) = 2
Next i
Result = WorksheetFunction.SumProduct(X, Y)
End Function