MS-Access / Getting Started

Late Binding

During development, using early binding is easier because it provides IntelliSense. For deployment, however, late binding is often preferred because code continues to compile regardless of whether a reference is missing. In addition, a runtime error is displayed when you try to create an object if the object is not installed. It's often said that there is a performance penalty when using late binding compared to early binding, however, we find that this is negligible with today's modern hardware.

In late binding, variables are defined as Object instead of the strongly typed data type for an object. For example, if you were automating objects in the Excel 2007 object model, you might have code that looks something like this:

Dim objXL 	As Excel.Application
Dim objBook 	As Excel.Workbook
Dim objSheet 	As Excel.Worksheet
' Launch Excel
Set objXL = New Excel.Application

With late binding, this becomes:

Dim objXL 	As Object ' Excel.Application
Dim objBook 	As Object ' Excel.Workbook
Dim objSheet 	As Object ' Excel.Worksheet
' Launch Excel
Set objXL = CreateObject("Excel.Application")

Notice that we've changed the variable declarations of the objects to use the Object data type in VBA. We still like to include comments in the code for documentation so that we will always know what we're working with. If the CreateObject function fails, it will throw runtime error 429.

With late binding, you may also consider using the IsNothing function calling a method on an object. For example, to open a workbook in Excel using late binding, you might write it something like this:

Dim objXL 	As Object ' Excel.Application
Dim objBook 	As Object ' Excel.Workbook
Dim objSheet 	As Object ' Excel.Worksheet
' Launch Excel
Set objXL = CreateObject("Excel.Application")
' Get the workbook
If (Not IsNothing(objXL)) Then
    Set objBook = objXL.Workbooks.Open("<PathToWorkbook.xls>")
End If

As a reminder, the IsNothing function is defined as follows:

Public Function IsNothing(obj As Object) As Boolean
    IsNothing = (obj Is Nothing)
End Function
[Previous] [Contents] [Next]