Tuesday 20 December 2011

Late & Early Binding VBA

Recently I came across this term of bindings (Late/Early). Being a VBA developer for past few years and having worked with the concept numerous times, I realized lately it as Late/Early Binding. (I am bad with names and terms, I must confess)
So the concept goes as follows according to MSDN:

Early binding (MSDN):
An object is early bound when it is assigned to a variable declared to be of a specific object type

Example:
Sub test_LateEarlyBindings()

     'Early Binding
     Dim fs As Scripting.FileSystemObject

     Set fs = New Scripting.FileSystemObject

End Sub



Late Binding (MSDN):
An object is late bound when it is assigned to a variable declared to be of type Object.

Example:
Sub test_LateEarlyBindings()

    'Late Binding
    Dim fs As Object
    
    Set fs = CreateObject("Scripting.FileSystemObject")


End Sub

The advantage of early binding over late binding is they allow compiler to allocate memory and perform optimization before an application executes. In addition to this when objects are declared explicitly as their types the VBA editor provide a helpful intellisense to assist the developer with object associated methods and properties, which becomes quite difficult in terms of late bound objects.

 

Then why use late binding ???

I came to know the utility of the late binding when I had to develop VBA based solutions which addressed users with varying office application versions (2003/2007).
Sub test_LateEarlyBindings()

    'Early Binding
    Dim outlookApp As Outlook.Application
    
    Set outlookApp = New Outlook.Application


End Sub

In the above code the instantiation of the Outlook object within VBA if flexible to work with different version of outlook installed on user PC (2003/2007) as this is instantiated as late bound object to the variable. This code relives the developer to explicitly add the outlook reference to the solution as it is picked up at run time and provides higher flexibility to the solution. This case was also sometimes used by myself when referencing the PDFCreator library for generating PDF reports.

Coding Tip (Late bound object):

As we discussed earlier since the late bound object doesn’t offer intellisense help while coding, I becomes tedious to develop the functionality and call upon the right name of methods and properties associated with the object.
A simple tip to overcome this problem is, initially develop the code as an early bound object and once the required functionality works well replace the object instantiation part by “CreateObject” method and uncheck the external references relating to the object from the reference library of the VBA project.

Refrences: 
Link: http://msdn.microsoft.com/en-us/library/0tcf61s1.aspx

No comments: