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

rue*_*edi 2 excel vba arguments object excel-vba

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

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
Run Code Online (Sandbox Code Playgroud)

但在行中col = colGen我得到的错误是"参数不是可选的",但只是不明白为什么会这样.谁能在这帮助我?

Ror*_*ory 5

你有几个问题.首先,你的函数实际上并没有返回任何东西.其次,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
Run Code Online (Sandbox Code Playgroud)