当将键作为字符串参数传递给函数时,vba excel错误“通过ref参数类型不匹配”

时间:2013-11-11 08:57:39

标签: excel vba excel-vba argument-passing

我在以下子测试()中遇到“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时,错误消失。

请告诉我为什么需要这个多余的声明?

2 个答案:

答案 0 :(得分:3)

此外,您已在函数中声明k As String,因此该函数希望您将String传递给它。由于您尚未在k中声明Sub Test()k将被视为Variant,因此您将通过参数类型不匹配获得" "错误。

当您通过curKey时,它不会给您一个错误,因为curKeyString中定义为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