简体   繁体   English

Excel UDF接受范围和数组作为参数,例如“ SUM”

[英]Excel UDF that accepts both Range and Array as Parameter like 'SUM'

I an writing a UDF that needs to accept both Arrays and Ranges. 我正在编写需要同时接受数组和范围的UDF。

Usually declaring parameter as variant would work but a Range is an object so this no longer applies. 通常将参数声明为variant会起作用,但是Range是一个对象,因此不再适用。 That being said bellow I pasted code that only works when passing an array. 话虽如此,但我粘贴了仅在传递数组时有效的代码。
Here is theorethical example, based on SUM : 这是基于SUM理论示例:

Function TSUM(numbers() As Variant) As Variant
    Dim i As Integer
    For i = 1 To UBound(numbers, 1)
        TSUM = TSUM + numbers(i)
    Next i
End Function

=TSUM({1,1}) Returns 2 = TSUM({1,1})返回2
=TSUM(A1:B1) Returns #VALUE! = TSUM(A1:B1)返回#VALUE!

So how can I fix above example to accept Ranges as well? 那么,如何修改上面的示例以接受Ranges?

If you are content to sum the array/range item by item, I would just change to using a For Each loop that works well for either Ranges or Arrays. 如果您愿意逐项汇总数组/范围,我将改为使用适用于Ranges或Arrays的For Each循环。

Here is that version 这是那个版本

Public Function TSUM(numbers As Variant) As Variant
    Dim i As Variant

    For Each i In numbers
        TSUM = TSUM + i
    Next i
End Function

If you generally want to work a function based on the type of the argument, you can use TypeName() and switching logic. 如果通常要根据参数的类型来使用函数,则可以使用TypeName()和切换逻辑。 Here is you function with that approach. 这是您使用该方法的功能。 I called it TSUM2 for uniqueness. 我称它为TSUM2是唯一性。

Public Function TSUM2(numbers As Variant) As Variant
    Dim i As Integer

    If TypeName(numbers) = "Range" Then
        TSUM2 = Application.WorksheetFunction.Sum(numbers)
    Else
        For i = 1 To UBound(numbers, 1)
            TSUM2 = TSUM2 + numbers(i)
        Next i
    End If
End Function

Note in both examples, I removed the parentheses from the numbers parameters (was numbers() as Variant before). 请注意,在两个示例中,我都从数字参数中删除了括号(在以前, numbers() as Variant )。 This allows it to accept Range inputs. 这使其可以接受范围输入。

If you take the second approach, be sure to debug and verify the TypeNames that could come through. 如果采用第二种方法,请确保调试并验证可能通过的TypeName。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM