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

后端 未结 1 1017
灰色年华
灰色年华 2020-12-19 18:49

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 an

相关标签:
1条回答
  • 2020-12-19 19:34

    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:


    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:

    • Early and Late Binding (my site)
    • Early Binding vs Late Binding (ex-SO Documentation)
    0 讨论(0)
提交回复
热议问题