3

I have a VBA function that accepts arrays, it works great if I pass it a reference such as A1:A10. It does not accept a "formula" argument such as A1:A10+1 or A1:A10^2, the resulting cells contain #VALUE.

Many excel functions support this, such as linest(...) which i can write the following formula to get a forth order fit without having to manually list the four columns for the X argument.

     =LINEST( B1:B10, A1:A10^{1,2,3} )

My function declaration is:

     Function FFT(ByRef A) As Variant

I'm expecting Excel to evaluate the expression and pass the result into the function. Is this not possible with Excel VBA?

1 Answer 1

1

If you're calling your function from another VBA subroutine or function, Excel will not interpret the range calculation for you. You have to perform any data manipulations over the range area yourself before calling your function.

But as long as you're using the function as a UDF from a worksheet cell, Excel will interpret the range parameters as you describe them. The caveat when applying any calculations to the range is you must "tag" the cell formula to excel as an array formula by typing with control-shift-enter to complete the cell formula.

Consider this setup:

Option Explicit

Public Function CalculateThis(inRange) As Double
    Dim answer As Double
    answer = 0#
    CalculateThis = answer
End Function

enter image description here

The range parameter A1:E1 comes in as expected, a Variant/Object/Range. Use the View-->Locals window in the VBA Editor to take a look.

enter image description here

Now, if you wanted to apply a calculation to the range before it gets to your function, you still can.

Consider the formula =CalculateThis(A1:E1^2). What you expect is an array of five values, each value squared. But if you enter this formula by typing a simple enter, what you get is a single value instead of an array. (Bonus points to someone who can explain why the value is 9.)

enter image description here

But enter the same formula with control-shift-enter and you get the expected array of five values, with each value squared.

enter image description here

You have to check for some error conditions if your range and array calculation don't quite match up. For example =CalculateThis(A1:E1^{1,2,3,4,5}) (entered with control-shift-enter) gets you the expected:

enter image description here

But =CalculateThis(A1:E1^{1,2,3}) does not:

enter image description here

(The errors in the variant array are strings "Error 2042" that you can check for.)

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

Comments

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.