Vba 将集合作为参数发送到过程

Vba 将集合作为参数发送到过程,vba,excel,object,arguments,Vba,Excel,Object,Arguments,我尝试将集合作为函数输出提交给另一个过程。这是我的代码: Function colGen() As Collection Dim col As Collection Dim bo As Boolean Dim str As String Set col = New Collection bo = True str = "Test" col.Add bo col.Add str End Function Sub test() Dim col As Collection Set col = New

我尝试将集合作为函数输出提交给另一个过程。这是我的代码:

Function colGen() As Collection
Dim col As Collection
Dim bo As Boolean
Dim str As String
Set col = New Collection
bo = True
str = "Test"
col.Add bo
col.Add str
End Function

Sub test()
Dim col As Collection
Set col = New Collection
Dim str As String
col = colGen
MsgBox (str)
End Sub

但是在
col=colGen
行中,我得到了一个错误,即“参数不是可选的”,但我不明白为什么会这样。有人能帮我吗?

你有几个问题。首先,函数实际上不返回任何内容。其次,将对象分配给变量时,需要使用
Set

Function colGen() As Collection
    Dim col                   As Collection
    Dim bo                    As Boolean
    Dim str                   As String
    Set col = New Collection
    bo = True
    str = "Test"
    col.Add bo
    col.Add str
    Set colGen = col
End Function

Sub test()
    Dim col                   As Collection
    Dim str                   As String
    Set col = colGen
    ' str has no value
    ' so check the collection
    MsgBox col(2)
End Sub

由于集合是一个对象,要影响它一个新值,您必须使用
设置
关键字
,因此您的行应该是

Set col=colGen

而不是

col=colGen

就像您所做的那样
Set col=New Collection


您还忘了定义函数的输出,因此下面是您的修改代码:

Function colGen() As Collection
    Dim col As Collection, _
        bo As Boolean, _
        str As String

    Set col = New Collection

    bo = True
    str = "Test"

    col.Add bo
    col.Add str

    'You must assign your output value
    'As it is an object, you MUST use "Set"
    Set colGen = col
End Function

Sub test()
    Dim col As Collection, _
        str As String

    Set col = New Collection

    col = colGen
    str = col(col.Count)
    MsgBox (str)
End Sub

尝试
Set col=colGen
因为集合是一个对象,要影响它一个新值,您必须使用
Set
关键字,所以您的行应该是
Set col=colGen