接受一个范围作为数组参数

我有一个函数,它接受一个数组并输出另一个数组。 它的内部比下面的玩具例子更复杂。

Public Function divide_by_2_5(ByRef coeffs() As Double) As Double() Dim Columns As Integer Columns = UBound(coeffs, 2) - LBound(coeffs, 2) + 1 Dim output() As Double ReDim output(1 To 1, 1 To Columns) Dim i As Integer For i = 1 To Columns output(1, i) = coeffs(1, i) / 2.5 Next i divide_by_2_5 = output End Function 

以下是我所看到的:

在这里输入图像说明

我想第二行代替包含函数的输出。 在这种情况下,这将是0.4, 0.4, 0.4, 0.4

不幸的是,我得到了#VALUE! 错误,我不知道如何debugging。

一些澄清:显然有可能有相同的函数返回一个数组或写入电子表格(使用CtrlShiftEnter )。 以类似的方式,input是来自范围还是数组?

 Public Function divide_by_2_5(coeffs As Variant) As Double() Dim v() As Variant If TypeName(coeffs) = "Range" Then v = coeffs.Value Else v = coeffs End If Dim output() As Double ReDim output(LBound(v, 1) To UBound(v, 1), LBound(v, 2) To UBound(v, 2)) Dim r As Long Dim c As Long For r = LBound(v, 1) To UBound(v, 1) For c = LBound(v, 2) To UBound(v, 2) output(r, c) = v(r, c) / 2.5 Next Next divide_by_2_5 = output End Function 

把这个称为UDF的例子是:

 {=divide_by_2_5(C2:F2)} 

使用Range从VBA调用这个例子可能是:

 Dim v As Variant v = divide_by_2_5(Worksheets("Sheet1").Range("C2:F2")) 

使用数组从VBA调用这个示例可能是:

 Sub test() Dim x(1, 4) As Variant Dim v As Variant x(1, 1) = 6 x(1, 2) = 7 x(1, 3) = 8 x(1, 4) = 9 v = divide_by_2_5(x) MsgBox v(1, 3) End Sub 

如果你想D2,E2,F2,G2等于0.4,你需要传递一个单一的值给你的函数,如:

 Public Function divide_by_2_5 (ByRef coeff As Range) As Double divide_by_2_5 = coeff.Value / 2.5 End Function 

进行以下调用: =divide_by_2_5(D1) D2上的=divide_by_2_5(D1) ,然后拖动到G2。

我认为一个UDF只能给它的调用单元添加一个值

将传递的参数更改为Rangevariables。

 Public Function divide_by_2_5(ByRef inputRange As Range) As Double() Dim output() As Double ReDim output(1 To inputRange.Rows.Count, 1 To inputRange.Columns.Count) As Double Dim r As Long Dim c As Long For r = 1 To inputRange.Rows.Count For c = 1 To inputRange.Columns.Count output(r, c) = inputRange.Cells(r, c).Value / 2.5 Next Next divide_by_2_5 = output End Function 

注:我原本以为我可以只是有一个Variant数组传递到函数,但是很困惑,因为我testing使用头

 Public Function divide_by_2_5(ByRef x As Variant) As Double() 

代替

 Public Function divide_by_2_5(ByRef x() As Variant) As Double() 

所以我testing的版本不接受一个Variant 数组 ,只是一个包含Range对象的Variant。 然后在我的后续testing代码中,我成功地访问了像x(i)这样的东西,但是没有返回Variant数组的第i个元素 – 它只是返回Range的第i个单元格。