Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.72 MB, 490 trang )
9.5.4 Freeing an Object Variable: the Nothing Keyword
To free an object variable so that it no longer points to anything, we use the Nothing keyword, as
Set rng2 = Nothing
It is good programming practice to free object variables when they are no longer needed, since this
can save resources. An object variable is also set to Nothing automatically when its lifetime
Note that once an object no longer has any references to it, the object will automatically be
destroyed by VBA, thus freeing up its resources (memory). However, all references to the object
must be freed before the object is destroyed. This is another reason not to point more than one
object variable at the same object if possible.
9.5.5 The Is Operator
To compare the values of two ordinary variables, Var1 and Var2, we would just write:
If Var1 = Var2 Then . . .
If rng Is rng2 then . . .
However, the syntax for comparing two object variables to see if they refer to the same object is
special (as is the syntax for setting the value of an object variable—using the Set statement). It is
done using the Is operator:
Similarly, to test whether or not an object variable has been set to Nothing, we write:
If rng Is Nothing Then . . .
Be advised that there is a problem with the Is operator in the current version of VBA. This
problem exists in the version of VBA used by Office 97 and Office 2000. (Microsoft has
acknowledged the problem.) For example, the code:
Dim Wks As Worksheet
Dim Wks2 As Worksheet
Set Wks = ActiveSheet
Set Wks2 = ActiveSheet
MsgBox Wks Is Wks2
will correctly display the value True. However, the analogous code:
Dim rng As Range
Dim rng2 As Range
Set rng = ActiveSheet.Rows(1)
Set rng2 = ActiveSheet.Rows(1)
MsgBox rng Is rng2
incorrectly displays the value False. If we change the penultimate line to:
Set rng2 = rng
then the message box correctly displays True.
9.5.6 Default Members
In most object models, many objects have a default member (property or method) that is invoked
when a property or method is expected but we do not specify one. For instance, in the Microsoft
Word object model, the default member for the Range object is the Text property. Hence, the
VBA Word code:
Dim rng As Range
Set rng = ActiveDocument.Words(1)
rng = "Donna"
sets the first word in the active document to Donna, since Word applies the default property in the
last line, effectively replacing it with:
rng.Text = "Donna"
Unfortunately, neither the Excel VBA documentation nor the Excel object model make an effort
to identify the default members of Excel objects. Accordingly, my suggestion is to avoid the issue
when programming Excel.
In any case, default members tend to make code less readable, and for this reason, I generally
avoid them. One notable exception is for a collection object. It is generally the case that the
default member of a collection object is the Item method. Hence, for instance, we can refer to the
fourth cell in the current selection by:
rather than by the more clumsy:
Since this use of the default member is not likely to cause any confusion, we will use it.
9.5.7 Global Members
Many of the properties and methods of the Application object can be used without qualifying them
with the word Application. These are called global members . For instance, the Selection
property is global, and so we can write:
To identify the global members, the Excel object model has a special object called the Global
object. This object is not used directly—its purpose is simply to identify the global members of
the object model. Note that the members of the Global object form a proper subset of the members
of the Application object (which means that not all of the members of the Application object are
Table 9-2 lists the (nonhidden) global members of the Excel object model
Table 9-2. Excel global members
Chapter 10. Excel Applications
Simply put, we can define an Office application to be an Office "document" (for instance, an
Access database, Excel workbook, Word document, Word template, or PowerPoint presentation)
that contains some special customization. This customization usually takes the form of a
combination of VBA procedures and menu and/or toolbar customizations and is generally
designed to simplify or automate certain tasks. It may provide utilities, which are programs for
performing a specific task, such as printing or sorting.
This may seem like a fairly liberal definition. For instance, if we add a single custom menu item to
a Word template that simply adds a closing (Sincerely yours, etc.) to the end of a Word document,
we could consider this template to be a Word application. However, it is doubtful that we could
get anyone to buy this Word application!
The point we want to emphasize is that an Office application is quite different from a traditional
Windows application, such as Excel itself. Traditional Windows applications are built around a
main executable file. In the case of Excel, this file is called excel.exe. Of course, a complex
application like Excel involves many additional supporting files, such as additional executables,
help files, object library files, resource files, information files, ActiveX control files, and the
ubiquitous DLL files.
On the other hand, Office applications do not revolve around standalone executable files. Rather,
they are created within an Office document. In particular, an Access application is created within
an Access database, an Excel application is created within an Excel workbook, a Word application
is created within a Word document, and a PowerPoint application is created within a PowerPoint
presentation. Office applications can be created within Office templates or add-ins as well.
This raises a whole new set of issues related to the distribution of Office applications. In
developing an Office application for distribution, we must immediately deal with two issues.
Where do we put the code for this application, and what means do we provide the user to invoke
the features of the application? The first issue is complicated by whether we will allow the user to
have access to the application's code and data or not.
The answers to these questions depend, not surprisingly, on the nature of the application.
10.1 Providing Access to an Application's Features
I recently created an Excel application for a well-known fast food company. The company wanted
to send out data on sales and other things to its field offices, in the form of a rather complicated
Excel pivot table. They wanted the field personnel to be able to filter the pivot table by various
means (thus creating smaller pivot tables) as well as generate a variety of charts showing different
views of the data. (The complete application involved other features, but this will illustrate the
In particular, the main pivot table contains several types of data (sales, transaction counts, and so
on) for several Designated Marketing Areas (DMAs) and store types (company, franchise, or
both). One feature of the application is a chart-creating utility for this data. But where should the
code for this feature go and how should the field personnel be given access to this charting utility?
Since the charting utility directly involves the pivot table, it seems reasonable in this case to
simply place a command button labeled Make Chart(s) directly on the pivot table worksheet.
When the user clicks the button, a dialog box such as the one shown in Figure 10-1 appears,
allowing the user to make various selections and then create the chart or charts.
Figure 10-1. Dialog for a charting utility
In general, there are several possible options for providing access to the charting utility, that is, for
displaying the dialog box in Figure 10-1 (or, for that matter, for providing access to any macro):
Select it from the Macro dialog by choosing Tools
Macros. The Macro
dialog was discussed in Chapter 4. This is the most efficient method for a user who writes
macros and wants to run one quickly (and it provides an easy method to run many of the
very short examples presented in this book). But since the dialog displays only the names
of macros to be run, it's not suitable for a user who is unfamiliar with the macros, nor is it
a very efficient method of running frequently used macros.
Run or display it automatically when a workbook opens by attaching code to one of
Excel's events, in this case the Open event. Events are discussed in detail in Chapter 11.
Place a button directly on the worksheet.
Place a button on an existing Excel toolbar. This can be done programmatically (a topic
discussed in Chapter 12) or through the user interface (see Section 10.1.2 later in this
Create a new toolbar and add the button to it, either programmatically or through the user
interface. For information on the latter, see Section 10.1.1 later in this section.
Add a menu item to an existing Excel menu, either programmatically or through the user
Create a new menu bar and add a menu item, either programmatically or through the user
In this case, since we did not want the user to be able to invoke the chart-printing utility unless the
worksheet containing the pivot table was active, we opted for the button on the worksheet
approach. This is not to say, however, that the other approaches would not work.
On the other hand, if the utility in question has wider applicability, then it would probably make
more sense to use a toolbar or add a menu item. (I much prefer menu items over toolbar buttons,
because they are easily invoked using the keyboard and don't get in the way of other windows.)
Indeed, an application that has many features might benefit from a dedicated toolbar or menu bar
or a dedicated popup menu on, say, the main Excel worksheet and chart menu bars.
In short, the decision as to how to provide access to the features of an Office application depends
on several things, including the complexity of the application, the scope of its features, and
10.1.1 Working with Toolbars and Menus Interactively
Whether we choose to place a command button for a macro on an existing Excel toolbar or on a
custom toolbar of our own making, we may need to specify, using the Excel user interface, when
the toolbar in question will be displayed. We can create a new toolbar and display or hide existing
toolbars by selecting the Customize option from the Tools menu. The Toolbars tab for the
Customize dialog box is shown in Figure 10-2.
Figure 10-2. The Toolbars tab of the Customize dialog
To create a new toolbar, simply click the New button. Excel opens the New Toolbar dialog, which
prompts us for a name for the toolbar. After we assign it a unique name, Excel will create the
toolbar, list it in the Toolbars list box, and display the toolbar. We can then populate the toolbar
To display or hide existing toolbars, we simply check or uncheck their boxes in the Toolbars list
We can also create a new submenu, which can then be added to an existing menu or toolbar. To do
this, we select the Commands tab of the Customize dialog (see Figure 10-3), then select the New
Menu option in the Categories list box. Click on the New Menu item in the Commands list box
and drag it to the appropriate menu or toolbar. Finally, we right-click on the new menu and enter
its caption in the context menu's Name field.
Figure 10-3. The Commands tab of the Customize dialog