2016-09-11 67 views
1

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

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 

这是我看到:

enter image description here

我想在第二排,而不是包含函数的输出。在这种情况下,那将是0.4, 0.4, 0.4, 0.4

不幸的是,我得到一个#VALUE!错误,我不知道如何调试。

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

+0

如果您想要将一系列单元格传递给该函数,则需要将传递的参数声明为Range或Variant。 – YowE3K

+0

您的'ReDim输出(1,coeffs)'语句应该是'ReDim output(1,columns)'。 – YowE3K

+0

@ YowE3K,谢谢,编辑 – user357269

回答

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)} 

从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 
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 array,只是一个包含Range对象的Variant。然后在我的后续测试代码中,我成功地访问了像x(i)这样的东西,但那不是返回Variant数组的第i个元素 - 它只是返回Range的第i个单元格。

+0

感谢您清理我的代码。你测试了这个顺便说一句吗?我仍然得到相同的错误 – user357269

+0

我测试了类似的东西 - 我可能犯了一个错误,将它“翻译”回你的变量等。给我一秒钟,我会检查。 – YowE3K

+0

叹息 - 这是UBound导致的问题 - 我要删除我的回答 – YowE3K

0

如果您想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然后拖动它直到G2。

我觉得一个UDF只能值添加到它的呼叫单元只有

+0

我最初认为UDF也只能对单个单元格起作用,但如果它可以实际输出到多个单元格作为数组公式输入。 – YowE3K

+0

你是对的。我从来没有听说过,直到现在。 – suisgrand

+0

我学会了更多的东西,只是试图回答SO问题,而不是我在使用Excel的年份和年份。 – YowE3K