简体   繁体   English

将标量 VBA function 应用于数组中的每个单元格

[英]Apply a scalar VBA function to each cell in an array

I have a VBA function that performs a numerical computation, eg:我有一个 VBA function 执行数值计算,例如:

Function MyFunc(ByVal x As Double, ByVal a As Double) As Double
    MyFunc = x + a
End Function

I want to use a worksheet formula to apply this function to an array and sum the values.我想使用工作表公式将此 function 应用于数组并对值求和。 For example, in cell B1 I would like to enter:例如,在单元格B1中,我想输入:

=SUM(MyFunc(A1#, 2))

with the meaning of (if A1# is the dynamic array A1:A3 ):含义为(如果A1#是动态数组A1:A3 ):

=SUM(MyFunc(A1,2), MyFunc(A2,2), MyFunc(A3,2))

Can I do this without having to explicitly write the array loop in my VBA function?我可以这样做而不必在我的 VBA function 中显式编写数组循环吗?

If you want to pass a spill-down to a UDF, you can pass it as a Range :如果要将溢出传递给 UDF,可以将其作为Range传递:

Function MyFunc(x As Range, a As Double)
    Dim L As Long, U As Long, arr, i As Long
    Dim r As Range
    L = 1
    U = x.Count
    ReDim arr(L To U)

    For i = L To U
        arr(i) = x(i) + a
    Next i
    MyFunc = arr
End Function

So in the worksheet in cell C1 we put:因此,在单元格C1的工作表中,我们输入:

=myfunc(A1#,8)

As you see, it spills across, and in C2 we put:如您所见,它溢出了,在C2中我们输入:

=SUM(myfunc(A1#,8))

在此处输入图像描述

As you see, we give it a Range ;如您所见,我们给它一个Range it returns an Array which SUM() can easily handle.它返回一个SUM()可以轻松处理的Array

You could use Evaluate in combination with range:您可以将 Evaluate 与范围结合使用:

Function MyFunc1(x As Range, ByVal a As Double) As Variant
    MyFunc1 = Application.Evaluate("(" & x.Address & "+" & a & ")")
End Function

And directly summed:并直接总结:

Function MyFunc1(x As Range, ByVal a As Double) As Variant
    MyFunc1 = Application.Evaluate("SUM(" & x.Address & "+" & a & ")")
End Function

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

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