简体   繁体   中英

Apply a scalar VBA function to each cell in an array

I have a VBA function that performs a numerical computation, eg:

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. For example, in cell B1 I would like to enter:

=SUM(MyFunc(A1#, 2))

with the meaning of (if A1# is the dynamic array 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?

If you want to pass a spill-down to a UDF, you can pass it as a 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:

=myfunc(A1#,8)

As you see, it spills across, and in C2 we put:

=SUM(myfunc(A1#,8))

在此处输入图像描述

As you see, we give it a Range ; it returns an Array which SUM() can easily handle.

You could use Evaluate in combination with range:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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