Part III: More-Advanced Access Techniques
796
Creating a new instance with CreateObject
In addition to creating an instance of an object library by using the New keyword, you can create
an instance of an object library by using the CreateObject function. You use the Create
Object function to create instances of object libraries that do not support the New keyword. To
use the CreateObject function, first declare a variable of the type that you want to create. Then
use the Set statement in conjunction with the CreateObject function to set the variable to a
new instance of the object library.
Late binding is often used with Automation servers that don’t support early binding, or when the
users seldom work with the Automation server. In the latter case, a user may be better off with late
binding because his computer spends the time setting up and binding to an Automation server
only when it’s needed. It’s also a good idea if the application will be used by a number of users
who may not all have the same version of the Automation server on their computers.
Here’s a simple example of late-binding to Microsoft Outlook and displaying the Outlook calendar.
Public Sub DisplayOutlookCalendar()
Dim ObjOutlook As Object
Dim ObjNamespace As Object
On Error Resume Next
‘Late binding:
Set ObjOutlook = GetObject(, “Outlook.Application”)
If Err.Number = 429 Then
‘Outlook is not running on this
‘computer, so start a new instance:
Set ObjOutlook = CreateObject(“Outlook.application”)
End If
On Error GoTo 0 ‘Disable error trapping
Set ObjNamespace = ObjOutlook.GetNamespace(“MAPI”)
If ObjOutlook.ActiveExplorer Is Nothing Then
ObjOutlook.Explorers.Add _
(ObjNamespace.GetDefaultFolder(9), 0).Activate
Else
Set ObjOutlook.ActiveExplorer.CurrentFolder = _
ObjNamespace.GetDefaultFolder(9)
ObjOutlook.ActiveExplorer.Display
End If
Set ObjNamespace = Nothing
Set ObjOutlook = Nothing
End Sub
This code runs rather slowly on most computers. The slow performance is not the result of late
binding. Instead, it’s because Outlook is a pretty big application and requires a lot of CPU cycles
and memory to get up and running.
One very big difference between early and late binding is that late binding doesn’t require an
object library reference. When the code in this example runs, the VBA engine in Access passes the