将集合作为参数发送到过程
Send collection to procedure as parameter
我尝试将集合作为函数输出提交给另一个过程。这是我的代码:
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
行中我得到了 "Argument is not optional" 的错误,但就是不明白为什么会这样。有人可以帮我吗?
你有几个问题。首先,您的函数实际上 return 什么都没有。其次,在将对象分配给变量时需要使用 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
我尝试将集合作为函数输出提交给另一个过程。这是我的代码:
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
行中我得到了 "Argument is not optional" 的错误,但就是不明白为什么会这样。有人可以帮我吗?
你有几个问题。首先,您的函数实际上 return 什么都没有。其次,在将对象分配给变量时需要使用 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