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

前端 未结 3 1028
离开以前
离开以前 2020-12-01 21:27

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

Set xmlDocument = New MSXML2.DOMDocument

or like this:

<         


        
3条回答
  •  日久生厌
    2020-12-01 22:12

    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.

提交回复
热议问题