上下文
在VBA中,您可以创建并填充字典,例如:
Dim oDict As Object
Set oDict = CreateObject("Scripting.Dictionary")
oDict("key 1") = "value 1"
oDict("key 2") = "value 2"
oDict("key 3") = "value 3"
使用Keys方法,您可以将键作为数组获取:
返回包含字典对象中所有现有键的数组。
Dim aKeys() As Variant
aKeys = oDict.Keys
Debug.Print VarType(aKeys) ' prints "8204"
Debug.Print VarType(oDict.Keys) ' prints "8204"
问题
但是当我直接访问其中一个键时,会出现这个神秘的错误信息:
Debug.Print aKeys(2) ' prints "key 3"
Debug.Print oDict.Keys(2) ' Run-time error '451':
' Property let procedure not defined
' and property get procedure did not
' return an object
解决失败的尝试
虽然上述是我不理解的主要行为,但以下是处理oDict.Keys
作为数组的所有尝试的完整列表:
Option Explicit
Public Function ArrayGet(ByRef aArray() As Variant, i As Integer) As Variant
ArrayGet = aArray(i)
End Function
Public Function ArrayWrap(ByRef aArray() As Variant) As Variant()
ArrayWrap = aArray
End Function
Public Sub TEST()
Dim oDict As Object
Set oDict = CreateObject("Scripting.Dictionary")
oDict("key 1") = "value 1"
oDict("key 2") = "value 2"
oDict("key 3") = "value 3"
Dim aKeys() As Variant
aKeys = oDict.Keys
Debug.Print VarType(aKeys) ' prints "8204"
Debug.Print VarType(oDict.Keys) ' prints "8204"
Debug.Print aKeys(2) ' prints "key 3"
'Debug.Print oDict.Keys(2) ' Run-time error '451': Property let procedure not defined and property get procedure did not return an object
'Debug.Print oDict.Keys.Get(2) ' Run-time error '424': Object required
'Debug.Print oDict.Keys.Item(2) ' Run-time error '424': Object required
Debug.Print ArrayGet(aKeys, 2) ' prints "key 3"
'Debug.Print ArrayGet(oDict.Keys, 2) ' Compile error : Type mismatch: array or user-defined type expected
'Debug.Print Array(aKeys)(2) ' Run-time error '9' : Subscript out of range
'Debug.Print Array(oDict.Keys)(2) ' Run-time error '9' : Subscript out of range
Debug.Print ArrayWrap(aKeys)(2) ' prints "key 3"
'Debug.Print ArrayWrap(oDict.Keys)(2) ' Compile error : Type mismatch: array or user-defined type expected
Dim key As Variant
For Each key In aKeys
Debug.Print key ' prints "key 1", "key 2" and "key 3"
Next key
For Each key In oDict.Keys
Debug.Print key ' prints "key 1", "key 2" and "key 3"
Next key
End Sub