Late Binding

When you declare a variable As Object or As Variant, Visual Basic uses late binding. Late binding is also known as run-time binding. Late binding simply means that Visual Basic doesn't associate your object variable with the Automation object at design time but waits until you actually run the procedure. Because the declaration As Object or As Variant is very general in nature, Visual Basic cannot determine at compile time that the object your variable refers to indeed has the properties and methods your VBA procedure is using.

The following declaration results in late binding of the specified object: Dim mydoc As Object

The advantage of late binding is that all the Automation objects know how to use it.

The disadvantage is that there is no support for built-in constants. Because Visual Basic does not know at design time the type library your object is referring to, you must define constants in your code by looking up the values in the application's documentation. Also, querying an application at run time can slow down the performance of your solution.

Note: Late binding makes it possible to access objects in a type library of another application without first establishing a reference to the object library. Use late binding if you are uncertain that your users will have the referenced type libraries installed on their machines.

The following procedure demonstrates how to use late binding to print out a Word document.

Sub PrintWordDoc()

Dim objWord As Object

Set objWord = CreateObject("Word.Application") With objWord

.Visible = True

.Documents.Open "C:\Hello.doc" .Options.PrintBackground = False .ActiveDocument.PrintOut End With objWord.Documents.Close objWord.Quit Set objWord = Nothing End Sub

0 0

Post a comment