How to create an array function

Is it possible to create a custom function that returns an array, so that I can assign that function to an array variable?

Note to self: If it is possible, revise XRisk() accordingly.
Who is Participating?
aikimarkConnect With a Mentor Commented:
Public Function ArrayTest(ByVal parmSize As Long) As Long()
    Dim lngLoop As Long
    Dim lngReturn() As Long
    ReDim lngReturn(1 To parmSize)
    For lngLoop = 1 To parmSize
        lngReturn(lngLoop) = lngLoop
    ArrayTest = lngReturn
End Function

Public Sub testarray()
    Debug.Print UBound(ArrayTest(100))
    Debug.Print ArrayTest(105)(3)
End Sub

Open in new window

Patrick MatthewsConnect With a Mentor Commented:
Yes, you can.  I typically do it by:

1) Declaring the function as Variant
2) Declaring an array variable within the function to hold the "answer"
3) Setting the return value of the function to that array variable

Then, if I call that function from elsewhere in my VB project, I make sure to declare the variable accepting the result as a Variant.
A few different ways but this is one:

Function yourFunction () as variant ()
Dim vArray as variant

YOUR app

yourFunction = vArray

End function
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

What version of VB is this.  In VB5 (and earlier versions) you had to return a Variant data type as noted by matthewspatrick.  In VB6, you were allowed to return an array.

What is XRisk()?
MilewskpAuthor Commented:
Hi, aikimark
XRisk() is just the name of a function I'm using. How can I tell if I'm using VB5 or 6? Can you show me an example of a VB6 array function?
click the help about menu.  The version will be displayed in the subsequent dialog box.
MilewskpAuthor Commented:
I have VB 6.5, Version 1053? Can you show me an example of a VB6 array function?
MilewskpAuthor Commented:
Thanks everyone!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.