Returning Array from Function

  • Thread starter Thread starter Dale Fye
  • Start date Start date
D

Dale Fye

I have some code that enumerates the key fields in a
table. I use this code in several places in one of my
programs, but would believe that storing these field names
in an array and refering to the array would be quicker
than what I am currently doing.

I'd like to be able to pass the name of the table to a
function, and have it return an array to the calling code,
but cannot figure out how to do this. I can declare the
Array in the General section of my form and just populate
it in my function, but I need to be able to use this
function in several different form modules, so would
prefer to keep the array as a local variable. Anyone know
how to deal with this?
 
Dale Fye said:
I have some code that enumerates the key fields in a
table. I use this code in several places in one of my
programs, but would believe that storing these field names
in an array and refering to the array would be quicker
than what I am currently doing.

I'd like to be able to pass the name of the table to a
function, and have it return an array to the calling code,
but cannot figure out how to do this. I can declare the
Array in the General section of my form and just populate
it in my function, but I need to be able to use this
function in several different form modules, so would
prefer to keep the array as a local variable. Anyone know
how to deal with this?

You can have the function return a Variant, and in the function assign
an array to the function's return value. For example,

'----- function definition -----
Function fReturnArray() As Variant

fReturnArray = Array("Red", "Green", "Blue")

End Function

'----- In Immediate Window -----
a = freturnarray : for i = lbound(a) to ubound(a) : ?a(i) : next i
Red
Green
Blue
 
You can Dim the Array in the calling Sub/Function, and pass it as a
Parameter of the work Function and populate there. When the work function
returns the calling Sub/Function can access the Array directly. Here is an
example:

Sub Worker(a() As Integer)
Dim i As Integer
For i = 1 To 5
a(i) = i * 10
Next
End Sub

Sub Caller()
Dim a(10) As Integer, i as Integer
Call Worker(a())
For i = 1 To 5
Debug.Print i & " --- " & a(i)
Next
End Sub

Ron W
 
Back
Top