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")
?
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")
?
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.
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.
As long as the variable is not typed as object
is the same as
both use early binding. Whereas
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.