如何创建函数以接受不定数量的参数,但要成对使用?

时间:2018-09-18 10:08:10

标签: excel vba excel-vba

我正在考虑创建类似于 IFS 公式的VBA函数,其中您可以传递不确定数量的参数,但始终需要第二个参数。

=IFS(logical_test1, value_if_true1, [logical_test2, value_if_true2], ...)

要求是比较某些值,如果所有值都相同,则输出True,否则输出False。

假设我们有这张桌子。

Item ID | Price | Description
1001    | 10.00 | Item A
1002    | 10.00 | Item A
1003    | 25.00 | Item A
1004    | 10.00 | Item B

如果我需要在某些项目上做一些事情,我会简单地调用如下函数:

Function(criteria1, value1, criteria2, value2, ...)

' Mark items with Price = 10.00 and Description = Item A
Dim IsAdd As Boolean: IsAdd = FnCheckData(strCriteria2, "10.00", strCriteria3, "Item A")

' Mark items with Item ID = 1002
Dim IsAdd As Boolean: IsAdd = FnCheckData(strCriteria1, "1002")

' Mark items with Item ID = 1003, Price = 25.00 and Description = Item A
Dim IsAdd As Boolean: IsAdd = FnCheckData(strCriteria1, "1003", strCriteria2, "25.00", strCriteria3, "Item A")

' This would error out since the second argument is not supplied
Dim IsAdd As Boolean: IsAdd = FnCheckData(strCriteria1)

这可能吗?如果是这样,怎么办?预先感谢!

1 个答案:

答案 0 :(得分:3)

您的功能可能看起来像这样

Function NeedEvenNumber(ParamArray vStrings()) As Boolean

    On Error GoTo EH

    If IsMissing(vStrings) Then
        Debug.Print "Nothing passed"
    End If

    If (UBound(vStrings) Mod 2) - 1 = 0 Then
        Debug.Print "Correct number of params passed"
    End If

    Exit Function

EH:
    MsgBox "Something went wrong", vbOKOnly, "Error"


End Function