运行时错误与字典使用后期绑定但不提前绑定
我所做的是将一个字典放入一个子例程中的一个数组中
这是定义
Dim Arr() As Variant ReDim Arr(0 To Dict.Count - 1) For c= 0 To Dict.Count - 1 Arr(c) = Dict.Keys(c) ' <~~~~~~ Error here Next c
编译器说
运行时错误451:属性让过程未定义和属性get过程没有返回一个对象。
它与伟大的工程
Public Sub SubRoutine(Dict As Scripting.Dictionary)
但不与
Public Sub SubRoutine(Dict As Object) –
请参阅声明没有Microsoft脚本运行时的字典
<Solution>
你做这个
Dim Arr() As Variant ReDim Arr(0 To Dict.Count - 1) For c = 0 To Dict.Count - 1 Arr(c) = Dict.Keys(c) Next c
但是像这样循环是不必要的。 这就是Arr = Dict.Keys
所做的。 所以,而不是以上,只是做
Dim Arr As Variant Arr = Dict.Keys
额外的好处是, 这使得错误消失 。
</Solution>
但是为什么错误发生在代码的后期版本中,而不是早期版本呢?
<Educated guess slash wild speculation>
在早期绑定的情况下,编译器知道.Keys
方法不带参数 – 它只是返回一个数组。 所以它将Dict.Keys(c)
解释为{returned array}(c)
并返回返回数组的第c
个元素。
用后期绑定,我猜Object容器不知道.Keys
方法不带参数(aka参数),所以它将c
作为参数发送给它。 但没有这样的getter(或setter)定义,因此错误。 为了解决这个问题,你可以通过说Dict.Keys()(c)
来强制它不向Keys
方法发送参数,这会带来{returned array}(c)
行为。
</Educated guess slash wild speculation>
这是我第一次遇到这样的情况,后期代码的行为与早期的不同。
这工作:
Dim Arr() As Variant ReDim Arr(0 To Dict.Count - 1) For c = 0 To Dict.Count - 1 Arr(c) = Dict.Keys()(c) Next c