返回自定义对象Excel VBA

我不知道函数如何返回Excel VBA中的对象。

例如,在Java中,我习惯这样写:

Private ArrayList<> getARandomArrayList() { //... My code return anArrayList; } 

这个方法应该返回一个我可以使用的arrayList。

如果我在Excel中这样做,我相信它应该是这样的:

 Function getARandomArrayList() As System.Collections.ArrayList '... My code getARandomArrayList = anArrayList End Function 

当我尝试使用这种函数时,出现“编译错误:用户定义的types未定义”错误窗口。 如果我使用像Double或Stringtypes的variables,我没有问题。 只有与对象,我得到的错误。

一个VBA.Collection可能会为你工作,这取决于你的需求。 (编辑:正如Vincent在评论中指出的,不需要额外的引用。)这是它看起来像使用一个:

 Function getSomeCollection() As VBA.Collection 'Declare a collection Dim newCollection As VBA.Collection 'Initialize the collection Set newCollection = New VBA.Collection 'Add a string. 'Other methods are Item (access by index), Count, and Remove (by index) newCollection.Add "hello" 'Reference the collection (note it's 1-based) MsgBox newCollection(1) 'Set the return value Set getSomeCollection = newCollection End Function 

正如罗里所说:

您必须设置对相关对象库的引用,以便能够将variables声明为包含在其中的types

我去参考和激活系统librairies。