Visual Basic Expert SolutionsChapter 11OLE AutomationBy Edward B. Toupin |
This chapter introduces you to Object Linking and Embedding version 2.0, otherwise known in Visual Basic 4 as OLEv2.0. As you learn the basics of application integration with OLE, you will see how Visual Basic's tools can be used to give you a fully functional method of information-sharing between Windows-based applications.
We will first delve into OLE and its capabilities under Microsoft Windows 95. This topic provides a brief overview and history of OLE to give you an understanding of the premise for OLEv2.0. Once the basics of OLE are explained, we will take a look at object linking and embedding. This topic will explore the interaction between OLE servers and OLE containers as well as the different methods of integrating applications under Windows.
The remainder of the chapter explains some of the concepts involved in OLE automation and how it is utilized by Windows-based applications. To demonstrate some of the concepts of OLE, we will take a look at a few sample Visual Basic applications that utilize OLE to manipulate objects under Windows.
Note: Unless otherwise specified, all references to OLE and OLEv2.0 refer to Object Link and Embedding version 2.0.
In this chapter we will cover the following:
Windows 3.0 introduced a whole new method of working with the computer. Everything was at the user's fingertips in a graphical environment. However, the user was still working with many disparate applications. As applications that supported OLE—also known as OLE enabled applications—began to appear in the marketplace, the user was able to combine the functionality of different applications into one consolidated document.
OLE was originally developed on top of the Windows Dynamic Data Exchange (DDE) subsystem. DDE allows Windows-based applications to communicate with one another by exchanging simple messages and handles to globally allocated memory. Many applications had requirements that exceeded the capabilities of DDE, so users and vendors needed to develop extensions to support these requirements. The primary problem with DDE was that it was not robust enough to handle the morass of information exchanged between the multitude of evolving Windows-based applications.
To spearhead an endeavor to produce a more robust and efficient means of information exchange between applications, Microsoft and Aldus Corporation set forth a document outlining the initial specifications for OLE. As a result of the specification, Microsoft delivered OLEv1.0. The first applications to support OLEv1.0 were Microsoft Excel and Lotus Notes. As more and more vendors added OLEv1.0 capabilities to their applications, Microsoft found a need to develop a more sophisticated communications interface. Out of this need came the specifications for OLEv2.0.
Because everything under OLEv2.0 is centered around the contents of one document, a new form of computing—known as document-centric computing—came about. This new form of computing allows users to be more productive by integrating Windows applications and providing a common interface standard for all Windows applications.
Users and developers benefit considerably from this document-centric, component software approach to productivity. Instead of relying on the functionality of a single application, users now can utilize the functionality of many applications, or components, for their documents. For developers, the use of component software reduced the complexity of application development considerably by providing a Plug and Play approach to application development.
The premise of OLE is to change the view of productivity in the Windows environment. Instead of looking at many different applications and how they contribute to a finished product, document-centric computing focuses on the finished product. This view of computing frees the user from worrying about which application will meet the needs of a given task. The user is able to approach the document from the data standpoint instead.
For example, the user doesn't have to work specifically with a spreadsheet application to manipulate numbers, a drawing application to draw figures, or a word-processing application to manage text. With OLE the user can work in any OLE-enabled application and have access to numbers, figures, and text by using the functionality of spreadsheets, graphic applications, and word processors in one container application (see fig. 11.1).
Document-centric computing is based on the use of software components to supply functionality to a container application. Component software can be compared to a puzzle. The puzzle consists of many pieces of different shapes and colors. By assembling these pieces together you get one complete picture. With component software you have the ability to combine the functionality of many different applications together to produce a result consisting of each application's—or component's—data.
The ideas of component software usage and document-centric computing are very similar to the ideas of object-oriented applications. Object-oriented principles are focused on data rather than on function. The operations on data are encapsulated to hide the specifics of the data's functional requirements and provide a common calling interface to manipulate the data.
Note: Object-oriented, document-centric applications focus on data while structured applications are centered around the functionality of one application.
Word for Windows, for example, allows you to incorporate images from Microsoft Draw, spreadsheets from Excel, and numerous other such objects. However, Word for Windows does not have the built-in functionality to manage such objects by itself, but instead uses the functionality of the different software components. Each component provides a means of manipulating data, but all components have a common means of accessing the data. To contrast, a structured application, such as one of the older DOS-based word processors, could manage text only. The functionality of the application was designed to handle word-processing operations only and could not handle any other type of information.
As with every technological advancement, OLE comes a dictionary of buzzwords. The following terms are important throughout these next few chapters and are important in understanding the concepts of OLE.
An OLE server is an application that provides services to other OLE-enabled applications. Servers can be drawing programs, spreadsheets, communication applications, or any number of applications that provide a service.
OLE automation is the implementation of OLE that integrates applications through interapplication communications. Applications that support OLE automation expose their OLE objects to allow programming languages and other applications access to these objects.
When an application exposes its objects, you can programmatically manipulate the application from programming tools and other applications. You can develop in Visual Basic applications that can access the objects of OLE server applications as well as utilize the functionality of those applications within container applications.
An example of OLE automation would be in the contrast of spreadsheet macros and programming languages. In a spreadsheet, such as Microsoft Excel, you can write macros that automatically execute keystrokes that you would otherwise have to execute manually. These keystrokes may sort data or print reports to a printer. With OLE automation, you can write an application in Visual Basic that can perform operations with the Excel spreadsheet externally.
OLE automation offers the following advantages over implementations of macro languages included within some applications:
OLE applications that expose their objects to other applications allow other applications to incorporate the functionality of these objects. Because these objects are available, you can use the functionality of OLE servers in your own applications. This approach allows you to bring together the best functionality of multiple applications into one consolidated application. You can take components from different applications and plug them into your own, giving you a Plug and Play approach to development.
Using OLE automation from Visual Basic you can, for example, print a range of cells within a spreadsheet to a printer or change the values of a range of cells in a spreadsheet. Operations such as these are useful, for example, when you have an application that collects data from the stock market to provide up-to-the-minute information on market activity. You can incorporate the data of the stock market server application into Excel and use it to periodically update a graph for trending the market's activity for the day.
Prior to OLE, developers had to be concerned about the interfaces to applications as the applications were upgraded from one version to the next. With OLE, the object interfaces remain the same to give you a consistent calling convention for all versions of an application. In this way, container applications that you develop using OLE will not have to change drastically every time a server application is upgraded. This not only reduces the amount of time spent in development but also reduces the learning curve that would otherwise be involved in relearning the new server's interface calling methods.
An OLE automation object is an instance of a class within your application that you can manipulate programmatically. In an application that manages documents, the OLE automation objects might look like the diagram in figure 11.2.
Fig. 11.2 With an application object at the base of a hierarchy, objects contained within OLE-enabled applications constitute an application's OLE object hierarchy.
Figure 11.2 depicts a word-processing application that contains windows to manage documents for your word-processing activity. Each document contains characteristic sections, paragraphs, and words. These characteristics are also known as the properties of the document. Just as your hair, eyes, nose, and ears are your unique properties that describe you, the properties of the document describe the document to an application.
The document in figure 11.1 also contains other OLE objects, such as graphics and spreadsheets. These objects are created by two other applications and are stored in the document by a method known as embedding. Because the document application does not have the resources available to manage the graphic and spreadsheet objects alone, it uses the resources of the graphic and spreadsheet applications. The graphic image in the document is drawn and managed by a graphic application while the spreadsheet is managed by a spreadsheet application. As is shown, both of the objects contain properties that describe the characteristics of the objects.
To perform operations on each object in the illustration, each object has member functions, or methods, that uniquely apply to that object. The object becomes programmable when you expose those member functions for access by other applications.
Note: Properties contain information about the state (or characteristics) of an object while methods are member functions that perform an action on an object.
As demonstrated in figure 11.2, the properties for an OLE object describe the characteristics of the object. For example, a document can have sections, paragraphs, and words as well as dimensions, fonts, and color. A graphic can have shape, line, and fill properties as well as color. The methods of an OLE object allow you to perform actions on the object. The document object may include Print to print the document to a printer and Resize to adjust for different printer page sizes. The graphic object may include Scale to resize the graphic and Redraw to update the graphic.
When using OLE, container applications require information that describe the server applications and services available for an object. This type of information is supplied by the system registration database, or system registry. All OLE server applications must register themselves with the system registry before they can be used by any container applications. When registering themselves, they provide information as to the type of objects they provide, the file extensions they service, and the directory paths to the server.
The system registry contains information about applications stored on the computer for use by OLE as well as configuration information for the Windows environment on the current machine. This information replaces the INI files that accompanied many earlier applications and is a central store for all OLE applications as well as the Program Manager and File Manager.
For example, the File Manager uses the system registry to locate the server application of the file selected. When you double-click a file in a file list, the File Manager looks for the extension of the selected file in the system registry. Once located, the File Manager runs the server listed in the registry that services this file and loads the file into the server. For example, selecting a file named TEST.TXT would run Notepad and load TEST.TXT into Notepad for editing.
The database for the system registry is a binary file called REG.DAT and is located in the Windows directory. The application REGEDIT allows you to view and edit the information in the database to manage your machine. REGEDIT allows you to view all configuration information in a tree structure by using the following command:
As seen in figure 11.3, the application displays the tree of information for each OLE server class so that you can view and edit information associated with each application class.
Many server applications come with a text file with the extension REG. This file contains vital registration information for the server, which is registered in the system registry. To load this information manually, use the following command:
REGEDIT /S filename.REG
Many server applications automatically register themselves with the system registry when they are either installed or when they are first run. On occasion a server is not registered automatically. It is a good idea to perform this operation manually if this should occur so that you will have access to the server.
Object linking provides a means of linking an object of a server application into a container application. The linked object is managed by its server application, but the object is used by the container application. The container stores only a reference to the object of the server application.
Object embedding involves the placement of an object into a container application. Similar to linking, the object is still managed by a server application but it resides wholly in the container application. To follow object embedding is in-place activation. This method allows you edit an embedded object within a container application by incorporating the object's server's functionality within the container.
The OLE control provides an interface for OLE in Visual Basic and allows you to incorporate data into an application by linking or embedding that data from another application. The control can manage linked and embedded data as well as in-place activation and OLE automation either programatically or manually.
When you link an object into a container application you are inserting a placeholder for the object but not the actual object itself. This placeholder is a reference to the server application and object name that are used in the container application. For example, you can link a range of spreadsheet cells into a Visual Basic application. The data associated with the cells is stored in another file. The only reference to the spreadsheet information is a link to the data and an image of the data stored in an OLE control.
If you want to edit the linked spreadsheet cells, double-click the linked object in the OLE control. If not already running, the spreadsheet server application starts automatically and loads the linked cells. You can then edit those spreadsheet cells using the server application. The edited cells of the spreadsheet are then updated in the Visual Basic container application and stored in the OLE object.
The information stored in the spreadsheet server application is accessible not only by the Visual Basic application but also by any other application that has a link to the data. The linked information in the spreadsheet server application can be changed by any of the linked containers. For example, in figure 11.4, a spreadsheet is linked to a Visual Basic application and a Microsoft Word document. If the spreadsheet's data is changed by either application, the modified data appears in both the Visual Basic application and the Microsoft Word document.
Fig. 11.4 Linked objects are centrally available for access by multiple applications.
Linking an object from a server application into one or more container applications enables you to maintain a common data object for access by multiple container applications. Object linking is beneficial where you have multiple applications that use a central store of information. You have to edit the information one time only, and all containers that use the information are updated.
When you create an embedded object in an OLE control of a Visual Basic container application, the data associated with the embedded object is stored in the container application. When you save the contents of the container application to a file, the file contains the name of the application that produced the object, the object's data, and a Metafile image of the object.
When an object is embedded in an application, no application except for the container has access to the data in the embedded object. Embedding is useful when you want your container application to maintain data that is produced and edited in another application. When the user activates the object, the server application that created the object is invoked by the container application, and the object's data is opened for editing.
For example, in figure 11.5 we are opening the Microsoft Graph server application from a Visual Basic container application. The server is used to create the object, which is then stored, embedded, into the container application. The graph from Microsoft Graph is now native to Visual Basic and can be treated as though it were part of the Visual Basic container application.
Fig. 11.5 Embedded objects are wholly contained within container applications.
A variation to object embedding is called in-place activation, also known as visual editing. In-place activation enables you to edit an embedded object within the container application. As with embedding, the capabilities of the server application are used to edit the object; the functionality of the server application is incorporated into the container for the editing process. The one requirement for using in-place activation is that the container and server applications support OLE automation. If either of the two applications does not support automation, then you will not be able to use in-place activation on an embedded object.
With in-place activation, when you double-click an embedded object, the menus and toolbars of the server application replace the menus and toolbars of the container application. The container application inherits the functionality of the object's server application so that you may edit the object in-place—that is, you may edit the object where it sits within the container. When you complete editing the object, all menus of the container application are restored to the original state.
Figure 11.6 shows an Excel worksheet being edited in-place in a Visual Basic OLE control. The form in the figure contains an Excel spreadsheet object in a Visual Basic OLE control. Notice the menu is in the form inherited from the spreadsheet application to allow you to edit the spreadsheet object.
By incorporating OLE automation and in-place activation, you can add numbers, text, and equations to the cells as though you were actually working in the Excel application.
Note: If a server application supports in-place activation, its menus and functions will supersede the container application's menu and functions. If it does not support in-place activation, the server is loaded, and the object you are to edit is loaded into the server.
**
Visual Basic OLE control is an object within Visual Basic that provides an interface to the OLEv2.0 subsystem. The OLE control allows you to incorporate objects from server applications for use in a Visual Basic application. You can link, embed, and visually edit the object located in the OLE control.
The Plug and Play approach discussed earlier is made possible with the OLE object by allowing you to incorporate the functionality from many different applications into one container application. Not only can you incorporate the spreadsheet capabilities of Excel but you can also access the word-processing capabilities of Word for Windows and the drawing capabilities of Microsoft Draw into one consolidated application. This keeps you from having to write all of the base code otherwise required to perform operations already available in the many server applications that support OLEv2.0.
Designtime OLE controls in Visual Basic are specifically for editing and creating OLE objects within a Visual Basic container application. At designtime, you can place an OLE control into a form using the OLE tool of the toolbox, as shown in figure 11.7. Once you position the OLE control on the form, Visual Basic will load the Insert Object dialog box, shown in figure 11.8, so that you may select a class to add to the object.
The Insert Object dialog box (see fig. 11.8) allows you to embed or
link an object in the OLE control. If you select the Create New
radio button of the dialog box, you will be embedding an object in your
container application.
You may select a class from the Object Type list by double-clicking
the class or clicking the OK button. If the class supports in-place activation,
the form in which the OLE control is contained will acquire a menu from
that class server, and an image of the selected class will appear in the
OLE control. If the class does not support in-place activation, the server
for the selected class will be executed and appear for you to edit your
object. For example, selecting the Microsoft Excel 5.0 Worksheet places
an image of a spreadsheet in the control; selecting Microsoft Graph, however,
executes the graph application.
As shown in figure 11.9, if you select the Create from File radio
button, you will be selecting a particular file from your hard disk to
load as the object.
If you select the Link check box, a reference to the object will
be placed into your container so that it will be updated whenever it is
changed by the server application of the object. If you do not select the
Link check box, the image from the file will be loaded into the
OLE control. Changes will not be reflected, however, if the object's file
should be changed by the server. The latter is similar to embedding an
object in that the object from the file is wholly contained in the container.
As with object embedding, you may edit the object by double-clicking that
object to access the object's server.
At runtime there are several methods of the OLE control that you can use to embed and link an object into a container application. As you can see in figure 11.10, three command buttons on the form are programmed to manipulate the control.
The first button, Insert Object, executes the Insert_Click() subroutine in Listing 11.1 and accesses the Insert Object dialog box that you worked with at designtime. The method OLE1.InsertObjDlg opens the dialog box so that you may select an object to link or embed in the same manner as you did at runtime.
The second button, Embed Object, executes the Link_Click() subroutine in Listing 11.1 and allows you to dynamically embed an object into the OLE1 control of the form. You must provide the name of a source document that you want to embed into the application. This function bypasses the Insert Object dialog box and performs the embedding operation on the values you pass to the method. For example, OLE1.CreateEmbed "C:\USER\TESTSHT.XLS" loads the file TESTSHT.XLS and embeds it into the OLE1 control on the form.
To edit the embedded object, select the object with the right mouse button or double-click the object. Using the right mouse button accesses a floating menu from which you can select to edit or open the object's server. Double-clicking goes straight to the editing function of the object. If the server supports in-place activation, you can edit the object within the OLE control; otherwise, the server is started and you edit the object within the server application.
The third button, Link Object, executes the Embed_Click() subroutine in Listing 11.1 and allows you to dynamically link an object into the OLE1 control of the form. As with OLE1.CreateEmbed, OLE1.CreateLink "C:\USER\TESTSHT.XLS" uses the name of a source document that you want to link into the application. As with embedding, you can select the object with the right mouse button or double-click the object to edit. You cannot edit a linked object in-place because the object is not contained within the container as it is with embedding. When you edit the object, the server application for the object is started and the object is loaded into the server for editing.
Listing 11.1 Figure.MAK Creating an Embedded and a Linked Object
OLE automation is an industry standard that applications use to expose their OLE objects to development tools, macro languages, and other applications that support OLE automation. A spreadsheet application, for example, may expose a worksheet, chart, cell, or range of cells all as different types of objects. A word processor might expose objects such as application, document, paragraph, or sentence.
When an application supports OLE automation, the objects it exposes can be accessed by Visual Basic. You can use Visual Basic to manipulate these objects by invoking methods on the object or by getting and setting the object's properties. For example, if you created an OLE automation object named MyObj, you might write code such as this to manipulate the object:
To access another application's OLE objects, you have to provide a reference to the application's object library. The objects, functions, properties, and methods supported by an application are usually defined in the application's object library. For more information on the properties and methods supported by an application, refer to an application's documentation. In Visual Basic, shown in figure 11.11, follow these steps to load the object library of an application:
1. 1. From the Tools menu, choose References. The References
dialog box appears, allowing you to select which object libraries to include.
2. 2. Select the application reference or, if it is not listed, click
Browse and select the appropriate file.
An application's objects can be referenced without adding a reference to the application's object library. Adding the object library reference is preferable for the following reasons:
To access another application's objects, you must define a variable to use when referencing the methods and properties of the application. The variable is then provided a reference to an object when you open communications with that application. To create a variable, you must dimension a variable of type Object as follows:
This statement uses the Object data type of Visual Basic and creates a variable called Spread. Now you must use this variable to initiate a conversation with an application. This can be accomplished with the CreateObject() function that creates an object of a specified type and assigns that object to your variable Spread. Use the following syntax to specify an object to create:
Let's say there is a spreadsheet application named SPRDSHT.EXE that supports a worksheet object and a chart object. These objects would be defined as follows:
For other applications, refer to the application's documentation to get a list of supported objects. You can also look in the system registry, as shown in figure 11.12. As is shown, Excel supports application, chart, and sheet objects.
Once you know the type of object you want to create, use the Set keyword to assign the object returned by the CreateObject() function to the object variable. When the following statement is executed, the SPRDSHT application is started and a worksheet object is created:
If the application is already running, the current instance of the application is used. The worksheet object's image is not embedded or linked into the Visual Basic application but instead resides in and is maintained by the spreadsheet application.
Once a class is available, you can access the objects of the class. Accessing these objects involves calling member functions or changing properties of the objects from within Visual Basic. In figure 11.13, the Visual Basic application uses a globally declared object variable named Spread.
Fig. 11.13 Visual Basic can access classes and create instances of those classes in Microsoft Excel.
When the Create Sheet Object button (refer to fig. 11.13) is clicked, we use CreateObject() from Listing 11.2 to assign a sheet class of Excel to the Spread object variable. Using the Cells method of the sheet class, we place numbers at row 1-column 1 and row 1-column 2 and a formula at row 1-column 3. The final call to the Cells() method sets the Font.Bold property to True to bold the resulting value of the equation. The Quit Excel button uses the Spread.Application.Quit method to exit the Excel application and clear the Spread object.
Listing 11.2 Project1.MAK Visual Basic Application-Manipulating Sheet Objects Within Microsoft Excel.
Note: In figure 11.13, Excel was already running when the Visual Basic application was executed. Because Excel was running, OLE used the currently executing version. Otherwise, if Excel was not running it would have been started before the remainder of the code executed. If OLE had started the Excel application, it would have been invisible—the default startup state of an OLE automation server application. To make Excel visible, the Spread.Application.Visible = True statement would have been used immediately following the CreateObject() function.
Similar to object linking, you can access existing objects that reside in files saved by server applications. You can use the GetObject() function to activate an object that has been saved to a file.
The GetObject() function is similar to the CreateObject() function in that it initiates a conversation with an application. However, it does not create a new object. The GetObject() function uses an existing object and allows you to manipulate that object from within Visual Basic. For example, the function call GetObject("C:\EXCEL\FILES\FRATE2.XLS") will load the Excel spreadsheet application and load the file FRATE2.XLS into the spreadsheet for you. When you call the function with a path and filename, as with C:\EXCEL\FILES\FRATE2.XLS, OLE refers to the registry database to find out which application is associated with a file containing the XLS extension. The application, being Excel, is run and loaded with the file FRATE2.XLS for editing.
To activate an object from a file, first dimension an object variable as you did with CreateObject(), then call the GetObject() function using the following syntax:
GetObject (filename[, class])
The filename argument is a string containing the full path and name of the file you want to activate. For example, let's use SPRDSHT.EXE again and say that we created an object that was saved in a file called FRATE2.SPD. The following code invokes SPRDSHT.EXE, loads the file FRATE2.SPD, and assigns FRATE2.SPD to an object variable:
When you use GetObject() to activate an object, OLE determines which application to invoke and which object to activate from the system registry based on the file name you provide. Some files may support more than one class of object and require that you specify which application to use. For example, FRATE2.SPD may support an application object and a worksheet object, both of which are part of the same file. To specify which object in a file you want to activate, you use the optional Class parameter. Here's an example of activating the worksheet object in the file FRATE2.SPD:
If the filename argument is set to an empty string (""), the GetObject() function returns the currently active object of the class specified as the second argument. For example, the following code will return a reference to an object of the SPRDSHT.Worksheet class that may be currently running.
In figure 11.14, we are using a file that we saved from figure 11.13. As you can see, the basic structure of the code is similar except for the GetObject() function.
When the Link Sheet Object button is pressed, we use GetObject from Listing 11.3 to load the file TEMP.XLS into the Excel application. The resulting sheet reference is assigned to the Spread variable. Using the Cells() method of the Sheet class, we place numbers at row 1-column 1 and row 1-column 2. We are using the equation placed into the spreadsheet from the CreateObject() call of figure 11.13 to add the new numbers together and display the result in row 1-column 3. As before, the Quit Excel button uses the Spread.Application.Quit method to exit the Excel application and clear the Spread object. The primary difference between this application and the one mentioned in the section "Creating a New Object" is that the Visual Basic application is using an object, a sheet in this case, that already exists. The GetObject function uses classes of objects that are readily available and does not create a new object for its specific use.
Note: When you use GetObject(), OLE looks in the system registry to locate the server associated with the object you are referencing. OLE uses the extension of a filename you specify, such as XLS or TXT, and runs the server application that services that extension. The object you are referencing is then loaded into the server application for editing.
Listing 11.3 Project1.MAK Linking an Existing Object with GetObject
Note: In figure 11.14, Excel was already running when the Visual Basic application was executed. Because Excel was running, OLE used the currently executing version. Otherwise, if Excel was not running, it would have been started before the remainder of the code executed. If OLE had started the Excel application it would have been invisible, the default startup state of an OLE automation server application. To make Excel visible, use the Spread.Application.Visible = True statement immediately following the GetObject() function.
Once you have created a variable that references an OLE object, you can use the object in Visual Basic in the same way as any Visual Basic object. You use the object.property syntax that is normally used in Visual Basic to get and set the object's properties or to perform methods on an object. By calling to the methods and properties of and object, you can use the resources of the object as well as manipulate it for your application.
Once you initiate a conversation with an application and have an available object, you manipulate the properties of the object from within Visual Basic. After creating the object, for example, you could write code such as the following to change the current cell, insert text, and save the object to a file:
As you have seen, you can use the OLE control to create and display linked and embedded objects in a Visual Basic application. Some applications that supply objects support linking and embedding and also support OLE automation. If you use the OLE control to create a linked or embedded object and that object does support OLE automation, you can access that object's properties and methods in Visual Basic using the Object property. The Object property returns the object in the OLE control. This property refers to an OLE object in the same way an object variable created using the CreateObject() or GetObject() functions refers to an object.
For example, let's say an OLE control named OLE1 contains an object that supports OLE automation. Let's also say that this object has an Insert method, a Select method, and a Bold property. In this case, you could write the following code in Listing 11.4 to manipulate the OLE control's object:
Listing 11.4 Setting the Properties of a Visual Basic OLE Object
You assign values to OLE object properties in the same manner as that of a regular variable in Visual Basic. You place the object's variable and property name on the left side of an equation and the desired property setting on the right side, as in Listing 11.5.
Listing 11.5 Assigning Values to OLE Objects
The above code creates an object, ObjVar, of the class SprdSht.Worksheet. The code then sets the text of a cell at the row and position stored in RowPos and ColPos to the string "This is some test text.". This operation will work only if the object we created in CreateObject() supports the Cell() method, so it is a good idea to check the documentation of the application to determine which methods are supported by its objects.
Retrieving information from a property is just as simple as setting the value. In the following code, we are retrieving the text from ObjVar and storing it into the Variant variable X.
All arguments involved with OLE automation objects use the Variant data type. When retrieving a value from a property or method, OLE automation objects always return values of the Variant data type. If you use a variable with a data type other than Variant when assigning a property value or performing a method, the variable is coerced to the Variant data type.
In addition to getting and setting properties, you can manipulate an object by using the methods it supports. In a manner similar to that of executing Visual Basic methods on internal objects, you can access the methods of applications that expose their object for OLE automation.
Some object methods may return a value to the calling Visual Basic application while others do not return any values. Methods that do not return a value behave like a subroutine. If you assign such a method to a variable, an error occurs.
The code in Listing 11.6 uses a function called IsBold, which is a method of the Text property of ObjVar. The function returns a value to the Variant X, which is used to determine execution through the remainder of the application.
Listing 11.6 Performing Methods on OLE Objects
X = ObjVar.Text.IsBold
If X Then
ObjVar.Text = "The text is bold."
Else
ObjVar.Text = "The text is not bold."
End If
' This method requires two arguments.
ObjVar.Move XPos, YPos
Some OLE automation objects contain subobjects. A cell could be considered a subobject of a spreadsheet object. You can include multiple objects, properties, and methods on the same line of code using the dot syntax, just as you would with a Visual Basic object. For example, the following code is setting the FontBold property of the cell returned by the method Cell() of the ObjVar object.
All OLE automation objects support some method that closes the object and the application that created it. Because OLE objects can use a significant amount of memory in your Visual Basic application, it is a good idea to explicitly close an object when you no longer need it. To close an object, use the appropriate method, such as the following example:
The user can close an object using the application that created the object. When an object has been closed, either programmatically or by the user, any object variables that refer to the object are set to NULL. This NULL value represents that the object variable is no longer assigned an object.
If you define an object locally within a procedure and the variable loses scope when you leave the procedure, the object and its application are not closed. However, you can no longer use that object variable to refer to the object. Attempting to use the object variable will return the error Object Variable Not Set. If the application is still running and the object is still active, you can use the GetObject() function to assign another object variable to the object.
Even though you can perform a multitude of OLE operations from within Visual Basic applications, some features of objects supported by OLE cannot be accessed by Visual Basic applications. Such circumstances involve the limits on access to data that is specific or unique to an application. For example, Visual Basic cannot exchange user-defined types effectively with another application because that user-defined type may not be known to the other application. Passing an unknown type to another application can have unforeseen affects since the other application will not know how to handle the unknown data type. The following sections discuss some of these limitations.
Some OLE objects contain properties and methods that use arrays as arguments. Visual Basic has the following limitations when using arrays with OLE objects:
If you want to access an array returned from a property or user-defined type, you should use the LBound() and UBound() functions to determine the size of the array. Once the size is determined, you can access the individual elements of the array one at a time.
The code in Listing 11.7 increments I through each element of the array. Using I, the value of each array element is placed into Value, which can then be used in code that you require to use on the elements of the array.
Listing 11.7 Accessing Arrays within Specified Bounds
When calling an object's methods from Visual Basic you cannot use named arguments. A named argument is one that contains the name of the argument followed by the value of the argument. For example, the following lines of code use named arguments:
When calling a method using named arguments, you can pass the arguments in any order desired because the names of the arguments will correlate the values in the called method. In Visual Basic, however, you cannot use named arguments.
When calling from Visual Basic a method that supports named arguments, you must specify each argument being passed to the method in the order specified in the argument list of the called method. If you want to omit one of the optional argument for the method you should leave it blank.
A collection is an object that contains objects of one specific class. Many objects that support collections can be referenced in a singular form and a plural form. For example, a collection of menus for a particular application can be accessed using a Menu object and a Menus object. Collections are, however, usually accessed using the plural form. A collection of Row objects in a spreadsheet is referenced by Rows and a collections of a Cell object is referenced by Cells.
In order to determine the number of elements in a collection, many collections support a property called Count. This property returns the number of elements of the specific type in the collection. For example, the property ObjVar.Rows.Count returns the number of rows in the object variable ObjVar.
To access an individual element of a collection you use an index in a manner similar to that of an array. For example, Rows(1) returns the first row of an object while Rows(Rows.Count) returns the last row.
When accessing an OLE collection object you may encounter the following two problems:
Some OLE collection objects allow access to methods that enable you to iterate through the collections. If an object does not explicitly provide methods for doing this, you may not be able to cycle through an object's collections in your Visual Basic program.
If you know that a collection indeed uses a numeric subscript, you can iterate through it. You'll need to provide error trapping, however, because you don't know if the subscripts are contiguous.
To add a twist to accessing collections, some collections do not use numeric subscripts. For example, if an object has a collection of fonts, instead of using numeric subscripts, the Fonts collection might use string subscripts. In code, the collection might look like this:
In essence, collections may be seen as arrays that may be accessed either by numeric offset or by a textual index. In either case, the collection allows you to reference any number of like elements available within a given application.
In this chapter we discussed the elements of OLE automation and how it is implemented with Visual Basic 4. OLE servers (or object applications) provide methods and properties that can be manipulated from OLE clients (or controlling applications). From Visual Basic you can use the OLE control to embed or link objects as well as perform automation on those objects. You can also create instances of objects programatically to access the members and methods of those objects.
For more information, refer to the following chapters:
| Previous Chapter | Next Chapter | Search | Table of Contents | Book Home Page |
| Buy This Book | Que Home Page | Digital Bookshelf | Disclaimer |
To order books from QUE, call us at 800-716-0044 or 317-361-5400.
For comments or technical support for our books and software, select Talk to Us.
© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.