Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return array of objects from function - VBA

I need to "return" an Array of Objects from a function that I created using VBA. When I try to set the function as the array it gives me an error message, saying

Object is required.

I am not very used to VBA, and I can't fix this. Here is the function code:

Function sortedList(listRange As Integer, tempList() As ship) As ship
   Dim temp As ship
   Set temp = Nothing

   For i = listRange - 10 To 1 Step -1

       For j = 2 To listRange - 10
            If tempList(j - 1).Arrival > tempList(j).Arrival Then
                Set temp = tempList(j - 1)
                Set tempList(j - 1) = tempList(j)
                Set tempList(j) = temp
            End If
        Next j
    Next i

    'return tempList - how?
    Set sortedList = tempList

End Function

Ship is a "class" that I created. tempList is the array of objects from class ship that I need to return from the function sortedList.

The function works, it's just the return part that I can't make work.

Thanks for the help. If more information is necessary let me know!

like image 760
Pedro Destri Avatar asked Aug 17 '17 12:08

Pedro Destri


People also ask

How do I return an array from a function in VBA?

A function in a normal module (but not a Class module) can return an array by putting () after the data type. Note that what is returned is actually a copy of the array inside the function, not a reference. So if the function returns the contents of a Static array its data can't be changed by the calling procedure.

Can you have an array of objects in VBA?

VBA ArrayList is a kind of data structure we use in VBA to store the data. ArrayList in Excel VBA is a class used to create an array of values. This, unlike traditional arrays, where those arrays have a fixed length, but Array List doesn't any fixed length.

How do you declare a dynamic array in VBA?

Create a Dynamic Array in VBA First, declare an array with its name. After that, the elements count left the parentheses empty. Now, use the ReDim statement. In the end, specify the count of elements you want to add to the array.


1 Answers

Declare the function to return an array

Function sortedList(listRange As Integer, tempList() As ship) As ship()

and then assign the result without Set

sortedList = tempList
like image 108
Rory Avatar answered Oct 15 '22 02:10

Rory