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

╄→гoц情女王★ 提交于 2019-12-17 09:53:48

问题


What criteria should I use to decide whether I write VBA code like this:

Set xmlDocument = New MSXML2.DOMDocument

or like this:

Set xmlDocument = CreateObject("MSXML2.DOMDocument")

?


回答1:


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.

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 requires that a type library is referenced. Whereas CreateObject uses the registry.

CreateObject can be used to create an object on a remote machine.




回答2:


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.

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).

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.




回答3:


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.

The latter can be used to create an instance of an object using its ProgId without needing the type library. 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.



来源:https://stackoverflow.com/questions/170070/what-are-the-differences-between-using-the-new-keyword-and-calling-createobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!