Link to home
Start Free TrialLog in
Avatar of mhdhallak
mhdhallak

asked on

Function resturn array...

How can I set up a function that returns an array?
ASKER CERTIFIED SOLUTION
Avatar of Erick37
Erick37
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of wsh2
wsh2

In VB6 arrays can be passed by reference. When you do a ByRef, the subroutine then updates the actual array in the calling procedure. Below is an example.. just copy and paste it into a New Standard.Exe project and run it.. <smile>

<----- Code Begin ----->

Option Explicit

Private Sub Form_Load()

Dim strWork() As String
Dim intWork() As Integer
ReDim intWork(3)
intWork(0) = 1
intWork(1) = 2
intWork(2) = 3
Call MySubroutine(intWork(), strWork())

MsgBox (intWork(0) & " = " & strWork(0) & vbCrLf _
   & intWork(1) & " = " & strWork(1) & vbCrLf _
   & intWork(2) & " = " & strWork(2) & vbCrLf)

End Sub

Private Sub MySubroutine _
(ByRef intNumbers() As Integer, _
ByRef strStrings() As String)

   Dim intIndex As Integer
   ReDim strStrings(UBound(intNumbers))
   For intIndex = 0 To UBound(intNumbers)
     strStrings(intIndex) = intNumbers(intIndex) & " *** "
     intNumbers(intIndex) = intNumbers(intIndex) + 10
   Next intIndex
   
End Sub

<----- Code End ----->
You can also do this by using Variants.. an Example follows:

<----- Code Begin ----->

Option Explicit

Private Sub Form_Load()

Dim strWork() As String
Dim intWork() As Integer
Dim varWork As Variant
ReDim intWork(3)
intWork(0) = 1
intWork(1) = 2
intWork(2) = 3
varWork = intWork()
strWork() = MyFunction(varWork)

MsgBox (intWork(0) & " = " & strWork(0) & vbCrLf _
   & intWork(1) & " = " & strWork(1) & vbCrLf _
   & intWork(2) & " = " & strWork(2) & vbCrLf)

End Sub

Private Function MyFunction _
(ByRef varTable As Variant) _
As Variant

   Dim intNumbers() As Integer
   intNumbers() = varTable
   
   Dim strStrings() As String
   ReDim strStrings(UBound(intNumbers))
   
   Dim intIndex As Integer
   For intIndex = 0 To UBound(intNumbers)
     strStrings(intIndex) = intNumbers(intIndex) & " *** "
     intNumbers(intIndex) = intNumbers(intIndex) + 10
   Next intIndex
   
   MyFunction = strStrings()

End Function

<----- Code End ----->
Avatar of mhdhallak

ASKER

Sorry guys. But Eric was the first one to answer the question and I worked out his answer and it was right.

Erick37 - would you mind sending me an e-mail please, it's quite urgent. deathtospammers@eircom.net