4

我正在尝试在 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 类型(所以类型不匹配)。

有没有办法将此变体转换为双(数组)?我尝试将 X 声明为 Double ,然后遍历输入范围本身,但不知道如何“访问”输入范围中的每个元素。

有什么建议么?

谢谢

4

1 回答 1

2

Y will need to be a 2D variant array. (I suggest you construct Y in the required form directly.) Try this:

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
于 2013-05-17T12:48:31.223 回答