Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array function in Excel VBA

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
like image 592
Joe Avatar asked Apr 24 '12 01:04

Joe


3 Answers

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
like image 102
Mike T Avatar answered Sep 28 '22 02:09

Mike T


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.

like image 20
andy holaday Avatar answered Sep 28 '22 03:09

andy holaday


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
like image 44
Charles Williams Avatar answered Sep 28 '22 02:09

Charles Williams