声明没有Microsoft脚本运行时的字典 [英] Declare a dictionary without Microsoft Scripting Runtime

查看:211
本文介绍了声明没有Microsoft脚本运行时的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实有一个主Excel VBA程序,它调用后期绑定的子例程,因为使用工具 - >参考 - > Microsoft脚本运行时是不可行的,因为知道的原因。

 主程序
Dim Dict As Object
Set Dict = CreateObject(Scripting.Dictionary)
调用SubRoutine(Dict)

下一步是将字典发送到我的SubRoutine

  Public Sub SubRoutine(Dict As Scripting.Dictionary)
做某事
end

将导致编译错误,这是预期的,因为我没有对Microsoft Scripting Runtime的引用。
现在的问题是,如何解决这个问题来声明字典。
通过使用

  Set Dict = CreateObject(Scripting.Dictionary)

将空字典。

解决方案

您正在有效地询问如何使用晚期绑定而不是早期绑定(一篇文章讨论此更多文章)。



而不是以下内容,这意味着早期绑定(即设置对Microsoft Scripting Runtime库的显式引用):

  Public Sub SubRoutine(Dict As Scripting.Dictionary)

您需要将Sub的参数声明为通用的 Object 类型,因为使用后期绑定(即没有显式引用集,让程序在运行时显示出来) :

  Public Sub SubRoutine(Dict As Object)

想想 Object 作为一个可以容纳任何类型的对象的容器,但一旦将对象放在其中,例如一个字典,那就是它变成了什么。在本地窗口中,它将显示为对象/字典,这意味着容器是 Object (这在很大程度上与您无关,不要担心这个),但性质/行为是字典(这是你想要的)。



附录:这句最后一句不像我以为那样真实。请参阅后续问题中的解释:使用晚期绑定但不能早期绑定时使用词典时的运行时错误


I do have a main Excel VBA Programm which calls a Sub Routine with late binding because using the Tools->References-> Microsoft Scripting Runtime is not feasable for the know reasons.

Main Program    
Dim Dict As Object
Set Dict = CreateObject("Scripting.Dictionary")
Call SubRoutine(Dict)

next step is to send the dictionary to my SubRoutine

Public Sub SubRoutine(Dict As Scripting.Dictionary)
do something
end

will result in compiling error which is expected because I do not have the reference to the Microsoft Scripting Runtime. The Questions is now, how to solve that problem to declare the dictionary. By using

Set Dict = CreateObject("Scripting.Dictionary")

Would empty the dictionary.

解决方案

You are effectively asking how to use late binding instead of early binding (one article discussing this, more articles).

Instead of the following, which implies early binding (i.e. setting an explicit reference to the Microsoft Scripting Runtime library):

Public Sub SubRoutine(Dict As Scripting.Dictionary)

you need to declare your Sub's parameter as a generic Object type, as is required when using late binding (i.e. no explicit reference set, letting the program figure things out at runtime):

Public Sub SubRoutine(Dict As Object)

Think of Object as a container that can hold any kind of object — but once you put an object in it, e.g. a Dictionary, then that's what it becomes. In the Locals window it will appear as Object/Dictionary, meaning the container is Object (which is largely irrelevant to you, don't worry about this) but the nature/behaviour is Dictionary (which is what you want).

Addendum: This last sentence isn't quite as true as I thought it was. See explanation in follow-up question: Runtime Error with Dictionary when using late binding but not early binding

这篇关于声明没有Microsoft脚本运行时的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆