Passing Arrays Out

It is possible to pass arrays out of subroutines and functions.
An array can be returned from a function (or property).
The receiving array must have the same data type as the arrays being returned from the function (or property)
If a function returns an array (i.e. a Variant) include the word Array in the name of the function
If the data types do not match then a compile error will be thrown.
If the function returns an explicitly typed array then the variable must also be a matching explicitly typed array.


Returning a String Array

This function returns an array of Long integers.
The function declaration returns an arrays of type Long.
The variable "myvalues" is also declared as an array of type Long.

Public Sub AsDataType 
   Dim myvalues() As Long
   myvalues = GetNumbers_ReturnLong()
End Sub

Public Function GetNumbers_ReturnLong() As Long()
   Dim mynumbers() as Long
   ReDim mynumbers(1 to 2)
   mynumbers(1) = 10
   mynumbers(2) = 20
   GetNumbers_ReturnLong = mynumbers
End Function

Returning a Variant Array

This function returns an array which can be of any type

Public Sub AsVariant 
   Dim myvalues() As Variant
   myvalues = GetNumbers_ReturnVariant()
End Sub

Public Function GetNumbers_ReturnVariant() As Variant()
   Dim mynumbers() as Long
   ReDim mynumbers(1 to 2)
   mynumbers(1) = 10
   mynumbers(2) = 20
   GetNumbers_ReturnVariant = mynumbers
End Function

Returning as a Variant

It is possible to return an array of any dimension and any data type.
This can be achieved by declaring the return value as just a Variant.

Public Sub AsVariant 
   Dim myvalues As Variant
   myvalues = GetNumbers_ReturnLong()
End Sub

Public Function DynamicArray() As Variant
Dim myIntegerArray() As Integer
Dim myLongArray() As Long
Dim myDoubleArray() As Double
Dim myStringArray() As String

   DynamicArray = myIntegerArray
   DynamicArray = myLongArray
   DynamicArray = myDoubleArray
   DynamicArray = myStringArray
End Function

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext