处理UDF中可选参数的最佳方法?

时间:2018-08-07 14:13:00

标签: vba excel-vba optional-parameters

我有类似的功能

Public Function func(ByRef mandatory_arg1 As Range, ByRef mandatory_arg2 As Range, _
                     Optional ByRef optional_Arg1 As Range, Optional ByRef optional_arg2 As Range, _
                     Optional ByRef optional_arg3 As Range, Optional ByRef optional_arg4 As Range, _
                     Optional ByRef optional_arg5 As Range, Optional ByRef optional_arg6 As Range) As Double
    func = WorksheetFunction.SumIfs(mandatory_arg1, ...) / WorksheetFunction.SumIfs(mandatory_arg2, ...)
End Function

处理缺少参数的情况的最佳方法是什么?正在使用类似于

的If-Else结构
if IsMissing(optional_Arg1) or IsMissing(optional_Arg2) Then
    ' ...
EndIf

唯一的方法?还是WorksheetFunction.SumIfs(...)会忽略Nothing的参数?

1 个答案:

答案 0 :(得分:1)

使用ParamArray并遍历所传递的范围。

Public Function func(ByRef mandatory_arg1 As Range, ByRef mandatory_arg2 As Range, _
                     ParamArray rngs()) As Double
    dim i as long

    If IsMissing(rngs) Then
        'no optional ranges
    End If


    For i = LBound(rngs) To UBound(rngs)
        'process rngs(i)
    Next i

end function