简体   繁体   English

使用New关键字和在Excel VBA中调用CreateObject有什么区别?

[英]What are the differences between using the New keyword and calling CreateObject in Excel VBA?

What criteria should I use to decide whether I write VBA code like this: 我应该使用什么标准来决定是否像这样编写VBA代码:

Set xmlDocument = New MSXML2.DOMDocument

or like this: 或者像这样:

Set xmlDocument = CreateObject("MSXML2.DOMDocument")

?

As long as the variable is not typed as object 只要变量不是作为对象键入的

Dim xmlDocument as MSXML2.DOMDocument
Set xmlDocument = CreateObject("MSXML2.DOMDocument")

is the same as 是相同的

Dim xmlDocument as MSXML2.DOMDocument
Set xmlDocument = New MSXML2.DOMDocument

both use early binding. 都使用早期绑定。 Whereas

Dim xmlDocument as Object
Set xmlDocument = CreateObject("MSXML2.DOMDocument")

uses late binding. 使用后期绑定。 See MSDN here . 在此处查看MSDN。

When you're creating externally provided objects, there are no differences between the New operator, declaring a variable As New, and using the CreateObject function. 在创建外部提供的对象时,New运算符,声明变量As New和使用CreateObject函数之间没有区别。

New requires that a type library is referenced. New要求引用类型库。 Whereas CreateObject uses the registry. 而CreateObject使用注册表。

CreateObject can be used to create an object on a remote machine. CreateObject可用于在远程计算机上创建对象。

You should always use 你应该经常使用

Set xmlDocument = CreateObject("MSXML2.DOMDocument")

This is irrelevant to the binding issue. 这与绑定问题无关。 Only the declaration determines the binding. 只有声明才能确定绑定。

Using CreateObject exclusively will make it easier to switch between early and late binding, since you only have to change the declaration line. 独占使用CreateObject可以更容易地在早期和晚期绑定之间切换,因为您只需要更改声明行。

In other words, if you write this: 换句话说,如果你这样写:

Dim xmlDocument As MSXML2.DOMDocument
Set xmlDocument = CreateObject("MSXML2.DOMDocument")

Then, to switch to late binding, you only have to change the first line (to As Object ). 然后,要切换到后期绑定,您只需要更改第一行(到As Object )。

If you write it like this: 如果你这样写:

Dim xmlDocument As MSXML2.DOMDocument
Set xmlDocument = New MSXML2.DOMDocument

then when you switch to late binding, you have to change both lines. 然后当你切换到后期绑定时,你必须改变两行。

For the former you need to have a reference to the type library in your application. 对于前者,您需要在应用程序中引用类型库。 It will typically use early binding (assuming you declare your variable as MSXML2.DOMDocument rather than as Object, which you probably will), so will generally be faster and will give you intellisense support. 它通常会使用早期绑定(假设你将变量声明为MSXML2.DOMDocument而不是Object,你可能会这样),所以通常会更快并且会给你智能感知支持。

The latter can be used to create an instance of an object using its ProgId without needing the type library. 后者可用于使用其ProgId创建对象的实例,而无需类型库。 Typically you will be using late binding. 通常,您将使用后期绑定。

Normally it's better to use "As New" if you have a type library, and benefit from early binding. 通常情况下,如果您有类型库,最好使用“As New”,并从早期绑定中受益。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM