Using the New Keyword

Instead of using the CreateObject function to assign a reference to another application, you can use the New keyword. The New keyword tells Visual Basic to create a new instance of an object, return a reference to that instance, and assign the reference to the object variable being declared. For example, you can use the New keyword in the following way:

Dim objWord As Word.Application Set objWord = New Word.Application

Dim objAccess As Access.Application Set objAccess = New Access.Application

Object variables declared with the New keyword are always early-bound. Using the New keyword is more efficient than using the CreateObject function. Each time you use the New keyword, Visual Basic creates a new instance of the application. If the application is already running and you don't want to start another instance, you should use the GetObject function.

The New keyword can also be used to create a new instance of the object at the same time that you declare its object variable. For example:

Dim objWord As New Word.Application

Notice that when you declare the object variable with the New keyword in the Dim statement, you do not need to use the Set statement. However, this method of creating an object variable is not recommended because you lose control over when the object variable is actually created. Using the New keyword in the declaration statement causes the object variable to be created even if it isn't used. Therefore, if you want control over when the object is created, always declare your object variables using the following syntax:

Dim objWord As Word.Application Set objWord = New Word.Application

The Set statement can be placed further in your code where you need to use the object. The following section of this chapter demonstrates how to use the New keyword to create a new instance of Microsoft Outlook and write your contact addresses to an Excel worksheet.

0 0

Post a comment