我在以下子测试()中遇到“by ref argument type mismatch”错误:
Public Function GetOtherDict(k As String, dict As Dictionary) As Dictionary
Dim otherDict As New Dictionary
curItem = dict.Item(k)
otherDict.Add curItem, curItem
Set GetOtherDict = otherDict
End Function
Public Sub Test()
Dim dict As New Dictionary
dict.Add "a", 1
dict.Add "b", 2
For Each k In dict.Keys
Dim otherDict As Dictionary
Dim curKey As String
curKey = k
Set otherDict = GetOtherDict(k, dict)
Next
End Sub
当我使用GetOtherDict
参数而不是curKey
参数调用函数k
时,错误消失。
请告诉我为什么需要这个多余的声明?
答案 0 :(得分:3)
此外,您已在函数中声明k As String
,因此该函数希望您将String
传递给它。由于您尚未在k
中声明Sub Test()
,k
将被视为Variant
,因此您将通过参数类型不匹配获得" 强>"错误。
当您通过curKey
时,它不会给您一个错误,因为curKey
在String
中定义为Sub Test()
,这是函数所期望的...
另一个提示:请在代码末尾使用Option Explicit
。
答案 1 :(得分:-1)
我没有编程vba很长时间但是尝试
Public Function GetOtherDict(k As String, dict As Dictionary) As Dictionary
Dim otherDict As New Dictionary
curItem = dict.Item(hub)
otherDict.Add curItem, curItem
return otherDict
End Function