2

I created a function called test

Function test(a() As Variant)
    Debug.Print "Type: "; TypeName(a)
    Debug.Print "lb: "; LBound(a)
    Debug.Print "ub: "; UBound(a)
    test = a(UBound(a))
End Function

It is okay when I type

=test({4,5,6,8,9})

in a cell. It returns 9.

Let's have some data on the worksheet.

   A  B
1  1  3
2  0  6
3  1  9
4  0  7
5  1  8

I type the below formula with ctrl+shift+enter in a cell.

{=test(IF(A1:A5=1,B1:B5))}

I think an array is passed into test but it doesn't work. It can return LBound(a) and UBound(a) as usual but test = a(UBound(a)) fails.

What is the problem? How can I write a write VBA user defined function to take array argument from IF.

1
  • =test{(IF(A1:A5=1,B1:B5))} Try this Commented Dec 18, 2015 at 4:44

1 Answer 1

2

There is a fundimental difference between the two examples. =test({4,5,6,8,9}) passes a 1-D array, and {=test(IF(A1:A5=1,B1:B5))} passes a 2-D array. Your code is set up to process only 1-D arrays, so the second example fails.

How to fix this will depend entirely on what you actually want the UDF to do. For the example, You could coerce the input to 1-D using Transpose, but that's probably to limited for the general case. Might be better to test in parameter to determine its dimension and process accordingly

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

2 Comments

Just a follow-up question, how can I know this is a 2-D array? and what index is used in this array?
There are lots of good array functions on cpearson.com including finding the dimension of an array. To make it work for just 2-D try test = a(UBound(a,1))

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.