首页 > 解决方案 > VBA - 字典搜索 - 类型不匹配

问题描述

所以我正在学习如何使用字典,但我遇到了类型问题。在下面的代码中,我得到一个错误。

类型不匹配

每次我尝试打电话If Not target.SearchItem(sKey) Is Nothing Then。我希望它返回一个对象,如果不是,Nothing我可以将它转换回 long。

For Each target In dList.getArray
    For Each key In aList.getArray(1).getKeys
        sKey = CStr(key)
            'Error occurs here - as Type mismatch
            If Not target.SearchItem(sKey) Is Nothing Then
                cData.setData(sKey) = CLng(target.SearchItem(sKey))
                target.removeData = sKey
             Else
                 'if value doesn't exists it will just be 0
                  cData.setData(sKey) = 0
              End If
    Next key
Next target

data是我的字典,它在一个单独的类中:

Property Get SearchItem(name As String) As Variant
    If data.exists(name) Then
        'becomes a Variant/Integer - data(name) is a Variant/long
        Set SearchItem = CVar(data(name))
    Else
        'Should return Nothing if item doesnt exist
        Set SearchItem = Nothing
    End If
End Property

更新:为了解释我多一点的问题。即使我将它作为变体返回,它仍将部分为 Integer,因此 If Nottarget.SearchItem(sKey) Is Nothing Then将返回不匹配,因为它需要一个对象并且 VBA 不会将其读取为变体或其他东西。有没有什么东西可以长期有效?那将解决问题。

下面的代码返回了我想要的 long,但我不能使用 -99,因为它会破坏数据分析。它必须是没有价值的东西

Property Get SearchItem(name As String)
    If data.exists(name) Then
        SearchItem = data(name)
    Else
        'SearchItem = Nothing
         SearchItem = -99
    End If
End Property

标签: excelvbadictionarytype-mismatch

解决方案


  1. If Not target.SearchItem(sKey) Is Nothing Then
    • 这意味着存储的项目是一个对象
  2. cData.setData(sKey) = CLng(target.SearchItem(sKey))
    • 此行对 Object 起作用的唯一方法是 Object 具有可以转换为 long 的默认值。如果 Object 的默认值返回一个可以转换为 long 的值。

Clng(Object)对存储在字典中的实际对象有效吗?

如果要存储混合数据类型,SearchItem请检查返回数据是否为对象。

Property Get SearchItem(name As String) As Variant
    If isObject(data(name)) Then
        Set SearchItem = data(name)
    Else
        SearchItem = data(name)
    End If
End Property

我不会在这种方法中转换数据类型。相反,我会创建一个或多个单独的方法或在使用点转换数据类型。

Function getTypedItem(Key as Variant, DataType as VbVarType) as Variant

IsNumeric(对象)

.Exists由于您使用的是字典的实际键,我们知道它会返回一些东西,并且在这种情况下不需要。您需要做的是测试它是否返回一个对象,然后再测试Object Is Nothing.

If IsObject(Target.SearchItem(sKey)) Then
    If IsNumeric(Target.SearchItem(sKey)) Then
        cData.setData(sKey) = CLng(Target.SearchItem(sKey))
    End If
ElseIf IsNumeric(Target.SearchItem(sKey)) Then
    cData.setData(sKey) = CLng(Target.SearchItem(sKey))
End If

推荐阅读