简体   繁体   English

VBA Excel 将 Arguments 的变量 # 传递给带有 ParamArray 的内置函数

[英]VBA Excel Passing Variable # of Arguments to Built-in Functions with ParamArray

I want to create a VBA function which combines several built-in Excel functions, each of which can take one or more cell ranges.我想创建一个 VBA function ,它结合了几个内置的 Excel 函数,每个函数都可以采用一个或多个单元格范围。 The number of ranges entered must be flexible, and these arguments will be entered in the worksheet.输入的范围数量必须灵活,这些 arguments 将在工作表中输入。 This should be easiest using VBA's ParamArray, but I'm unsure how to pass each cell range into the built-in functions.使用 VBA 的 ParamArray 这应该是最简单的,但我不确定如何将每个单元格范围传递给内置函数。 Here's a simple example of what I've tried:这是我尝试过的一个简单示例:

Function Func1(ParamArray Ranges() As Variant)
    Func1 = Application.WorksheetFunction.Sum(Ranges)
End Function

This works for single cell arguments, but not ranges.这适用于单细胞 arguments,但不适用于范围。 For example, if cell A1 =1 and A2 =2, "=Func1(A1,A2)" returns 3, but =Func1(A1:A2) returns #VALUE!例如,如果单元格A1 =1 且A2 =2,“=Func1(A1,A2)”返回 3,但=Func1(A1:A2)返回#VALUE!

I thought of looping through each range in Ranges() , but I can't think of any way to enter the arguments into the built-in SUM function one at a time while looping.我想过循环遍历Ranges()中的每个范围,但我想不出任何方法可以在循环时一次将 arguments 输入到内置SUM function 中。

ps - in reality I'm calling about 10 different functions (not just sum, otherwise this would be trivial), each with the same set of ranges, and this code is meant to allow those to only be entered once per cell, rather than typed into each of the 10 functions. ps - 实际上我调用了大约 10 个不同的函数(不仅仅是求和,否则这将是微不足道的),每个函数都有相同的范围集,并且此代码旨在允许每个单元格仅输入一次,而不是输入 10 个函数中的每一个。

You need to iterate the array - for example:您需要迭代数组 - 例如:

Function Func1(ParamArray Ranges() As Variant)
    Dim n As Long
    For n = LBound(Ranges) To UBound(Ranges)
        Func1 = Func1 + Application.WorksheetFunction.Sum(Ranges(n))
    Next
End Function

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

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