我有一个函数,它接受一个数组并输出另一个数组。它的内部结构比下面的玩具示例更复杂。
<li>Blank Entry</li>
这就是我所看到的:
我希望第二行包含函数的输出。在这种情况下,那将是<li>
。
不幸的是,我收到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!
- Ctrl
)。以类似的方式,输入是否可能来自范围或数组?
答案 0 :(得分:4)
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
答案 1 :(得分:0)
将传递的参数更改为Range
变量。
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数组传递给函数,但是因为我使用
标题进行了测试而感到困惑Public Function divide_by_2_5(ByRef x As Variant) As Double()
而不是
Public Function divide_by_2_5(ByRef x() As Variant) As Double()
所以我测试的版本不接受Variant 数组,只是一个包含Range对象的Variant。然后在我后来的测试代码中,我成功地访问了x(i)
之类的东西,但是没有返回Variant数组的第i个元素 - 它只是返回了Range的第i个单元格。 / p>
答案 2 :(得分:0)
如果您希望D2,E2,F2,G2等于0.4,则需要将一个单值传递给您的函数,例如:
Thread
在D2上进行以下调用:Public Function divide_by_2_5 (ByRef coeff As Range) As Double
divide_by_2_5 = coeff.Value / 2.5
End Function
,然后将其拖动到G2。
我认为UDF只能为其调用单元格添加一个值