Arrays and Functions in VB6

From Free Knowledge Base- The DUCK Project: information for everyone
Jump to: navigation, search

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

 

Byte Arrays

Convert String to ANSI Byte Array

Use the StrConv function with "vbFromUnicode" to convert a Visual Basic string to a byte array of ANSI characters.

Dim company As String
Dim b() As Byte
company = "CHILKAT SOFTWARE"
b = StrConv(company,vbFromUnicode)

Convert Byte Array to String

Use the StrConv function with "vbUnicode" to convert a byte array of ANSI characters to a string.

Dim s As String
Dim b(1 To 3) As Byte
b(1) = Asc("A")
b(2) = Asc("B")
b(3) = Asc("C")
s = StrConv(b, vbUnicode)