vba excel错误“通过引用参数types不匹配”时传递键作为string参数
我在下面的子testing()中遇到“通过参数types不匹配”错误:
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
当我用curKey
参数而不是k
参数调用函数GetOtherDict
,错误消失。
你能告诉我为什么我需要这个多余的声明?
此外,你已经在函数中声明k As String
,所以函数期望你传递一个String
。 既然你没有在Sub Test()
声明k
, k
将被视为一个Variant
,因此你得到了“ 通过参数types不匹配 ”的错误。
它不会给你一个错误,当你通过curKey
因为curKey
被定义为String
在Sub Test()
这是什么函数期望…
另一个提示 :请在代码末尾使用Option Explicit
。
我没有编程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