Automation Add-insWhen initially introduced in Excel 2000, the functions contained in COM Add-ins could not be called directly from a worksheet. In Excel 2002, Microsoft added Automation Add-ins to solve that problem. An automation add-in is nothing more than an ActiveX DLL that contains a public function. Creating the IfError Automation Add-inChapter 5 Function, General and Application-Specific Add-ins introduced the IFERROR() function, written as a VBA user-defined function. In Chapter 19 XLLs and the C API, it was rewritten in C, for best performance. We can re-create this as an automation add-in to improve on the performance of the VBA version, although not as much as the C version. This can be thought of as a compromise, improving the performance but keeping the simplicity of the Visual Basic code. To create the add-in, start a new empty ActiveX DLL project in VB6, change the project name to ProExcel and the class name to Functions, then copy in the code shown in Listing 21-6. Listing 21-6. The IFERROR User-Defined FunctionNote that this is exactly the same code as Listing 5-3 in Chapter 5 Function, General and Application-Specific Add-ins. Click File > Make ProExcel.DLL to build the DLL. Using the IfError Automation Add-inOpen Excel 2002, click the Tools > Add-ins menu and click the Automation button. The Automation Servers dialog lists every registered ActiveX DLL on the PC, including the one we just created. Select the entry for ProExcel.Functions and click OK. It should now be listed in the normal Tools > Add-ins dialog. Click OK to return to the worksheet. The function can now be called directly from the worksheet just like any other function:
Accessing the Excel Application Object from an Automation Add-inWhen creating anything more than a trivial function, we will usually want to use some of Excel's worksheet functions within the procedure. Alternatively, we may need to mark our function as volatile, so it is called every time the sheet is recalculated. Both of these situations require us to interact with the Excel Application object.If we add one of the same Add-in Designer classes to our project that we used for COM Add-ins, Excel will call the OnConnection event when the DLL is first loaded, giving us the opportunity to store a reference to the Application object. We can then use that object within our functions. The following steps explain how to set it up:
The first time any of the functions in the add-in is used, Excel loads the add-in, calls the OnConnection procedure, then calls the function. In the OnConnection procedure, we store a reference to the Excel Application object, which we use within the functions contained in the class. |