barlop
barlop

Reputation: 13743

In Excel VBA, how do I write a function that can work in an array formula?

In Excel VBA, I know I can use an array formula on multiple cells, by selecting a range of cells of Col C, and doing =A1:10*B1:B10 Ctrl-shift-enter.

But suppose instead of the multiplication operator, I want it to be my mymult.

How would I write the mymult function?

Function MyMult(a As Integer, b As Integer)
  MyMult = a * b
End Function

What I have isn't working

enter image description here

Upvotes: 2

Views: 306

Answers (1)

Florent B.
Florent B.

Reputation: 42518

Declare the arguments as variant. Then use Application.Caller.HasArray to check if the UDF is used as an array formula:

Public Function MyMult(a, b)
  If Application.Caller.HasArray Then
    Dim valsA(), valsB(), r&
    valsA = a.Value
    valsB = b.Value

    For r = LBound(valsA) To UBound(valsA)
      valsB(r, 1) = valsA(r, 1) * valsB(r, 1)
    Next

    MyMult = valsB
  Else
    MyMult = a * b
  End If
End Function

Note that you need to select C1:C3 before pressing CTRL + SHIFT + ENTER.

Upvotes: 5

Related Questions