如所写,您的函数仅接受两个范围作为参数。
为了允许在函数中使用可变数量的范围,您需要在参数列表中声明一个 ParamArray 变体数组。然后,您可以依次处理数组中的每个范围。
例如,
Function myAdd(Arg1 As Range, ParamArray Args2() As Variant) As Double
Dim elem As Variant
Dim i As Long
For Each elem In Arg1
myAdd = myAdd + elem.Value
Next elem
For i = LBound(Args2) To UBound(Args2)
For Each elem In Args2(i)
myAdd = myAdd + elem.Value
Next elem
Next i
End Function
然后可以在工作表中使用此函数来添加多个范围。
对于您的函数,有一个问题是可以传递给函数的范围(或单元格)是“会话”,哪些是“客户”。
最容易处理的情况是,如果您决定第一个范围是 Sessions,而任何后续范围都是客户。
Function calculateIt(Sessions As Range, ParamArray Customers() As Variant) As Double
'This function accepts a single Sessions range and one or more Customers
'ranges
Dim i As Long
Dim sessElem As Variant
Dim custElem As Variant
For Each sessElem In Sessions
'do something with sessElem.Value, the value of each
'cell in the single range Sessions
Debug.Print "sessElem: " & sessElem.Value
Next sessElem
'loop through each of the one or more ranges in Customers()
For i = LBound(Customers) To UBound(Customers)
'loop through the cells in the range Customers(i)
For Each custElem In Customers(i)
'do something with custElem.Value, the value of
'each cell in the range Customers(i)
Debug.Print "custElem: " & custElem.Value
Next custElem
Next i
End Function
如果您想包含任意数量的 Sessions 范围和任意数量的 Customers 范围,那么您将必须包含一个参数来告诉函数,以便它可以将 Sessions 范围与 Customers 范围分开。
该参数可以设置为函数的第一个数字参数,该参数将标识以下参数中有多少是 Sessions 范围,其余参数隐式为客户范围。该函数的签名将是:
Function calculateIt(numOfSessionRanges, ParamAray Args() As Variant)
或者它可能是一个“守卫”参数,将会话范围与客户范围分开。然后,您的代码必须测试每个参数以查看它是否是守卫。该函数如下所示:
Function calculateIt(ParamArray Args() As Variant)
也许有这样的电话:
calculateIt(sessRange1,sessRange2,...,"|",custRange1,custRange2,...)
那么程序逻辑可能是这样的:
Function calculateIt(ParamArray Args() As Variant) As Double
...
'loop through Args
IsSessionArg = True
For i = lbound(Args) to UBound(Args)
'only need to check for the type of the argument
If TypeName(Args(i)) = "String" Then
IsSessionArg = False
ElseIf IsSessionArg Then
'process Args(i) as Session range
Else
'process Args(i) as Customer range
End if
Next i
calculateIt = <somevalue>
End Function