vba excel error "by ref argument type mismatch" when passing key to function as string argument

StackOverflow https://stackoverflow.com/questions/19902327

  •  30-07-2022
  •  | 
  •  

Pregunta

I'm getting an "by ref argument type mismatch" error on the following sub test():

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

When I call the function GetOtherDict with the curKey argument instead of the k argument the error disappears.

Can you please tell me why do I need this redundant declaration?

¿Fue útil?

Solución

Also you have declared k As String in the function so the function expects that you pass a String to it. Since you have not declared k in Sub Test(), k will be considered as a Variant and hence you are getting that "by ref argument type mismatch" Error.

It doesn't give you an error when you pass curKey because curKey is defined as String in Sub Test() which is what the function expects...

Another TIP: Please use Option Explicit at the end of the code.

Otros consejos

I havent programmed vba for a long time but try

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top