将variables作为parameter passing给VBA中的函数

我有一个function

Function convertToDict(arrayIp As Variant) As Object Dim dict As Object Set dict = CreateObject("scripting.dictionary") For Each element In arrayIp If dict.exists(element) Then dict.Item(element) = dict.Item(element) + 1 Else dict.Add element, 1 End If Next End Function 

我试图从一个子调用这个函数

 Dim dict As Object varray = Range("B4:B" & finalRow - 1).Value dict = convertToDict(varray) 

但它会抛出错误:

运行时错误450,参数的错误数量或属性无效

我在这里做了什么错误?

我传递一个变体,结果是一个Object

因为你正在处理你需要在对象和子对象中 设置的 对象

 Function convertToDict(arrayIp As Variant) As Object Dim dict As Object Set dict = CreateObject("scripting.dictionary") For Each element In arrayIp If dict.exists(element) Then dict.Item(element) = dict.Item(element) + 1 Else dict.Add element, 1 End If Next Set convertToDict = dict End Function Sub qwerty() Dim dict As Object finalRow = 10 varray = Range("B4:B" & finalRow - 1).Value Set dict = convertToDict(varray) End Sub 

由于dict是一个对象,因此在分配给它时需要使用Set 。 尝试

 Set dict = convertToDict(varray)