excel - 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
解决方案
If Not target.SearchItem(sKey) Is Nothing Then
- 这意味着存储的项目是一个对象
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
推荐阅读
- javascript - 为什么我的简单 if 检查,如果用户在那里,在我的 ejs 视图中抛出一个错误。如果 var 不存在,我指定其他内容,但仍然不起作用
- django - 如何在新表 Django 中对来自不同表的列进行求和
- python - 使用 Selenium 抓取嵌套的 html
- cassandra - 您应该使用准备好的语句进行准确的类型映射
- python - 我尝试运行这个 Mobilenet 脚本
- javascript - 奇怪的 referenceError 仅在第一次加载索引时发生
- r - dplyr 中波浪号和点符号的含义
- php - 图像未在服务器上使用 TCPDF 显示
- sql - SQlite3 Join 和多重排序
- reactjs - 如何删除/更新表格?