8

I have a function in VBA that generates an array of strings. It works fine when called from another VBA function, but not when called from the worksheet.

Here's how it should be used:

  • select A1:A3
  • write in the formula bar =Test(), then hit Ctrl-Shift-Enter to make it an array function
  • A1 should contain A, A2 should contain B, and A3 should contain C

When I actually try this, it puts A in all three cells of the array. How can I get the data returned by Test into the different cells of the array?


For those who'd like to see it, here's the code of the function. Keep in mind, the function works fine when called from other functions.

Function Test() As String()
    Dim a(1 To 3) As String
    a(1) = "A"
    a(2) = "B"
    a(3) = "C"
    Test = a
End Function

4 Answers 4

9

You function works fine if you transpose the data. To do this, you need Variant() instead of String():

Function Test() As Variant()
    Dim a(1 To 3) As Variant
    a(1) = "A"
    a(2) = "B"
    a(3) = "C"
    Test = Application.Transpose(a)
End Function
Sign up to request clarification or add additional context in comments.

4 Comments

I had no idea that the default direction of an array was to the right, rather than down.
Unfortunatelly, there doesn't appear to be a simple automatic way for Excel to fill the array either horizontal or vertical. There could be some tricks out there, however.
Yup, as @andy holaday points out, Chip Pearson has also figured out the horizontal/vertical dilemma.
Rather than use Transpose in the UDF you could use Transpose in you array formula when you want a vertical entry set, or not if you want it horizintal
4

You might want to check Chip Pearson's advice on returning an array from a UDF.

This is my first response here. I hope this is not inappropriate.

1 Comment

It's never wrong to refer to Chip Pearson's site. At least I hope not, as I do it all the time! +1
3

I find it simplest to always work with 2-dimensional arrays, then you don't need transpose etc

Function Test() As String()
    Dim a(1 To 3, 1) As String
    a(1, 1) = "A"
    a(2, 1) = "B"
    a(3, 1) = "C"
    Test = a
End Function

Comments

0

Just figured out the problem -- the first dimension of an array going from VBA to Excel is horizontal, not vertical. To see the output of Test, put the array function =Test() in A1:C1 (not A1:A3).

1 Comment

Reading this reply in combination with the one from Charles Williams above is a bit confusing, although both are correct. A 1D VBA array is passed to Excel as a single row (as seen in the original Test UDF). A 2D VBA array is passed with the first dimension in a column (as seen in the Test UDF posted by Charles).

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.