Returning an Array from a Function

It’s possible for a function to return an array of values now from Visual Basic 6.0 version onwards. For example, you may want to return an array of bytes from a function without having to perform conversions to and from a string.

Here’s a simple example of a function that returns an array of bytes:

Private Sub Form_Load()

Dim b As Byte

Dim I As Integer

Dim ReturnArray() As Byte

i = Cbyte(54)

ReturnArray() = ArrayFunction(b)

For i = 0 To Ubound(ReturnArray)

Debug.Print ReturnArray(i)

Next

End Sub

Public Function ArrayFunction(b As Byte) As Byte()

Dim x(2) As Byte

x(0) = b

x(1) = b + CByte(200)

x(2) = b + b

ArrayFunction = x

End Function

After running the above example, ReturnArray() would be a three-element array containing the values assigned to the array in the ArrayFunction. Note that the array must be of the same data type as the function (in this case, Byte). Because this is a function call, the array can be passed without the parentheses.


No comments:

Post a Comment