具有无限参数的UDF

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

函数的参数是按照上升精度的顺序写的。

这是一个例子:

+---+-----------------+---------------------+ | | 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写在公式列表中的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好”

如果最佳值总是在Range的底部,但是您不确定正在search的列的行数,则可以使用:

 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 

根据你所显示的例子,这不适合你吗?

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

那你可以这样试试

 =get_best(B3:B5) 

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

你可以使用一个参数来添加你想要的范围:

 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 

您可以避免以这种方式传递任何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