具有无限参数的UDF

时间:2017-04-04 08:07:14

标签: excel vba excel-vba user-defined-functions excel-udf

我正在编写一个用户定义函数(UDF),它将一些单元格作为参数。 这些单元格包含相同的数据但具有不同的精度级别;该功能显示最佳精度。

函数的参数按递增精度的顺序写出。

这是一个例子:

+---+-----------------+---------------------+
|   |        A        |          B          |
+---+-----------------+---------------------+
| 1 | Best            | =get_best(B5;B4;B3) |
| 2 |                 |                     |
| 3 | provisional     | 1                   |
| 4 | definitive      | 2                   |
| 5 | etched in stone | 12                  |
+---+-----------------+---------------------+

函数显示12,因为单元格B5中的信息具有比B4和B3更好的值。因此,B5在公式argoument中的B4和B3之前写入。

我的UDF的代码如下:

Public Function get_best(r1 As Range, r2 As Range, r3 As Range) As Variant

    get_best = ""

    If r3.Value <> "" Then get_best = r3.Value Else
    If r2.Value <> "" Then get_best = r2.Value Else
    If r1.Value <> "" Then get_best = r1.Value

End Function

有效!但我想编辑它,所以它可能需要像=get_best(B7;B6;B5;B4;B3)这样的无限注释。 我怎么能这样做?

有用的评论: “单元格B5具有比B4和B3更好的值”意味着,例如,在B3中,您具有您在12个月前计算的预测值。在单元格B5中,您具有有效和测量值。所以,当你有B5时,你不再需要B3因为“B5比B3好”

4 个答案:

答案 0 :(得分:1)

根据您展示的示例,这不适合您吗?

Public Function get_best(ByVal Rng As Range) As Variant
    get_best = Application.Max(Rng)
End Function

然后你可以这样试试......

=get_best(B3:B5)

答案 1 :(得分:1)

你可以避免以这种方式传递任何range参数

Public Function get_best() As Variant
    get_best = Cells(Rows.Count, Application.Caller.Column).End(xlUp).Value
End Function

如果你必须指定一个(连续的)范围,你可以按如下方式行事:

Public Function get_best(r As Range) As Variant
    With r
        If WorksheetFunction.CountA(.Cells) > 0 Then get_best = .Cells(.Rows.Count + 1).End(xlUp).Value
    End With
End Function

答案 2 :(得分:1)

我不明白你的意思“小区B5的价值比B4和B3更好”。您的代码会查看哪个单元格包含从参数中的最后一个开始的值。

您可以使用paramarray添加任意数量的范围:

Public Function get_best(ParamArray Ranges()) As Variant

    Dim x As Long

    For x = UBound(Ranges) To LBound(Ranges) Step -1
        If Ranges(x) <> "" Then
            get_best = Ranges(x).Value
            Exit For
        End If
    Next x

End Function

答案 3 :(得分:1)

如果 best 值始终位于Range的底部,但您不确定要搜索的列中的行数,则可以使用:

Public Function get_best(rng As Range) As Variant

    Dim lngLastRow As Long

    lngLastRow = rng.Parent.Cells(rng.Parent.Rows.Count, rng.Column).End(xlUp).Row
    get_best = rng.Parent.Cells(lngLastRow, rng.Column).Value

End Function