CreateObject Function

Description

Creates an OLE Automation object.

Syntax

CreateObject(class)

The class argument uses the syntax “appname.objecttype” and has these parts:

Part Description
appname The name of the application providing the object.
objecttype The type or class of object to create.


Remarks

Every application that supports OLE Automation provides at least one type of object. For example, a word processing application may provide an application object, a document object, and a toolbar object.

To create an OLE Automation object, assign the object returned by CreateObject to an object variable:


Dim WordBasicObject As ObjectWordBasicObject = CreateObject("Word.Basic")

When this code is executed, the application creating the object is started (Microsoft Word in this example). If it is already running, a new instance of the application is started, and an object of the specified type is created. Once an object is created, you reference it in code using the object variable you defined. In the above example, you access properties and methods of the new object using the object variable, WordBasicObject. For example:


WordBasicObject.Insert "Hello, world.".FilePrint.FileSaveAs "C:\DOCS\TEST.DOC"

Similarly, you can pass the object returned by the CreateObject function to a function expecting an object as an argument. For example:


Call MySub (CreateObject("Word.Basic"))

Note Use CreateObject when there is no current instance of the object. If there is a current instance, or if you want to start the application and have it load a file, you can use the GetObject function.

If an object has registered itself as a single-instance object (for example, the Word.Basic object in Microsoft Word 6.0), only one instance of the object is created, no matter how many times CreateObject is executed.

See Also

GetObject Function, Set Statement.

Example

This example uses the CreateObject function to set a reference (xlApp) to Microsoft Excel. It uses the reference to access the Visible property of Microsoft Excel, then uses the Quit method of Microsoft Excel to close it. Finally, the reference itself is released.


Dim xlApp As Object    ' Declare variable to hold the reference.
    xlApp = CreateObject("excel.application").Visible = True    ' You may have to set Visible property to True
        ' if you want to see the application.
        ' Use xlApp to access Microsoft Excel's 
        ' other objects..Quit    ' When you finish, use the Quit method to close xlApp = Nothing    ' the application, then release the reference.