Late Binding vs Early Binding in VBA - (CreateObject() vs New)

2.3k views Asked by At

I'm trying to use VBA code to invoke a protected API which need authentication with OAuth2. Once I try to open a URL, I'm redirected to the ADFS page for authentication and than I come back.

Now for some applications using CreateObject("InternetExplorer.Application") and the .Navigate URL works fine, for other web app I need to use New InternetExplorerMedium in order to have the code working.

Can you tell me the differences between these objects and why some websites work with one and some work with the other?

Thank you

1

There are 1 answers

10
Vityata On

This way of referring to objects is called "Early" and "Late Binding". From MSDN:

The Visual Basic compiler performs a process called binding when an object is assigned to an object variable.

An object is early bound when it is assigned to a variable declared to be of a specific object type. Early bound objects allow the compiler to allocate memory and perform other optimizations before an application executes.

By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object, but lack many of the advantages of early-bound objects.

You should use early-bound objects whenever possible, because they allow the compiler to make important optimizations that yield more efficient applications. Early-bound objects are significantly faster than late-bound objects and make your code easier to read and maintain by stating exactly what kind of objects are being used.

TL DR:

The difference is that in early binding you get intellisense and compiling time bonus, but you should make sure that you have added the corresponding library.


  • Example usage of late binding:

Sub MyLateBinding()

    Dim objExcelApp     As Object
    Dim strName         As String

    'Definition of variables and assigning object:
    strName = "somename"
    Set objExcelApp = GetObject(, "Excel.Application")

    'A Is Nothing check:
    If objExcelApp Is Nothing Then Set objExcelApp = CreateObject("Excel.Application")

    'Doing something with the Excel Object
    objExcelApp.Caption = strName

    MsgBox strName

End Sub

  • Example usage of early binding:

First make sure that you add the MS Excel 16.0 Object Library from VBE>Extras>Libraries:

enter image description here


Sub MyEarlyBinding()

    Dim objExcelApp     As New Excel.Application
    Dim strName         As String

    'Definition of variables and assigning object:
    strName = "somename"

    'A IsNothing check:
    If objExcelApp Is Nothing Then Set objExcelApp = CreateObject("Excel.Application")

    'Doing something with the Excel Object
    objExcelApp.Caption = strName

    MsgBox strName

End Sub

Related articles: