Tải bản đầy đủ (.pdf) (99 trang)

Excel 2002 Power Programming with VBA phần 8 doc

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 (971.51 KB, 99 trang )

654
Part VI ✦ Developing Applications
Toolbar Manipulations
The following list summarizes the ways in which you can customize toolbars in
Excel:
✦ Remove controls from built-in toolbars. You can get rid of controls that you
never use and free up a few pixels of screen space.
✦ Add controls to built-in toolbars. You can add as many controls as you want to
any toolbar. These controls can be custom buttons or buttons from other tool-
bars, or they can come from the stock of controls that Excel provides.
✦ Create new toolbars. You can create as many new toolbars as you like, with
toolbar controls from any source.
✦ Change the functionality of built-in toolbar controls. You do this by attaching
your own macro to a built-in control.
✦ Change the image that appears on any toolbar control. Excel includes a rudi-
mentary but functional toolbar button editor, although there are several other
image-changing techniques.
You can perform these customizations manually by using the Customize dialog box.
This dialog box can be displayed using a number of different commands: select
View➪ Toolbars ➪ Customize, select the Tools ➪ Customize command, or right-click
any toolbar and choose Customize. In addition, you can customize toolbars by writ-
ing VBA code.
Don’t be afraid to experiment with toolbars. If you mess up a built-in toolbar, you
can easily reset it to its default state. Just access the Customize dialog box and
click the Toolbars tab. Then select the toolbar in the list, and click the Reset button.
How Excel Handles Toolbars
Before you start working with custom toolbars, it’s important to understand how
Excel deals with toolbars in general. You may be surprised.
Storing toolbars
Toolbars can be attached to XLS (worksheet) or XLA (add-in) files, which makes it
easy to distribute custom toolbars with your applications (see “Distributing tool-


bars” later in this chapter). You can attach any number of toolbars to a workbook.
When the user opens your file, the attached toolbars automatically appear. An
exception occurs if a toolbar with the same name already exists. In such a case, the
new toolbar does not replace the existing one.
Note
4799-2 ch22.F 6/11/01 9:42 AM Page 654
655
Chapter 22 ✦ Creating Custom Toolbars
Excel stores toolbar information in an XLB file, which resides in Windows’s main
directory (\WINDOWS or \WINNT). The exact name (and location) of this file
varies.
Why is this XLB file important? Assume that a colleague gives you an Excel work-
book that has a custom toolbar stored in it. When you open the workbook, the tool-
bar appears. You examine the workbook but decide that you’re not interested in it.
Nonetheless, when you exit Excel, the custom toolbar is added to your XLB file. If
you make any toolbar changes— from the minor adjustment of a built-in toolbar to
the introduction of a custom toolbar— the XLB file is resaved when you exit Excel.
Because the entire XLB file is loaded every time you start Excel, the time it takes to
start and exit Excel increases significantly as the XLB file grows in size. Plus, all
those toolbars eat up memory and system resources. Therefore, it’s in your best
interest to delete custom toolbars that you never use. Use the View ➪ Toolbars ➪
Customize command to do this.
If you upgrade to Excel 2002 from a previous version, the information in your old
XLB file will not be migrated to Excel 2002. In other words, you will lose any tool-
bar customizations that you’ve made.
When toolbars don’t work correctly
Excel’s approach to storing toolbars can cause problems. Suppose you’ve developed
an application that uses a custom toolbar, and you’ve attached that toolbar to the
application’s workbook. The first time an end user opens the workbook, the toolbar
is displayed. When the user closes Excel, your toolbar is saved in the user’s XLB

file. If the user alters the toolbar in any way — for example, if he or she accidentally
removes a button— the next time your application is opened, the correct toolbar
does not appear. Rather, the user sees the altered toolbar, which now lacks an impor-
tant button. In other words, a toolbar attached to a workbook is not displayed if the
user already has a toolbar with the same name. In many cases, this is not what you
want to happen.
Fortunately, you can write VBA code to prevent this scenario. The trick is never to
allow your custom toolbar to be added to the user’s toolbar collection. The best
way to do this is to create the toolbar on the fly every time the workbook is opened
and then delete it when your application closes. With this process, the toolbar is
never stored in the user’s XLB file. You might think that creating a toolbar on the fly
would be a slow process. As you’ll see later in this chapter, creating toolbars with
VBA is amazingly fast.
Manipulating Toolbars and Buttons Manually
Excel makes it easy for you to create new toolbars and modify existing toolbars. In
fact, you may not even have to use VBA to work with toolbars, because you can do
just about all your toolbar customization without it.
Note
4799-2 ch22.F 6/11/01 9:42 AM Page 655
656
Part VI ✦ Developing Applications
It’s important to understand that any customizations you make to a toolbar, either
built-in or custom, are “permanent.” In other words, the changes remain in effect
even when you restart Excel. These toolbar changes are not associated with a par-
ticular workbook. To restore a toolbar to its original state, you must reset it.
About command bar customization mode
To perform any type of manual toolbar (or menu) customization, Excel needs to be
in what I call command bar customization mode. You can put Excel into this mode by
using any of these techniques:
✦ Select View➪ Toolbars ➪ Customize.

✦ Select Tools➪ Customize.
✦ Right-click any toolbar or menu, and select Customize from the shortcut
menu.
When Excel is in command bar customization mode, the Customize dialog box is
displayed, and you can manipulate toolbars and menus any way you like. You’ll find
that you can right-click menus and toolbars to get a handy shortcut menu (see
Figure 22-1). After you’ve made your customization, click the Close button in the
Customize dialog box.
The Customize dialog box includes three tabs:
Toolbars Lists all the available toolbars, including custom toolbars you
have created. The list box also includes the two menu bars
(Worksheet Menu Bar and Chart Menu Bar), plus any other
custom menu bars.
Commands Lists by category all the available built-in commands. Use this
tab to add new items to a toolbar or menu bar.
Options Lets you select various options that relate to toolbars and
menus. These include icon size, screen tips, and menu
animations.
The Options tab of the Customize dialog box contains an option called Always
show full menus. I strongly recommend that you turn this option on. When this
option is off, incomplete menus are displayed. Apparently, Microsoft thought this
option would lessen confusion for beginners. In fact, it usually has the opposite
effect.
In the sections that follow, I briefly describe how to perform some common toolbar
modifications manually, using the Customize dialog box.
Tip
Caution
4799-2 ch22.F 6/11/01 9:42 AM Page 656
657
Chapter 22 ✦ Creating Custom Toolbars

Figure 22-1: In command bar customization mode, you can alter all toolbars
and menus.
Hiding or displaying a toolbar
The Toolbars tab in the Customize dialog box displays every toolbar (built-in tool-
bars and custom toolbars). Add a check mark to display a toolbar; remove the
check mark to hide it. The changes take effect immediately.
Creating a new toolbar
Click the New button, and then enter a name in the New Toolbar dialog box. Excel
creates and displays an empty toolbar. You can then add buttons (or menu com-
mands) to the new toolbar.
Figure 22-2 shows a custom toolbar that I created manually. This toolbar, called
Custom Formatting, contains the formatting tools that I use most frequently. Notice
that this toolbar includes drop-down menus as well as standard toolbar buttons.
Figure 22-2: A custom toolbar that contains
formatting tools
4799-2 ch22.F 6/11/01 9:42 AM Page 657
658
Part VI ✦ Developing Applications
Renaming a custom toolbar
Select a custom toolbar from the list, and click the Rename button. Enter a new
name in the Rename Toolbar dialog box. You cannot rename a built-in toolbar.
Deleting a custom toolbar
Select a custom toolbar from the list, and click the Delete button. You cannot delete
a built-in toolbar.
Resetting a built-in toolbar
Select a built-in toolbar from the list, and click the Reset button. The toolbar is
restored to its default state. If you’ve added any custom tools to the toolbar, they
are removed. If you’ve removed any of the default tools, they are restored. The
Reset button is disabled when a custom toolbar is selected.
Moving and copying controls

When Excel is in command bar customization mode (that is, the Customize dialog
box is displayed), you can copy and move toolbar controls freely among any visible
toolbars. To move a control, drag it to its new location, either within the current
toolbar or on a different toolbar. To copy a control, press Ctrl while you drag that
control to another toolbar. You can also copy a control within the same toolbar.
Inserting a new control
To add a new control to a toolbar, use the Commands tab of the Customize dialog
box shown in Figure 22-3.
Figure 22-3: The Commands tab contains
a list of every available built-in control.
4799-2 ch22.F 6/11/01 9:42 AM Page 658
659
Chapter 22 ✦ Creating Custom Toolbars
Here, the controls are arranged in 17 categories. When you select a category, the
controls in that category appear to the right. To find out what a control does, select
it and click the Description button. To add a control to a toolbar, locate it in the
Commands list, and then click and drag it to the toolbar.
Adding a toolbar button that executes a macro
To create a new toolbar button to which you will attach a macro, activate the
Commands tab of the Customize dialog box, and then choose Macros from the
Categories list. Drag the command labeled Custom Button to your toolbar (by
default, this button has a smiley face image).
After adding the button, right-click it and select your options from the menu shown
in Figure 22-4. You’ll want to change the name, assign a macro, and (I hope) change
the image.
Selecting Change Button Image from the shortcut menu displays a list of 42
images. This is a tiny subset of all of the available images you can use. See
“Adjusting a toolbar button image” later in this chapter.
Figure 22-4: Customizing a toolbar button
Note

4799-2 ch22.F 6/11/01 9:42 AM Page 659
660
Part VI ✦ Developing Applications
Distributing toolbars
In this section, I describe how to distribute custom toolbars to others, and I outline
what you need to be aware of to prevent problems.
Attaching a toolbar to a workbook
To store a toolbar in a workbook file, select View➪ Toolbars➪ Customize to display
the Customize dialog box. Click the Attach button to bring up the Attach Toolbars
dialog box, shown in Figure 22-5. This dialog box lists all the custom toolbars in the
Toolbars collection in the list box on the left. Toolbars already stored in the work-
book are shown in the list box on the right.
Figure 22-5: The Attach Toolbars dialog box
To attach a toolbar, select it and click the Copy button. When a toolbar in the right
list box is selected, the Copy button reads “Delete”; you can click it to remove a
selected toolbar from a workbook.
Oddly, there is no way to attach or detach toolbars from a workbook with VBA.
These operations must be performed manually.
The copy of the toolbar stored in the workbook always reflects its contents at the
time you attach it. If you modify the toolbar after attaching it, the changed version
is not automatically stored in the workbook. You must manually remove the old
toolbar and then attach the edited toolbar.
A toolbar that’s attached to a workbook automatically appears when the workbook
is opened, unless the workspace already has a toolbar by the same name. See “How
Excel Handles Toolbars” earlier in this chapter.
Distributing a toolbar with an add-in
As I mentioned in Chapter 21, distributing an application as an add-in is often the
preferred method for end users. Not surprisingly, an add-in can also include one or
more custom toolbars. But you need to be aware of a potential glitch.
Caution

Note
4799-2 ch22.F 6/11/01 9:42 AM Page 660
661
Chapter 22 ✦ Creating Custom Toolbars
Here’s a typical scenario: You create an application that uses a custom toolbar. The
buttons on that toolbar execute VBA procedures in the application’s workbook. You
attach the toolbar to the workbook and save the workbook. You create an add-in
from the workbook. You close the XLS version of the application. You install the
add-in. You click a button on the custom toolbar and the XLS file opens!
Your intent, of course, is to have the toolbar buttons execute procedures in the
add-in, not the XLS file. But when you attach the toolbar to the workbook, the tool-
bar is saved in its current state. In that state, the workbook includes references to
the macros in the XLS file. Consequently, clicking a button opens the XLS file so that
the macro can be executed. You could manually (or via VBA) change the
OnAction
property of each toolbar button so it refers to the add-in version (the XLA file). A
better approach, however, is to write code to create the toolbar on the fly when the
add-in is opened. I discuss this topic in detail later in the chapter.
Manipulating the CommandBars Collection
The CommandBars collection, contained in the Application object, is a collection
of all
CommandBar objects. Each CommandBar object has a collection of Controls.
All these objects have properties and methods that enable you to control toolbars
with VBA procedures.
In this section, I provide some key background information that you should know
about before you start writing code to manipulate toolbars. As always, a thorough
understanding of the object model will make your task much easier.
You manipulate Excel command bars (including toolbars) by using objects located
within the
CommandBars collection. This collection consists of the following items:

✦ All 54 of Excel 2002’s built-in toolbars.
✦ Any other custom toolbars that you create.
✦ A built-in menu bar named Worksheet Menu Bar. This appears when a work-
sheet is active.
✦ A built-in menu bar named Chart Menu Bar. This appears when a chart sheet
is active.
✦ Any other custom menu bars that you create.
✦ All 58 of Excel 2002’s built-in shortcut menus.
4799-2 ch22.F 6/11/01 9:42 AM Page 661
662
Part VI ✦ Developing Applications
Command bar types
As I mentioned at the beginning of this chapter, there are actually three types of
command bars, each of which is distinguished by its
Type property. Possible set-
tings for the
Type property of the CommandBars collection are shown in the follow-
ing table. VBA provides built-in constants for the command bar types.
Type Description Constant
0 Toolbar msoBarTypeNormal
1 Menu Bar msoBarTypeMenuBar
2 Shortcut Menu msoBarTypePopUp
Listing all CommandBar objects
If you’re curious about the objects in the CommandBars collection, the following
procedure should be enlightening. Executing this procedure generates a list (shown
in Figure 22-6) of all
CommandBar objects in the CommandBars collection. For Excel
2002, it lists a total of 114 built-in command bars, plus any custom menu bars or
toolbars. For each command bar, the procedure lists its
Index, Name, Type property

settings (displayed as Toolbar, Menu Bar,orShortcut), and whether it’s a built-in
command bar.
New Toolbars in Excel 2002
If you’re upgrading from a previous version of Excel, you’ll notice several new toolbars.
Compared to Excel 2000, Excel 2002 has 13 new toolbars:
Borders Drawing Canvas Organization Chart
Envelope Protection Clipboard
Diagram PivotTable Field List Task Pane
Draw Border Insert Shape Text to Speech
Online Meeting
You might be surprised to learn that the Task Pane is actually a toolbar — a very nonstandard
toolbar. It contains a single control.
4799-2 ch22.F 6/11/01 9:42 AM Page 662
663
Chapter 22 ✦ Creating Custom Toolbars
Figure 22-6: VBA code produced this list of all
CommandBar objects.
Sub ShowCommandBarNames()
Dim Row As Integer
Dim cbar As CommandBar
Cells.Clear
Row = 1
For Each cbar In CommandBars
Cells(Row, 1) = cbar.Index
Cells(Row, 2) = cbar.Name
Select Case cbar.Type
Case msoBarTypeNormal
Cells(Row, 3) = “Toolbar”
Case msoBarTypeMenuBar
Cells(Row, 3) = “Menu Bar”

Case msoBarTypePopUp
Cells(Row, 3) = “Shortcut”
End Select
Cells(Row, 4) = cbar.BuiltIn
Row = Row + 1
Next cbar
End Sub
4799-2 ch22.F 6/11/01 9:42 AM Page 663
664
Part VI ✦ Developing Applications
When you work with toolbars, you can turn on the macro recorder to see what’s
happening in terms of VBA code. Most (but not all) of the steps you take while
customizing toolbars generate VBA code. By examining this code, you can discover
how the object model for toolbars is put together. The object model actually is
fairly simple and straightforward.
Creating a command bar
In VBA, you create a new toolbar using the Add method of the CommandBars collec-
tion. The following instruction creates a new toolbar with a default name, such as
Custom 1. The created toolbar is initially empty (has no controls) and is not visible
(its
Visible property is False).
CommandBars.Add
More often, you’ll want to set some properties when you create a new toolbar. The
following example demonstrates one way to do this:
Sub CreateAToolbar()
Dim TBar As CommandBar
Set TBar = CommandBars.Add
With TBar
.Name = “MyToolbar”
.Top = 0

.Left = 0
.Visible = True
End With
End Sub
The CreateAToolbar procedure uses the Add method of the CommandBars collection
to add a new toolbar and create an object variable,
Tbar, that represents this new
toolbar. Subsequent instructions provide a name for the toolbar, set its position to
the extreme upper-left corner of the screen, and make it visible. The Top and Left
properties specify the position of the toolbar, and these settings represent screen
coordinates, not Excel’s window coordinates.
When you access the CommandBars collection in a code module for a UserForm,
ThisWorkbook, Sheet, or Chart, you must precede the references with the
Application object. For example:
Application.CommandBars.Add
If your code is in a standard VBA module, this is not necessary.
Note
Note
4799-2 ch22.F 6/11/01 9:42 AM Page 664
665
Chapter 22 ✦ Creating Custom Toolbars
Referring to command bars
You can refer to a particular CommandBar object by its Index or its Name property.
For example, the Standard toolbar has an
Index property setting of 3, so you can
refer to this toolbar in either of the following ways:
CommandBars(3)
CommandBars(“Standard”)
If you use a name, be aware that it is case-insensitive. In other words, you can use
Standard, STANDARD, standard, etc.

Index numbering for command bars is not consistent across versions of Excel! For
example, in Excel 2002, the 3-D Settings toolbar has an Index of 58. In Excel
2000, the WordArt toolbar has an Index of 58. If your application must work in
different versions of Excel, you should use the Name property instead of the Index
property.
Deleting a command bar
To delete a custom toolbar, use the Delete method of the CommandBar object. You
can refer to the object by its index number (if you know it) or its name. The follow-
ing instruction deletes the toolbar named
MyToolbar:
CommandBars(“MyToolbar”).Delete
If the toolbar doesn’t exist, the instruction generates an error. To avoid the error
message when you attempt to delete a toolbar that may or may not exist, the sim-
plest solution is to ignore the error. The following code deletes
MyToolbar if it
exists. If it doesn’t exist, no error message is displayed.
On Error Resume Next
CommandBars(“MyToolbar”).Delete
On Error GoTo 0
Another approach is to create a custom function that determines whether a partic-
ular toolbar is in the
CommandBars collection. The following function accepts a
single argument (a potential
CommandBar object name) and returns True if the
command bar exists. This function loops through the
CommandBars collection
and exits if it finds a command bar with a name that matches the argument.
Function CommandBarExists(n) As Boolean
Dim cb As CommandBar
For Each cb In CommandBars

If UCase(cb.Name) = UCase(n) Then
CommandBarExists = True
Caution
4799-2 ch22.F 6/11/01 9:42 AM Page 665
666
Part VI ✦ Developing Applications
Exit Function
End If
Next cb
CommandBarExists = False
End Function
Properties of command bars
The following are some of the more useful properties of a CommandBar object:
BuiltIn Read-only. True if the object is one of Excel’s built-in
command bars.
Left The command bar’s left position in pixels.
Name The command bar’s display name.
Position An integer that specifies the position of the command bar.
Possible values are as follows:
msoBarLeft — The command bar is docked on the left.
msoBarTop — The command bar is docked on the top.
msoBarRight — The command bar is docked on the right.
msoBarBottom — The command bar is docked on the
bottom.
msoBarFloating — The command bar isn’t docked.
msoBarPopup — The command bar is a shortcut menu.
Protection An integer that specifies the type of protection for the
command bar.
Possible values are as follows:
msoBarNoProtection — (Default) Not protected. The

command bar can be customized by the user.
msoBarNoCustomize — Cannot be customized.
msoBarNoResize — Cannot be resized.
msoBarNoMove — Cannot be moved.
msoBarNoChangeVisible — Its visibility state cannot be
changed by the user.
msoBarNoChangeDock — Cannot be docked to a different
position.
msoBarNoVerticalDock — Cannot be docked along the left
or right edge of the window.
msoBarNoHorizontalDock — Cannot be docked along the
top or bottom edge of the window.
4799-2 ch22.F 6/11/01 9:42 AM Page 666
667
Chapter 22 ✦ Creating Custom Toolbars
Top The command bar’s top position in pixels.
Type Returns an integer that represents the type of command bar.
Possible values are:
msoBarTypeNormal — Toolbar
msoBarTypeMenuBar — Menu Bar
msoBarTypePopUp — Shortcut Menu
Visible True if the command bar is visible.
The VBA examples in the following sections demonstrate the use of some of the
command bar properties.
Counting custom toolbars
The following function returns the number of custom toolbars. It loops through the
CommandBars collection and increments a counter if the command bar represented
by
cb is a toolbar and if its BuiltIn property is False.
Function CustomToolbars()

Dim cb As CommandBar
Dim Count As Integer
Count = 0
For Each cb In CommandBars
If cb.Type = msoBarTypeNormal Then
If Not cb.BuiltIn Then
Count = Count + 1
End If
End If
Next cb
CustomToolbars = Count
End Function
Preventing a toolbar from being modified
The Protection property of a CommandBar object provides you with many options
for protecting a
CommandBar. The following instruction sets the Protection property
for a toolbar named
MyToolbar:
CommandBars(“MyToolbar”).Protection = msoBarNoCustomize
After this instruction is executed, the user is unable to customize the toolbar.
The
Protection constants are additive, which means that you can apply different
types of protection with a single command. For example, the following instructions
adjust the
MyToolbar toolbar so that it cannot be customized or moved:
Set cb = CommandBars(“MyToolbar”)
cb.Protection = msoBarNoCustomize + msoBarNoMove
4799-2 ch22.F 6/11/01 9:42 AM Page 667
668
Part VI ✦ Developing Applications

Creating an “autosense” toolbar
Many of Excel’s built-in toolbars seem to have some intelligence; they appear when
you’re working in a specific context and disappear when you stop working in that
context. For example, the Chart toolbar normally appears when you are working on
a chart, and it disappears when you stop working on the chart. At one time,
Microsoft referred to this feature as toolbar autosensing, but it stopped using that
term in later versions. For lack of a better name, I’ll continue to use autosensing to
refer to this automatic toolbar behavior.
To disable autosensing for a particular toolbar, just close the toolbar while you’re
working in the context in which it normally appears. To reenable it, make the tool-
bar visible again while you’re working in its context.
You may want to program toolbar autosensing for your application. For example, you
might want to make a toolbar visible only when a certain worksheet is activated or
when a cell in a particular range is activated. Thanks to Excel’s support for events,
this sort of programming is relatively easy.
The procedure in Listing 22-1 creates a toolbar when the workbook is opened and
uses one of its worksheets’
SelectionChange events to determine whether the
active cell is contained in a range named
ToolbarRange. If so, the toolbar is made
visible; if not, the toolbar is hidden. In other words, the toolbar is visible only when
the active cell is within a specific range of the worksheet.
This procedure, which is called by the
Workbook_Open procedure, creates a simple
toolbar named
AutoSense. The four toolbar buttons are set up to execute proce-
dures named
Button1, Button2, Button3, and Button4. Note that, before creating
the toolbar, the code deletes the existing toolbar of the same name (if it exists).
Listing 22-1: The toolbar created here is visible only when

the cell pointer falls within a given range.
Sub CreateToolbar()
‘ Creates a demo toolbar named “AutoSense”
Dim AutoSense As CommandBar
Dim Button As CommandBarButton
‘ Delete the existing toolbar if it exists
On Error Resume Next
CommandBars(“AutoSense”).Delete
On Error GoTo 0
‘ Create the toolbar
Set AutoSense = CommandBars.Add
Note
4799-2 ch22.F 6/11/01 9:42 AM Page 668
669
Chapter 22 ✦ Creating Custom Toolbars
For i = 1 To 4
Set Button = AutoSense.Controls.Add(msoControlButton)
With Button
.OnAction = “Button” & i
.FaceId = i + 37
End With
Next i
AutoSense.Name = “AutoSense”
End Sub
The event-handler procedure for the SelectionChange event (which is located in
the code module for Sheet1) is as follows:
Private Sub Worksheet_SelectionChange(ByVal Target As _
Excel.Range)
If Union(Target, Range(“ToolbarRange”)).Address = _
Range(“ToolbarRange”).Address Then

CommandBars(“AutoSense”).Visible = True
Else
CommandBars(“AutoSense”).Visible = False
End If
End Sub
This procedure checks the active cell. If it’s contained within a range named
ToolbarRange, the AutoSense toolbar’s Visible property is set to True; other-
wise, it is set to False.
The workbook also contains a
Workbook_BeforeClose procedure that deletes the
AutoSense toolbar when the workbook is closed. This technique, of course, can be
adapted to provide other types of autosensing capability for a toolbar.
For a comprehensive discussion of the types of events Excel recognizes, see
Chapter 19.
Hiding (and later restoring) all toolbars
Some developers like to “take over” Excel when their application is loaded. For
example, they like to hide all toolbars, the status bar, and the formula bar. It’s only
proper, however, for them to clean up when their application is closed. This
includes restoring the toolbars that were originally visible.
The example in this section describes a way to hide all toolbars and then restore
them when the application is closed. The
HideAllToolbars procedure is called
from the
Workbook_Open event-handler, and the RestoreToolbars procedure is
called by the
Workbook_BeforeClose event-handler.
Cross-
Reference
4799-2 ch22.F 6/11/01 9:42 AM Page 669
670

Part VI ✦ Developing Applications
The code keeps track of which toolbars were visible by storing their names in a
worksheet named
TBSheet. When the workbook closes, the RestoreToolbars
subroutine reads these cells and displays the toolbars. Using a worksheet to store
the toolbar names is safer than using a VBA array (which can lose its values). Both
procedures are shown in Listing 22-2.
Listing 22-2: Removing all toolbars and then restoring them
Sub HideAllToolbars()
Dim TB As CommandBar
Dim TBNum As Integer
Dim TBSheet As Worksheet
Set TBSheet = Sheets(“TBSheet”)
Application.ScreenUpdating = False
‘ Clear the sheet
TBSheet.Cells.Clear
‘ Hide all visible toolbars and store
‘ their names
TBNum = 0
For Each TB In CommandBars
If TB.Type = msoBarTypeNormal Then
If TB.Visible Then
TBNum = TBNum + 1
TB.Visible = False
TBSheet.Cells(TBNum, 1) = TB.Name
End If
End If
Next TB
Application.ScreenUpdating = True
End Sub

Sub RestoreToolbars()
Dim TBSheet As Worksheet
Dim cell As Range
Set TBSheet = Sheets(“TBSheet”)
Application.ScreenUpdating = False
‘ Unhide the previously displayed the toolbars
On Error Resume Next
For Each cell In TBSheet.Range(“A:A”) _
.SpecialCells(xlCellTypeConstants)
CommandBars(cell.Value).Visible = True
Next cell
Application.ScreenUpdating = True
End Sub
4799-2 ch22.F 6/11/01 9:42 AM Page 670
671
Chapter 22 ✦ Creating Custom Toolbars
In some cases, you may find that hiding the visible toolbars is insufficient. For
example, the autosensing toolbars will still appear in their appropriate context.
One solution is to set the Enabled property to False for all the toolbars that you
don’t want to appear.
Referring to controls in a command bar
A CommandBar object such as a toolbar contains Control objects. These objects
are mainly toolbar buttons and menu items.
The following
Test procedure displays the Caption property for the first Control
object contained in the Standard toolbar, which has an index of 3:
Sub Test()
MsgBox CommandBars(3).Controls(1).Caption
End Sub
When you execute this procedure, you’ll see the message box shown in Figure 22-7

(assuming that your Standard toolbar has not been modified).
Using index numbers for command bar controls works regardless of the user’s
setting of the Always show full menus option (located in the Options tab of the
Customize dialog box).
Figure 22-7: Displaying the Caption property for a control
Rather than use an index number to refer to a control, you can use its Caption
property setting. The following procedure produces the same result as the
previous one:
Sub Test2()
MsgBox CommandBars(“Standard”).Controls(“New”).Caption
End Sub
Referring to a control by using its caption is language dependent. Therefore, the
example above will not work in non-English language versions of Excel. The solu-
tion is to use the FindControl method to locate the control using its Id prop-
erty. This is described in Chapter 23.
Caution
Note
4799-2 ch22.F 6/11/01 9:42 AM Page 671
672
Part VI ✦ Developing Applications
If you display the Caption property for a control, you’ll see that it probably
includes an ampersand (
&). The letter following the ampersand is the underlined
hot key in the displayed text (for example,
&New). When you refer to a command
bar control by using its
Caption property, there is no need to include the
ampersand.
In some cases, Control objects may contain other Control objects. For exam-
ple, the first control on the Drawing toolbar contains other controls (this also

demonstrates that you can include menu items on a toolbar). The concept of
Controls within Controls will become clearer in Chapter 23, when I discuss
menus.
Listing the controls on a command bar
The following procedure displays the Caption property for each Control object
within a
CommandBar object. This example uses the Standard toolbar.
Sub ShowControlCaptions()
Dim Cbar as CommandBar
Set CBar = CommandBars(“Standard”)
Cells.Clear
Row = 1
For Each ctl In CBar.Controls
Cells(Row, 1) = ctl.Caption
Row = Row + 1
Next ctl
End Sub
The output of the ShowControlCaptions procedure is shown in Figure 22-8.
Listing all controls on all toolbars
The following procedure loops through all command bars in the collection. If the
command bar is a toolbar — that is, if its
Type property is set to 1 — another loop
displays the
Caption for each toolbar button.
Sub ShowAllToolbarControls()
Dim row As Integer
Dim Cbar As CommandBar
Dim ctl As CommandBarControl
Cells.Clear
row = 1

For Each Cbar In CommandBars
If Cbar.Type = msoBarTypeNormal Then
Cells(row, 1) = Cbar.Name
Cross-
Reference
4799-2 ch22.F 6/11/01 9:42 AM Page 672
673
Chapter 22 ✦ Creating Custom Toolbars
Figure 22-8: A list of the captions for
each control on the Standard toolbar
For Each ctl In Cbar.Controls
Cells(row, 2) = ctl.Caption
row = row + 1
Next ctl
End If
Next Cbar
End Sub
Partial output of the ShowAllToolbarControls procedure is shown in Figure 22-9.
Adding a control to a command bar
To add a new control to a CommandBar object, use the Add method of the Controls
collection object. The following instruction adds a new control to a toolbar named
MyToolbar. Its Type property is set to the msoControlButton constant, which
creates a standard button.
CommandBars(“MyToolbar”).Controls.Add _
Type:=msoControlButton
The toolbar button added in the preceding instruction is just a blank button; click-
ing it has no effect. Most of the time, you’ll want to set some properties when you
add a new button to a toolbar. The following code adds a new control, gives it an
image through the
FaceId property, assigns a macro by way of the OnAction

property, and specifies a caption:
4799-2 ch22.F 6/11/01 9:42 AM Page 673
674
Part VI ✦ Developing Applications
Figure 22-9: A list of the captions for each control
on all toolbars
Sub AddButton()
Dim NewBtn As CommandBarButton
Set NewBtn = CommandBars(“MyToolbar”).Controls.Add _
(Type:=msoControlButton)
With NewBtn
.FaceId = 300
.OnAction = “MyMacro”
.Caption = “Tooltip goes here”
End With
End Sub
The AddButton procedure creates an object variable (NewBtn) that represents the
added control. The
With-End With construct then sets the properties for the
object.
Deleting a control from a command bar
To delete a control from a CommandBar object, use the Delete method of the
Controls collection. The following instruction deletes the first control on a
toolbar named
MyToolbar:
CommandBars(“MyToolbar”).Controls(1).Delete
4799-2 ch22.F 6/11/01 9:42 AM Page 674
675
Chapter 22 ✦ Creating Custom Toolbars
You can also specify the control by referring to its caption. The following instruc-

tion deletes a control that has a caption of
SortButton:
CommandBars(“MyToolbar”).Controls(“SortButton”).Delete
Properties of command bar controls
As you’ve seen, command bar controls have a number of properties that determine
how the controls look and work. Following is a list of a few of the more useful prop-
erties for command bar controls:
BeginGroup If True, a separator bar appears before the control.
BuiltIn Read-only. True if the control is one of Excel’s built-in
controls.
Caption The text that is displayed for the control. If the control shows
only an image, the caption appears when you move the
mouse pointer over the control.
Enabled If True, the control can be clicked.
FaceID A number that represents a graphic image displayed next to
the control’s text.
Id Read-only. A code number for a predefined Excel command.
OnAction The name of a VBA procedure to be executed when the user
clicks the control.
State Determines whether a control appears “pressed.”. This prop-
erty is available only for a
CommandBarButton control.
Style Determines whether the control appears with a caption
and/or image. This property is available only for
CommandBarButton and CommandBarComboBox controls.
ToolTipText Text that appears when the user moves the mouse pointer
over the control.
Type An integer that determines the type of the control.
Setting a control’s Style property
The Style property of a control determines its appearance (this property applies

only to
CommandBarButton and CommandBarComboBox controls). This property is
usually specified using a built-in constant. For example, to display a button with an
image and text, set the Style property to msoButtonIconAndCaption. Following
are valid style settings for a
CommandBarButton:
✦ msoButtonAutomatic
✦ msoButtonCaption
✦ msoButtonIcon
4799-2 ch22.F 6/11/01 9:42 AM Page 675
676
Part VI ✦ Developing Applications
✦ msoButtonIconAndCaption
✦ msoButtonIconAndCaptionBelow
✦ msoButtonIconAndWrapCaption
✦ msoButtonIconAndWrapCaptionBelow
✦ msoButtonWrapCaption
For a CommandBarComboBox, the valid settings are msoComboLabel or
msoComboNormal.
Figure 22-10 shows a toolbar with seven command button controls, each demon-
strating a different style.
A workbook that creates this toolbar is available on the companion CD-ROM.
Figure 22-10: The seven values of the Style property for a
command button control
The text displayed on a control is the control’s Caption property, and its image is
determined by the value of the FaceID property.
Adjusting a toolbar button image
When you’re in Excel’s command bar customization mode, you can right-click any
toolbar button and select Change Button Image. Doing so displays a list of 42
images from which you can select. Most of the time, none of these images is exactly

what you need. Therefore, you must specify the image with VBA.
The image (if any) displayed on a toolbar control is determined by its
FaceId prop-
erty. For an image to be displayed, the control’s
Style property can be set to any
value except
msoButtonCaption.
The following instruction sets the
FaceId property of the first button on the
MyToolbar toolbar image to 45, which is the code number for a mailbox icon:
CommandBars(“MyToolbar”).Controls(1).FaceId = 45
How does one determine the code number for a particular image? Well, there’s trial
and error . . . and there’s also a free utility that I developed called FaceID Identifier.
This add-in makes it easy to determine the
FaceID value for a particular image.
When the add-in is installed, choose Face ID Identifier from the Tools menu. You’ll
Note
On the
CD-ROM
4799-2 ch22.F 6/11/01 9:42 AM Page 676
677
Chapter 22 ✦ Creating Custom Toolbars
see a UserForm that shows all possible command bar images. When you move the
mouse pointer over an image, the
FaceID value is displayed in a text box (see
Figure 22-11).
Figure 22-11: The author’s FaceId Identifier add-in
shows the FaceId values for built-in toolbar images.
The FaceID Identifier add-in is available on the companion CD-ROM.
Adjusting a control’s Visible property

The Visible property determines if a particular toolbar is hidden or displayed.
Setting this property to False does not delete the toolbar. The following procedure,
which causes lots of on-screen action, simply reverses the
Visible property of
each toolbar. Hidden toolbars are displayed, and visible toolbars are hidden. To
return things to normal, execute the procedure a second time.
Sub ToggleAllToolbars()
Dim cb As CommandBar
On Error Resume Next
For Each cb In CommandBars
If cb.Type = msoBarTypeNormal Then
cb.Visible = Not cb.Visible
End If
Next cb
End Sub
The On Error Resume Next statement is present to prevent the error message
that occurs when certain Excel 2002 toolbars are accessed in the incorrect context.
Specifically, the toolbars that must be accessed in the correct context are Pivot
Table Field List, Online Meeting, and Document Recovery.
Note
On the
CD-ROM
4799-2 ch22.F 6/11/01 9:42 AM Page 677
678
Part VI ✦ Developing Applications
Changing a control’s caption dynamically
The procedure in Listing 22-3 creates a toolbar that contains a single button. The
caption on this button displays the number format string for the active cell (see
Figure 22-12). The procedure uses
Worksheet events to monitor when the selection

is changed. When a
SelectionChange event occurs, a procedure is executed that
changes the caption in the button.
Figure 22-12: This toolbar button displays the number format for the active cell.
Listing 22-3: Showing the user the current
cell’s number format
Sub MakeNumberFormatDisplay()
Dim TBar As CommandBar
Dim NewBtn As CommandBarButton
‘ Delete existing toolbar if it exists
On Error Resume Next
CommandBars(“Number Format”).Delete
On Error GoTo 0
‘ Create a new toolbar
Set TBar = CommandBars.Add
With TBar
.Name = “Number Format”
.Visible = True
End With
‘ Add a button control
Set NewBtn = CommandBars(“Number Format”).Controls.Add _
(Type:=msoControlButton)
With NewBtn
.Caption = “”
4799-2 ch22.F 6/11/01 9:42 AM Page 678

×