为什么VBA函数为集合提供编译错误但不为字符串提供编译错误

Joh*_*ohn 2 excel vba

我正在尝试将集合传递给VBA函数,但遇到了似乎无法修复的编译错误。

这是给出错误的简化示例。

Sub test()
    Dim fooString As String
    Dim fooCollection As collection
    Set fooCollection = New collection
    useString (fooString)
    useCollection (fooCollection)
End Sub

Public Function useString(foo As String)
    MsgBox ("here")
End Function

Public Function useCollection(foo As collection)
    MsgBox ("here")
End Function
Run Code Online (Sandbox Code Playgroud)

我没有看到自己在做的事情与示例所显示的有所不同,例如此处所示的示例:如何对集合进行排序?

这是我得到的错误(编译错误:参数不是可选的):

在此处输入图片说明

Ive*_*ach 5

由于出现隐式“有用”的默认成员,因此您得到此对话框。在“对象浏览器”中,导航到“类”窗格中的“集合”,在成员中,您将看到Item是默认成员,由深青色图标指定。

Collection类的默认成员

这是另一个例子。在运行代码之前,问问自己它将打印什么,并大声说出来。

Public Sub DontWrapIt()
    Dim foo As Range
    Set foo = Sheet1.Range("A1")
    GiveMeARange foo
    GiveMeARange (foo)
End Sub

Private Sub GiveMeARange(ByVal param As Variant)
    Debug.Print TypeName(param)
End Sub
Run Code Online (Sandbox Code Playgroud)

用括号将对象包装起来,将对其进行评估,这将导致对“有用的”默认成员的隐式调用……这需要Index未提供的参数-因此,“参数不是可选的”。