返回自定义对象Excel VBA
我很难理解函数如何在Excel VBA中返回对象 例如,在Java中,我习惯于这样编写:返回自定义对象Excel VBA,vba,excel,Vba,Excel,我很难理解函数如何在Excel VBA中返回对象 例如,在Java中,我习惯于这样编写: Private ArrayList<> getARandomArrayList() { //... My code return anArrayList; } Function getARandomArrayList() As System.Collections.ArrayList '... My code getARandomArrayList = anAr
Private ArrayList<> getARandomArrayList() {
//... My code
return anArrayList;
}
Function getARandomArrayList() As System.Collections.ArrayList
'... My code
getARandomArrayList = anArrayList
End Function
当我尝试使用这种函数时,我得到一个“编译错误:用户定义类型未定义”错误窗口。如果我使用像Double或String这样的变量类型,我就没有问题了。只有对象才会出错 A
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
根据您的需要,
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
正如罗里所说:
必须设置对相关对象库的引用,才能将变量声明为其中包含的类型 我进入参考并激活了系统库。正如Rory所说:
必须设置对相关对象库的引用,才能将变量声明为其中包含的类型
我进入了引用并激活了系统库。您必须设置对相关对象库的引用,才能将变量声明为其中包含的类型。感谢它终于起作用了。我将在答案中引用您的话。您必须设置对相关对象库的引用,以便能够将变量声明为其中包含的类型。谢谢,它终于起作用了。我会在答案中引用你的话。非常有趣!我可能会使用它而不是ArrayList。事实上,这是一个双重答案,因为我不需要选择引用。更新的答案提到它不需要额外的引用。(顺便说一句,如果这个答案有用,请标记为答案和/或向上投票!谢谢!)非常有趣!我可能会使用它而不是ArrayList。事实上,这是一个双重答案,因为我不需要选择引用。更新的答案提到它不需要额外的引用。(顺便说一句,如果这个答案有帮助,请标记为答案和/或向上投票!谢谢!)