vba - 具有无限参数的 UDF

标签 vba excel 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 具有更好的值(value)。由于这个原因,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 的底部但是您不确定要搜索的列中的行数,您可以使用它:

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

关于vba - 具有无限参数的 UDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43201632/

相关文章:

shell - 在 VBA shell 命令中使用 AppActivate 和 Sendkeys

excel - Office 2016 中的 MailItem.GetInspector.WordEditor 生成应用程序定义或对象定义的错误

Excel 列出工作表中的命名范围并获取值

vba - 读取 .txt 文件并将某些数据复制/粘贴到满足某些条件的 Excel

excel - 为什么单字母 UDF 名称不能使用 C 或 R?

ms-access - 错误代码 3021 bof 或 eof 为真或当前记录已被删除

excel - 为 XLS、XLSX 和 XLSM 编写的宏之间是否存在兼容性问题?

vba - Outlook 2013 VBA 宏未在新邮件上运行

sql - 如何扩展sql表?

swift - Swift 中的嵌套函数重载