Chapter 45. Creating Custom Excel Add-Ins

<feature><title>In This Chapter</title>
</feature>

For developers, one of the most useful features in Excel is the capability to create add-ins. This chapter discusses this concept and provides a practical example of creating an add-in.

What Is an Add-In?

Generally speaking, an add-in is something that’s added to software to give it additional functionality. Excel includes several add-ins, including the Analysis ToolPak and Solver. Some add-ins (the Analysis ToolPak, discussed in Chapter 38, is one example) provide new worksheet functions that you can use in formulas. Ideally, the new features blend in well with the original interface so that they appear to be part of the program.

Excel’s approach to add-ins is quite powerful because any knowledgeable Excel user can create add-ins from workbooks. An Excel add-in is basically a different form of a workbook file. Any Excel workbook can be converted into an add-in, but not every workbook is a good candidate for an add-in.

What distinguishes an add-in form a normal workbook? Add-ins, by default, have an .xlam extension In addition, add-ins are always hidden, so you can’t display worksheets or chart sheets that are contained in an add-in. But, you can access its VBA procedures and display dialog boxes that are contained on UserForms.

The following are some typical uses for Excel add-ins:

  • To store one or more custom worksheet functions. When the add-in is loaded, you can use the functions like any built-in worksheet function.

  • To store Excel utilities. VBA is ideal for creating general-purpose utilities that extend the power of Excel. The Power Utility Pak that I created is an example.

  • To store proprietary macros. If you don’t want end users to see (or modify) your macros, store the macros in an add-in and protect the VBA project with a password. A user can use the macros, but they can’t view or change them unless the user knows the password. An additional benefit is that the add-in doesn’t display a workbook window, which can be distracting.

As previously noted, Excel ships with several useful add-ins (see the sidebar “Add-Ins Included with Excel”), and you can acquire other add-ins from third-party vendors or the Internet. In addition, Excel includes the tools that enable you to create your own add-ins. I explain this process later in the chapter (see “Creating Add-Ins”).

Working with Add-Ins

The best way to work with add-ins is to use Excel’s Add-In Manager. To display the Add-In Manager:

  1. Choose Office Working with Add-Ins Excel Options

  2. In the Excel Options dialog box, select the Add-Ins category

  3. At the bottom of the dialog box, select Excel Add-Ins from the Manage list and click Go.

Excel displays its Add-Ins dialog box, shown in Figure 45.1. The list box contains all the add-ins that Excel knows about. Those checked are currently open. You can open and close add-ins from this dialog box by selecting or deselecting the check boxes.

The Add-Ins dialog box.

Figure 45.1. The Add-Ins dialog box.

Caution

You can also open most add-in files can by choosng Office Caution Open. After an add-in is opened, however, you can’t choose Office Caution Close to close it. The only way to remove the add-in is to exit and restart Excel or to write a macro to close the add-in. Therefore, you’re usually better off opening the add-ins by using the Add-Ins dialog box.

The user interface for some Add-ins (including those included with Excel) may be integrated into the Ribbon. For example, when you open the Analysis ToolPak add-in, you access these tools by choosing Formulas Solver Add-In: Solutions Solver Add-In: Data Analysis.

New Feature

If you open an add-in created in a previous version of Excel, any user interface modifications made by the add-in will not appear as they were intended to appear. Rather, you must access the user interface items (menus and toolbars) by choosing Add-Ins New Feature Menu Commands or Add-Ins New Feature Custom Toolbars. It’s likely that most add-in developers will create a new version of their add-in that uses the new Ribbon interface.

Why Create Add-Ins?

Most Excel users have no need to create add-ins. But if you develop spreadsheets for others—or if you simply want to get the most out of Excel—you may be interested in pursuing this topic further.

The following are several reasons why you may want to convert your Excel workbook application to an add-in:

  • To avoid confusion. If an end user loads your application as an add-in, the file isn’t visible in the Excel window—and, therefore, is less likely to confuse novice users or get in the way. Unlike a hidden workbook, an add-in can’t be unhidden.

  • To simplify access to worksheet functions. Custom worksheet functions stored in an add-in don’t require the workbook name qualifier. For example, if you have a custom function named MOVAVG stored in a workbook named Newfuncs.xlsm, you have to use a syntax such as the following to use this function in a different workbook:

    =NEWFUNC.XLSM!MOVAVG(A1:A50)

    But if this function is stored in an add-in file that’s open, the syntax is much simpler because you don’t need to include the file reference:

    =MOVAVG(A1:A50)
  • To provide easier access. After you identify the location of your add-in, it appears in the Add-Ins dialog box and can display a friendly name and a description of what it does.

  • To permit better control over loading. You can automatically open add-ins when Excel starts, regardless of the directory in which they’re stored.

  • To omit prompts when unloading. When an add-in is closed, the user never sees the Save Change In prompt because changes to add-ins aren’t saved unless you specifically do so from the VB Editor window.

Creating Add-Ins

Technically, you can convert any workbook to an add-in. But not all workbooks benefit from this conversion. In fact, workbooks that consist only of worksheets (that is, not macros or custom dialog boxes) become unusable because add-ins are hidden.

Workbooks that benefit from conversion to an add-in are those with macros. For example, you may have a workbook that consists of general-purpose macros and functions. This type of workbook makes an ideal add-in.

These steps describe how to create an add-in from a workbook.

  1. Develop your application and make sure that everything works properly.

  2. Choose Office Creating Add-Ins Prepare Creating Add-Ins Properties to display the Properties panel above your worksheet, enter a brief descriptive title in the Title field, and then enter a longer description in the Comments field. This step isn’t required, but it makes installing and identifying the add-in easier. To close the Properties panel, click its close button (X).

  3. Lock the VBA project. This optional step protects the VBA code and UserForms from being viewed. You do this in the VB Editor, using the Tools Creating Add-Ins projectname Properties command (where projectname corresponds to your VB project name). In the dialog box, click the Protection tab and select Lock Project For Viewing. If you like, you can specify a password to prevent others from viewing your code.

  4. Save the workbook as an add-in file by choosing Office Creating Add-Ins Save As and selecting Excel Add-In (*.xlam) from the Save As Type drop-down list. By default, Excel saves your add-in in your AddIns directory. But you can override this location and choose any directory you like.

Note

After you save the workbook as an add-in, the original (non-add-in) workbook remains active. You should close this file to avoid having two macros with the same name.

After you create the add-in, you need to install it:

  1. Choose Office Note Excel Options Note Add-Ins.

  2. Select Excel Add-Ins from the Manage drop-down list and click Go to display the Add-Ins dialog box.

  3. In the Add-Ins dialog box, click the Browse button to locate the XLAM file that you created, which installs the add-in. The Add-Ins dialog box uses the descriptive title that you provided in the Properties panel..

Note

You can continue to modify the macros and UserForms in the XLAM version of your file. Because the add-in doesn’t appear in the Excel window, you save your changes in the VB Editor by choosing Office Note Save.

An Add-In Example

This section discusses the steps to create a useful add-in from the change case.xlsm workbook I covered in Chapter 41. This workbook contains a UserForm that displays options that change the text case of selected cells (uppercase, lowercase, or proper case). Figure 45.2 shows the add-in in action.

This dialog box enables the user to change the case of text in the selected cells.

Figure 45.2. This dialog box enables the user to change the case of text in the selected cells.

On the CD-ROM

This file is available on the companion CD-ROM and is named change case.xlam. The file is not locked, so you have full access to the VBA code and UserForm.

Setting up the workbook

This workbook contains one worksheet, which is empty. Although the worksheet is not used, it must be present because every workbook must have at least one sheet.

Choose Insert Setting up the workbook Module in the VB Editor to insert a VBA module (named Module1). Choose Insert Setting up the workbook UserForm to insert a UserForm (named UserForm1).

Procedures in Module1

The two macro that follow are contained in the Module1 code module. The ShowUserForm procedure checks the type of selection. If a range is selected, the dialog box in UserForm1 appears. If anything other than a range is selected, a message box is displayed.

The ChangeCaseOfText procedure is a special callback procedure, with one argument, that is executed from a control on the Ribbon. See “Creating the user interface for your add-in macro,” later in this chapter. This procedure simply executes the ShowUserForm procedure.

Sub ShowUserForm()
    If TypeName(Selection) = "Range" Then
        UserForm1.Show
    Else
        MsgBox "Select some cells."
    End If
End Sub

Sub ChangeCaseOfText(ByVal control As IRibbonControl)
    Call ShowUserForm
End Sub

About the UserForm

Figure 45.3 shows the UserForm1 form, which has five controls: three OptionButton controls and two CommandButton controls. The controls have descriptive names, and the Accelerator property is set so that the controls display an accelerator key (for keyboard users). The option button with the Upper Case caption has its Value property set to True, which makes it the default option.

The custom dialog box.

Figure 45.3. The custom dialog box.

The UserForm1 object contains the event-handler procedures for the two CommandButton objects that are on the form. The following procedure is executed when the OK button is clicked. This procedure does all the work:

Private Sub OKButton_Click()
    CaseChangerDialog.Hide
    Application.ScreenUpdating = False

'   Upper case
    If OptionUpper Then
        For Each cell In Selection
        If Not cell.HasFormula Then
            cell.Value = StrConv(cell.Value, vbUpperCase)
        End If
        Next cell
    End If
'   Lower case
    If OptionLower Then
        For Each cell In Selection
        If Not cell.HasFormula Then
            cell.Value = StrConv(cell.Value, vbLowerCase)
        End If
        Next cell
    End If
'   Proper case
    If OptionProper Then
        For Each cell In Selection
        If Not cell.HasFormula Then
            cell.Value = StrConv(cell.Value, vbProperCase)
        End If
        Next cell
    End If
    Unload UserForm1
End Sub

The following procedure is executed if the user clicks the Cancel button.

Private Sub CancelButton_Click()
    Unload UserForm1
End Sub

Testing the workbook

Before you convert this workbook to an add-in, it’s a good idea to test it. You should test it when a different workbook is active in order to simulate what happens when the workbook is an add-in. Remember that an add-in is never the active workbook, and it never displays any of its worksheets.

To test it, I saved the workbook, closed it, and then reopened it. With the workbook open, I then activated a different workbook, selected some cells that contained text and then pressed Alt+F8 to display the Macros dialog box. I executed the ShowUserForm macro and tried all of the options.

Adding descriptive information

Adding descriptive information is recommended but not necessary. Choose Office Adding descriptive information Prepare Adding descriptive information Properties to display the Properties panel below the Ribbon. Enter a title for the add-in in the Title field. This text appears in the Add-Ins dialog box. In the Comments field, enter a description. This information appears at the bottom of the Add-Ins dialog box when the add-in is selected. See Figure 45.4.

Use the Properties panel to enter descriptive information about your add-in.

Figure 45.4. Use the Properties panel to enter descriptive information about your add-in.

Protecting the project

In some situations (such as a commercial product), you may want to protect your project so that others can’t see the source code. To protect the project, follow these steps:

  1. Activate the Visual Basic Editor.

  2. In the Project window, click the project.

  3. Choose Tools Protecting the project project name Properties. The VB Editor displays its Project Properties dialog box.

  4. Click the Protection tab (as shown in Figure 45.5).

    The Project Properties dialog box.

    Figure 45.5. The Project Properties dialog box.

  5. Select the Lock Project For Viewing check box.

  6. Enter a password (twice) for the project.

  7. Click OK.

Creating the add-in

To save the workbook as an add-in, switch to the Excel window and activate your workbook. Then choose Office Creating the add-in Save As. Select Microsoft Excel Add-In (*.xlam) from the Save As Type drop-down list. Enter a name for the add-in file and then click OK. By default, Excel saves the add-in in your AddIns directory, but you can choose a different directory if you like.

Creating the user interface for your add-in macro

At this point, the add-in is created, but it’s missing one key component: A way to execute the macro that displays the UserForm. This section describes how to modify your add-in file so that it adds a new button to the Ribbon. It uses a technique known as RibbonX, which involves XML.

Note

In previous versions, Excel’s user interface was very easy to modify. Even a relatively inexperienced user could add a new toolbar button and attach a macro to it. Things have changed with Excel 2007. Modifying Excel’s user interface is much more complicated. The following example is, admittedly, a very simple one. A complete discussion of RIbbonX is well beyond the scope of this book. In fact, entire books are devoted to this topic.

Specifically, we’ll add a new group that’s displayed when the Home tab is clicked. This group will contain one button, and clicking this button will execute the ChangeCaseofText macro.

The changes you need to make are done outside of Excel. Make sure that the add-in file is not open in Excel. You’ll need to use a text editor. such as Notepad.

  1. Create a folder named customUI

  2. Inside of that folder, create a text file named customUI.xml, with the following XML code:

    <customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
    <ribbon>
    <tabs>
    <tab idMso="TabHome">
    <group id="myAddins"
    label="My Add-Ins"
    insertAfterMso="GroupEditingExcel">
    <button id="myButton"
    label="Change Case of Text"
    onAction="ChangeCaseofText"/>
    </group>
    </tab>
    </tabs>
    </ribbon>
    </customUI>

    Note that this XML code refers to the macro, ChangeCaseofText. That explains the argument that’s required in the Sub procedure declaration, listed earlier in this chapter (see “Procedures in Module1”).

  3. Locate and select your XLAM file in Windows Explorer. This example assumes that the file is named change case.xlam.

  4. Add a .zip extension to the file by pressing F2 and then changing the filename to changecase.xlam.zip.

  5. Drag the customUI folder you created in Step 1 into the change case.xlam.zip file. (Windows treats ZIP files as if they were folders.) Figure 45.6 shows the contents of the change case.xlam.zip file.

    The change case.xlam.zip file contains subfolders, including the customUI folder you created.

    Figure 45.6. The change case.xlam.zip file contains subfolders, including the customUI folder you created.

  6. Double-click the rels folder within the ZIP file. This folder contains one file, .rels.

  7. Drag the .rels file to a location outside of the ZIP file (your Desktop, for example).

  8. Open the .rels file (which is an XML file) with a text editor, such as Notepad.

  9. Add the following line to the .rels file, before the </Relationships> tag:

    <Relationship Type="http://schemas.microsoft.com/office/2006/
    relationships/ui/extensibility" Target="/customUI/customUI.xml"/>
  10. Drag the .rels file back into the ZIP file, overwriting the original version.

  11. Remove the .zip extension so that the file is back to its original name: change case.xlam.

Note

Yes, these steps represent an absurd amount of error-prone manual effort. Remember, this book was published when Excel 2007 was just released. By the time you read this book, tools should be available to simplify this task. Try searching the Web for office custom UI editor.

Installing the add-in

Now it’s time to try the add-in. Choose Office Installing the add-in Excel Options Installing the add-in Add-Ins. Select Excel Add-ins from the Manage drop-down list, and click Go.

Excel displays its Add-Ins dialog box. Click the Browse button and locate the change case.xlam add-in that you just created. After you do so, the Add-Ins dialog box displays the add-in in its list. Notice that the information that you provided in the Properties panel appears here. Click OK to close the dialog box and open the add-in.

Figure 45.7 shows the new command in the Ribbon. Click this button, and the ChangeCaseofText macro executes.

The new user interface control in the Ribbon.

Figure 45.7. The new user interface control in the Ribbon.

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset