views:

536

answers:

3

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

?

+2  A: 

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.

Joe
That answer is not correct.
Mitch Wheat
A: 

Also see answer to the early/late binding question.

Matthew Murdoch
+4  A: 

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.

Mitch Wheat