Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

Set xmlDocument = New MSXML2.DOMDocument

or like this:

Set xmlDocument = CreateObject("MSXML2.DOMDocument")

?

like image 488
Matthew Murdoch Avatar asked Oct 04 '08 09:10

Matthew Murdoch


1 Answers

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.

like image 127
JimmyPena Avatar answered Sep 30 '22 12:09

JimmyPena