2

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

8
  • 1
    What is your expected output? (1*2)*(1*3)*(1*4) = 24? Commented Sep 10, 2017 at 14:43
  • Your example is inadequate since the best way to fulfill the requirements would be to put =a1*b1 in C1 and then double-click the fill handle. Commented Sep 10, 2017 at 14:43
  • Also why are a and b declared as Integer when you are expecting to use them as Range? Commented Sep 10, 2017 at 15:22
  • There is also =SUMPRODUCT(A1:10,B1:B10) Commented Sep 10, 2017 at 15:29
  • @BruceWayne You ask if my expected result is that one number, the product of them all. No, it's not one number. I said this is an array formula on multiple cells. That's where you select multiple cells before doing ctrl-shift-enter Commented Sep 10, 2017 at 20:08

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh cool, I never knew of the HasArray thing. Nice thinking, I'll have to remember that.
Is there any way for an array formula to be aware of and respond to the specific row? So for example, for the multiply function to not just multiply them but to append to the result based on what row it is e.g. i.imgur.com/cITiW6Q.png
An array formula processes all the rows in a single call and returns the results in an array. So yes it's possible. In this example r is the index of the row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.