【问题标题】:Runtime Error with Dictionary when using late binding but not early binding使用后期绑定但不使用早期绑定时字典出现运行时错误
【发布时间】:2021-10-23 07:16:14
【问题描述】:

我所做的是将字典放入子例程中的数组中

这就是定义

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:未定义属性让过程和属性获取过程未返回对象。

配合使用效果很好
Public Sub SubRoutine(Dict As Scripting.Dictionary) 

但不是与

Public Sub SubRoutine(Dict As Object) –

请参考Declare a dictionary without Microsoft Scripting Runtime

【问题讨论】:

  • 您是如何声明Arr 的?在这种情况下c 是什么?

标签: excel vba dictionary


【解决方案1】:

&lt;Solution&gt;

你这样做

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

额外的好处是 这会使错误消失

&lt;/Solution&gt;


但是为什么在后期绑定版本的代码中会出现错误,而不是在早期绑定呢?

&lt;Educated guess&gt;

通过早期绑定,编译器知道the .Keys method 不接受任何参数——它只是返回一个数组。因此它将Dict.Keys(c) 解释为{returned array}(c) 并返回该返回数组的cth 元素。

使用 late 绑定,我猜 Object 容器不知道 .Keys 方法不接受参数(又名参数),因此它将 c 作为参数发送给它.但是没有定义这样的getter(或setter),因此出现错误。要进行补救,您可以通过 Dict.Keys()(c) apparently force it 不向 Keys 方法发送任何参数,这会恢复 {returned array}(c) 的行为。

&lt;/Educated guess&gt;

这是我第一次遇到这样的情况,后期绑定代码的行为与早期绑定不同。

【讨论】:

  • 奇怪的行为! OP 也可以通过以下方式解决:Dict.Keys()(c),但正如您所注意到的,不必迭代键来构造数组,因为Keys 方法返回一个数组。 +1!
  • 对我不起作用 - 无论是早期绑定还是后期绑定。 C'est la vie。
【解决方案2】:

这行得通:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-21
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多