Difference between revisions of "Arrays and Functions in VB6"
From Free Knowledge Base- The DUCK Project: information for everyone
m |
|||
Line 35: | Line 35: | ||
End Sub | End Sub | ||
− | + | === pass an Array back to the calling procedure === | |
Private Function ReturnArray() As Variant | Private Function ReturnArray() As Variant |
Revision as of 18:50, 28 January 2008
Passing Arrays to Sub Routines and Functions
Simple code example:
Option Explicit Private Sub cmdGo_Click() Dim aFruit(9, 1) aFruit(0, 0) = 34 aFruit(0, 1) = "Apples" aFruit(1, 0) = 56 aFruit(1, 1) = "Oranges" aFruit(2, 0) = 4 aFruit(2, 1) = "Peaches" Call DoDisplayIt(aFruit) End Sub Private Sub DoDisplayIt(aFruit) Dim cnt As Integer txtOut.Text = "" For cnt = 0 To 2 txtOut.Text = txtOut.Text & vbCrLf & cnt & ". " & aFruit(cnt, 1) & " (in stock): " & aFruit(cnt, 0) Next cnt End Sub
Arrays are passed to procedures "By Value" by default in Visual BASIC. By Value means that the pointer is being passed, not the actual values. So if the Array value is modified in the procedure, it is also modified from the code after where the procedure is called. Visual Basic will not allow you to pass the value of an Array to a procedure "By Value."
Call RoutineA(varArray) Private Sub RoutineA(ByRef intArray() As Integer) Dim obj As Variant For Each obj In intArray Form1.txtOut.text = Form1.txtOut.text & vbCrLf & obj Next End Sub
pass an Array back to the calling procedure
Private Function ReturnArray() As Variant Dim MyArray(3) As Integer 'Declare a Static Integer Array of 4 elements MyArray(0) = 1 MyArray(1) = 2 MyArray(2) = 3 MyArray(3) = 4 ReturnArray = MyArray 'Pass the array back as a return value End Function
Accept an Array as an argument.
Private Sub cmdReturnArray_Click() Dim retval As Variant Dim obj retval = ReturnArray 'Assign the return value to a Variant Variable For Each obj In retval Form1.Print obj Next End Sub