16

我正在获取一组单元格并在下面的函数中对它们进行一些计算。

如果我传递一个范围(带:符号)作为第一个参数,它会起作用,但如果我选择一些单元格作为它的范围(A1, A3, B6, B9),它会失败。它只是在逗号之前获取第一个单元格作为第一个参数。但我想要整个细胞。

我能做些什么?(除了使用字符串传递范围)

Function calculateIt(Sessions As Range, Customers As Range) As Single
    ' calculate them...
End Function

还有一件事:是否可以将一组范围作为参数传递?如何?

4

4 回答 4

30

如所写,您的函数仅接受两个范围作为参数。

为了允许在函数中使用可变数量的范围,您需要在参数列表中声明一个 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

然后可以在工作表中使用此函数来添加多个范围。

myAdd 用法

对于您的函数,有一个问题是可以传递给函数的范围(或单元格)是“会话”,哪些是“客户”。

最容易处理的情况是,如果您决定第一个范围是 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
于 2013-08-11T03:23:03.583 回答
11

还有另一种将多个范围传递给函数的方法,我认为这对用户来说感觉更干净。在电子表格中调用函数时,将每组范围括在括号中,例如:calculateIt( (A1,A3), (B6,B9) )

上述调用假设您的两个 Session 位于 A1 和 A3 中,而您的两个客户位于 B6 和 B9 中。

为了使这项工作,您的函数需要遍历Areas输入范围中的每个。例如:

Function calculateIt(Sessions As Range, Customers As Range) As Single

    ' check we passed the same number of areas
    If (Sessions.Areas.Count <> Customers.Areas.Count) Then
        calculateIt = CVErr(xlErrNA)
        Exit Function
    End If

    Dim mySession, myCustomers As Range

    ' run through each area and calculate
    For a = 1 To Sessions.Areas.Count

        Set mySession = Sessions.Areas(a)
        Set myCustomers = Customers.Areas(a)

        ' calculate them...
    Next a

End Function

好消息是,如果您将两个输入都设置为连续范围,则可以像调用普通函数一样调用此函数,例如calculateIt(A1:A3, B6:B9).

希望有帮助:)

于 2015-07-09T09:09:44.183 回答
0

由于我是 vba 的初学者,我愿意深入了解 vba,了解所有 excel 内置函数如何从那里工作。

所以在上面的问题上我已经付出了我的基本努力。

Function multi_add(a As Range, ParamArray b() As Variant) As Double

    Dim ele As Variant

    Dim i As Long

    For Each ele In a
        multi_add = a + ele.Value **- a**
    Next ele

    For i = LBound(b) To UBound(b)
        For Each ele In b(i)
            multi_add = multi_add + ele.Value
        Next ele
    Next i

End Function

- a:对于上面的代码,这是减去的,导致计数加倍,所以你添加的值将添加第一个值两次。

于 2019-04-04T05:28:41.683 回答
0

我写了一个更好的函数,灵感来自@Ian S。

' Similar to SUMPRODUCT, but it works with non consecutive cells also, multiplying the price, in the first column, with
' the correspondent rate exchange of the second column.
' Usage:
' SUMCURRENCIES(D6:D10,E6:E10) will multiply D6 by E6, D7 by E7, and so on, finally sum all the multiplications.
' SUMCURRENCIES((D113,D117),(E113,E117)) instead will multiply D113 by E113 first, and then will add the result of D117 * E117.
Function SUMCURRENCIES(Prices As Range, ExchangeRates As Range) As Double

    ' Check if we passed the same number of areas.
    If (Prices.Areas.Count <> ExchangeRates.Areas.Count) Then
        SUMCURRENCIES = CVErr(xlErrNA)
        Exit Function
    End If

    Dim Price, ExchangeRate As Range
    Dim AreasCount, PricesCount As Integer
    
    Total = 0
    
    ' Runs through each area and multiple the value for the exchange rate.
    AreasCount = Prices.Areas.Count
    For i = 1 To AreasCount
        Set Price = Prices.Areas(i)
        Set ExchangeRate = ExchangeRates.Areas(i)
    
        If VarType(Price.Value2) = VBA.VbVarType.vbDouble Then
            Total = Price * ExchangeRate + Total
        Else
            PricesCount = Prices.Count
            For j = 1 To PricesCount
                Total = Prices(j).Value * ExchangeRates(j).Value + Total
            Next j
        End If
    Next i
    
    SUMCURRENCIES = Total
End Function
于 2021-09-22T18:32:28.750 回答