转换范围并从UDF返回

时间:2017-05-26 12:07:00

标签: excel vba excel-vba udf

我正在尝试编写一个非常简单的UDF,它将获取输入范围并返回另一个范围。输出范围的每个单元格应该等于输入范围单元格加1.这是我所拥有的

Public Function Addone(rng As Range) As Range

    Dim i As Integer, N As Integer
    N = rng.Count

    For i = 1 To N
        Addone.cells(1,i) = rng.cells(1,i) + 1
    Next i

End Function

假设范围" A1:C1"包含数字1,2,3。然后我转到工作表,选择一系列单元格(输出范围," A2:C2"),然后输入Addone(A1:C1)并按Ctrl + Shift + Enter。但是,输出单元格填充#VALUE

我检查了其他答案herehere,但无法使其适用于我的案例。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

您无法将输出定义为范围并在单元格中对其进行评估 必须将输出类型更改为double数组。内部函数定义一个临时数组,重新定义其大小基础N,然后分配给返回的数组。以下应该做。如果这解决了,请告诉我。

Public Function Addone2(rng As Range) As Double()

    Dim temp() As Double
    Dim i As Integer, N As Integer
    N = rng.Count
    ReDim temp(1 To N) As Double
    For i = 1 To N
        temp(i) = rng.Cells(1, i) + 1
    Next i
    Addone2 = temp
End Function