Is it possible to return an array from a function in a module? If so, how do I define it?
Printable View
Is it possible to return an array from a function in a module? If so, how do I define it?
Yes you can. Try this:
You can pass an array into the function as byref. See following code:
Public Function SomeFunc(ByRef SomeArray)
ReDim SomeArray(1)
SomeArray(0) = "Item 1"
SomeArray(1) = "Item 2"
End Function
Private Sub Command1_Click()
Dim SomeArray() 'Sets a dynamic variant array
Dim FuncReturn 'Dimension to get function return
FuncReturn = SomeFunc(SomeArray)
List1.AddItem SomeArray(0)
List1.AddItem SomeArray(1)
End Sub
To test this create a form and put a command button and a list view on it then paste the code into the form.
the correct code is:
Code:
Private Sub Command1_Click()
Dim varResult as variant
varResult=GetMyArray()
Ens Sub
Private Function GetMyArray()as variant
on error goto Err_Handler
Dim strArray()as string
dim i as long
redim strArray(5)
for i=0 to 5
strArray(i)="Hugo "&i
next i
GetMyArray=strArray
exit function
Err_Handler:
GetMyArray=null
end Function
Hi
Both methods are fine. I tend to use the return from a function as test of its success.
I guess that when you use ByRef it is not strictly being returned by the function but rather being set by the function.
I don't think you can return multiple arguments from a function so you may find that passing arguments ByRef gives you a solution.
The following code gives an example of a function that passes two variant arrays into a function. The function then populates these arrays with some strings. As we are using ByRef (which is the actually the default in VB, but I tend to state ByRef to remind myself) when we return to the sub that called the function I can use the new populated array.
Public Function SomeFunc(ByRef MyArray, _
ByRef MyArray2) As String
ReDim MyArray(1)
ReDim MyArray2(1)
MyArray(0) = "String 1"
MyArray(1) = "String 2"
MyArray2(0) = "String 1"
MyArray2(1) = "String 2"
End Function
Private Sub Form_Load()
Dim MyArray()
Dim MyArray2()
Dim FuncReurn As String
FuncReurn = SomeFunc(MyArray, MyArray2)
End Sub
I am no expert on VB (only been programming with it for a couple of months), so if you have any comments on my use of the language I would appreciate it.
Regards,
Gibbo