作为参数发送集合到过程
我尝试将一个集合作为一个函数输出提交给另一个过程。 这是我的代码:
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
我得到的错误,“参数不是可选的”,但不明白为什么这是。 有人可以帮我吗?
你有几个问题。 首先,你的函数实际上并没有返回任何东西。 其次,在将对象分配给variables时,您需要使用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
关键字 ,所以你的行应该是
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