Question posted 2008 · +6 upvotes
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")
?
Accepted answer +7 upvotes
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.
3 code variants in this answer
- Variant 1 — 2 lines, starts with
Dim xmlDocument as MSXML2.DOMDocument - Variant 2 — 2 lines, starts with
Dim xmlDocument as MSXML2.DOMDocument - Variant 3 — 2 lines, starts with
Dim xmlDocument as Object
Top excel-vba Q&A (6)
- How to clear the entire array? +58 (2010)
- How to change Format of a Cell to Text using VBA +55 (2011)
- Download attachment from Outlook and Open in Excel +43 (2012)
- Can a VBA function in Excel return a range? +36 (2009)
- 2 Dimensional array from range +34 (2013)
- Hiding an Excel worksheet with VBA +33 (2009)
excel-vba solutions on this site
.