VBA函数 – 参数不可选
Public Function RETURN_Equipment(Optional category As String) As Collection Dim config As classConfiguration Set config = New classConfiguration Dim item As classItem Set item = New classItem Dim myCollection As Collection Set myCollection = New Collection For Each config In Configurations For Each item In config.colItems If IsMissing(category) Then myCollection.add item ElseIf InStr(category, "mainframe") <> 0 And item.category = "mainframe" Then myCollection.add item MsgBox "Fired!" ElseIf category = "accessory" And item.category = "accessory" Then Else End If Next Next RETURN_Equipment = myCollection End Function
我不断收到
编译错误:
参数不是可选的
我在最后一行得到错误
RETURN_Equipment = myCollection
我了解错误信息,它告诉我,我没有填写一个参数。 但是我只有一个参数,我声明它是可选的。 它看起来像代码认为我试图从函数调用函数?
是什么赋予了?
任何时候你分配一个对象,你需要使用set
关键字。
set RETURN_Equipment = myCollection
我得到这个错误,因为我试图从函数返回结果时使用了错误的函数名称。 我正在这样做:
Function MyFuncA(arg as String) MyFuncB = arg 'The problem is I'm using MyFuncB instead of MyFuncA End Function
发生这种情况是因为我从其他地方复制了一个函数并更改了名称,而不是返回语句。 这不是OP的问题,但我得到相同的错误信息。
因为您已将可选参数指定为string,所以如果未指定值,则会默认为空string。
这意味着它不能错过
如果你指定为
Public Function RETURN_Equipment(Optional category) As Collection
这将是一个变种,可能会丢失,虽然你也可以通过传递非stringvariables作为类别参数
最好的行动方式可能是取代
If IsMissing(category) Then
同
If category = "" Then
正如Brad指出的那样,你需要使用Set
Set RETURN_Equipment = myCollection
有关完整的详细信息,请查看http://msdn.microsoft.com/en-us/library/office/gg251721%28v=office.15%29.aspx