【问题标题】:VBA Function - Argument Not OptionalVBA 函数 - 参数不是可选的
【发布时间】:2014-06-27 18:03:51
【问题描述】:
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

我理解错误信息,它告诉我我没有填写参数。但是我只有一个参数,而且我已经声明它是可选的。看起来代码认为我正在尝试从函数中调用函数?

什么给了?

【问题讨论】:

标签: excel vba


【解决方案1】:

任何时候分配对象时都需要使用set 关键字。

set RETURN_Equipment = myCollection

【讨论】:

  • 工作就像一个魅力,谢谢!既然您已经指出了这一点,那就完全有道理了。
【解决方案2】:

因为您已将可选参数指定为字符串,如果您未指定值,它将默认为空字符串。

这意味着它不能丢失

如果您将其指定为

Public Function RETURN_Equipment(Optional category) As Collection

这将是一个变体,可能会丢失,尽管您也可以通过将非字符串变体作为类别参数传递来搞砸事情

最好的做法可能是替换

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

【讨论】:

  • 我确实注意到 IsMissing() 没有触发,但没有调查它,因为我的分配错误搞砸了一切。感谢您今天为我节省了一些悲伤的提示。问候,
【解决方案3】:

我收到此错误是因为我在尝试从函数返回结果时使用了错误的函数名。我正在这样做:

Function MyFuncA(arg as String)
    MyFuncB = arg 'The problem is I'm using MyFuncB instead of MyFuncA
End Function

发生这种情况是因为我从其他地方复制了一个函数并更改了名称,但没有更改 return 语句。这不是 OP 的问题,但我收到了相同的错误消息。

【讨论】:

    猜你喜欢
    • 2019-01-09
    • 2015-09-28
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多