1. Trang chủ
  2. » Công Nghệ Thông Tin

Excel 2002 Power Programming with VBA phần 8 doc

99 226 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Excel 2002 Power Programming With Vba Phần 8
Thể loại Tài liệu
Năm xuất bản 2001
Thành phố Unknown
Định dạng
Số trang 99
Dung lượng 0,95 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

You can perform these customizations manually by using the Customize dialog box.This dialog box can be displayed using a number of different commands: selectView ➪ Toolbars ➪ Customize,

Trang 1

Toolbar Manipulations

The following list summarizes the ways in which you can customize toolbars inExcel:

✦ 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 bars, or they can come from the stock of controls that Excel provides

tool-✦ 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 otherimage-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: selectView ➪ Toolbars ➪ Customize, select the Tools ➪ Customize command, or right-clickany 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, youcan easily reset it to its default state Just access the Customize dialog box andclick 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 howExcel 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 iteasy 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 Anexception occurs if a toolbar with the same name already exists In such a case, thenew toolbar does not replace the existing one

Note

Trang 2

Excel stores toolbar information in an XLB file, which resides in Windows’s maindirectory (\WINDOWS or \WINNT) The exact name (and location) of this filevaries.

Why is this XLB file important? Assume that a colleague gives you an Excel 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

work-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 tostart and exit Excel increases significantly as the XLB file grows in size Plus, allthose toolbars eat up memory and system resources Therefore, it’s in your bestinterest 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 oldXLB 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 theapplication’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 XLBfile If the user alters the toolbar in any way — for example, if he or she accidentallyremoves 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 toallow your custom toolbar to be added to the user’s toolbar collection The bestway to do this is to create the toolbar on the fly every time the workbook is openedand then delete it when your application closes With this process, the toolbar isnever stored in the user’s XLB file You might think that creating a toolbar on the flywould be a slow process As you’ll see later in this chapter, creating toolbars withVBA is amazingly fast

Manipulating Toolbars and Buttons Manually

Excel makes it easy for you to create new toolbars and modify existing toolbars Infact, you may not even have to use VBA to work with toolbars, because you can dojust about all your toolbar customization without it

Note

Trang 3

It’s important to understand that any customizations you make to a toolbar, eitherbuilt-in or custom, are “permanent.” In other words, the changes remain in effecteven 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 shortcutmenu

When Excel is in command bar customization mode, the Customize dialog box isdisplayed, and you can manipulate toolbars and menus any way you like You’ll findthat you can right-click menus and toolbars to get a handy shortcut menu (seeFigure 22-1) After you’ve made your customization, click the Close button in theCustomize 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 menuanimations

The Options tab of the Customize dialog box contains an option called Alwaysshow full menus I strongly recommend that you turn this option on When thisoption is off, incomplete menus are displayed Apparently, Microsoft thought thisoption would lessen confusion for beginners In fact, it usually has the oppositeeffect

In the sections that follow, I briefly describe how to perform some common toolbarmodifications manually, using the Customize dialog box

Tip Caution

Trang 4

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 bars and custom toolbars) Add a check mark to display a toolbar; remove thecheck mark to hide it The changes take effect immediately

tool-Creating a new toolbar

Click the New button, and then enter a name in the New Toolbar dialog box Excelcreates 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, calledCustom Formatting, contains the formatting tools that I use most frequently Noticethat this toolbar includes drop-down menus as well as standard toolbar buttons

Figure 22-2: A custom toolbar that contains

formatting tools

Trang 5

Renaming a custom toolbar

Select a custom toolbar from the list, and click the Rename button Enter a newname 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 isrestored to its default state If you’ve added any custom tools to the toolbar, theyare removed If you’ve removed any of the default tools, they are restored TheReset 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 dialogbox is displayed), you can copy and move toolbar controls freely among any visibletoolbars To move a control, drag it to its new location, either within the currenttoolbar or on a different toolbar To copy a control, press Ctrl while you drag thatcontrol 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 dialogbox shown in Figure 22-3

Figure 22-3: The Commands tab contains

a list of every available built-in control

Trang 6

Here, the controls are arranged in 17 categories When you select a category, thecontrols 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 theCommands 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 theCommands tab of the Customize dialog box, and then choose Macros from theCategories list Drag the command labeled Custom Button to your toolbar (bydefault, 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) changethe image

Selecting Change Button Image from the shortcut menu displays a list of 42images 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

Trang 7

Distributing toolbars

In this section, I describe how to distribute custom toolbars to others, and I outlinewhat 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 displaythe Customize dialog box Click the Attach button to bring up the Attach Toolbarsdialog box, shown in Figure 22-5 This dialog box lists all the custom toolbars in theToolbars 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 rightlist box is selected, the Copy button reads “Delete”; you can click it to remove aselected 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 thetime 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 oldtoolbar 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 “HowExcel 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 thepreferred method for end users Not surprisingly, an add-in can also include one ormore custom toolbars But you need to be aware of a potential glitch

Caution Note

Trang 8

Here’s a typical scenario: You create an application that uses a custom toolbar Thebuttons on that toolbar execute VBA procedures in the application’s workbook Youattach the toolbar to the workbook and save the workbook You create an add-infrom 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 tothe macros in the XLS file Consequently, clicking a button opens the XLS file so thatthe 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) Abetter approach, however, is to write code to create the toolbar on the fly when theadd-in is opened I discuss this topic in detail later in the chapter

Manipulating the CommandBars Collection

The CommandBarscollection, contained in the Applicationobject, is a collection

of all CommandBarobjects Each CommandBarobject has a collection of Controls.All these objects have properties and methods that enable you to control toolbarswith VBA procedures

In this section, I provide some key background information that you should knowabout before you start writing code to manipulate toolbars As always, a thoroughunderstanding of the object model will make your task much easier

You manipulate Excel command bars (including toolbars) by using objects locatedwithin the CommandBarscollection 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 sheet is active

work-✦ 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

Trang 9

Command bar types

As I mentioned at the beginning of this chapter, there are actually three types ofcommand bars, each of which is distinguished by its Typeproperty Possible set-tings for the Typeproperty of the CommandBarscollection are shown in the follow-ing table VBA provides built-in constants for the command bar types

0 Toolbar msoBarTypeNormal

1 Menu Bar msoBarTypeMenuBar

2 Shortcut Menu msoBarTypePopUp

Listing all CommandBar objects

If you’re curious about the objects in the CommandBarscollection, the followingprocedure should be enlightening Executing this procedure generates a list (shown

in Figure 22-6) of all CommandBarobjects in the CommandBarscollection For Excel

2002, it lists a total of 114 built-in command bars, plus any custom menu bars ortoolbars For each command bar, the procedure lists its Index, Name, Typeproperty

settings (displayed as Toolbar, Menu Bar, or Shortcut), 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 ChartEnvelope Protection Clipboard

Diagram PivotTable Field List Task PaneDraw Border Insert Shape Text to SpeechOnline Meeting

You might be surprised to learn that the Task Pane is actually a toolbar — a very nonstandardtoolbar It contains a single control

Trang 10

Figure 22-6: VBA code produced this list of all

CommandBarobjects

Sub ShowCommandBarNames()Dim Row As IntegerDim cbar As CommandBarCells.Clear

Row = 1For Each cbar In CommandBarsCells(Row, 1) = cbar.IndexCells(Row, 2) = cbar.NameSelect Case cbar.TypeCase msoBarTypeNormalCells(Row, 3) = “Toolbar”

Case msoBarTypeMenuBarCells(Row, 3) = “Menu Bar”

Case msoBarTypePopUpCells(Row, 3) = “Shortcut”

End SelectCells(Row, 4) = cbar.BuiltInRow = Row + 1

Next cbarEnd Sub

Trang 11

When you work with toolbars, you can turn on the macro recorder to see what’shappening in terms of VBA code Most (but not all) of the steps you take whilecustomizing toolbars generate VBA code By examining this code, you can discoverhow the object model for toolbars is put together The object model actually isfairly simple and straightforward.

Creating a command bar

In VBA, you create a new toolbar using the Addmethod of the CommandBarstion The following instruction creates a new toolbar with a default name, such as

collec-Custom 1 The created toolbar is initially empty (has no controls) and is not visible(its Visibleproperty is False)

CommandBars.Add

More often, you’ll want to set some properties when you create a new toolbar Thefollowing example demonstrates one way to do this:

Sub CreateAToolbar()Dim TBar As CommandBarSet TBar = CommandBars.AddWith TBar

.Name = “MyToolbar”

.Top = 0.Left = 0.Visible = TrueEnd With

End Sub

The CreateAToolbarprocedure uses the Addmethod of the CommandBarscollection

to add a new toolbar and create an object variable, Tbar, that represents this newtoolbar Subsequent instructions provide a name for the toolbar, set its position tothe extreme upper-left corner of the screen, and make it visible The Topand Left

properties specify the position of the toolbar, and these settings represent screencoordinates, 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 theApplicationobject For example:

Application.CommandBars.Add

If your code is in a standard VBA module, this is not necessary

Note Note

Trang 12

Referring to command bars

You can refer to a particular CommandBarobject by its Indexor its Nameproperty

For example, the Standard toolbar has an Indexproperty setting of 3, so you canrefer 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! Forexample, 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 indifferent versions of Excel, you should use the Name property instead of the Indexproperty

Deleting a command bar

To delete a custom toolbar, use the Deletemethod of the CommandBarobject Youcan 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 errormessage 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 MyToolbarif itexists If it doesn’t exist, no error message is displayed

On Error Resume NextCommandBars(“MyToolbar”).Delete

On Error GoTo 0

Another approach is to create a custom function that determines whether a ular toolbar is in the CommandBarscollection The following function accepts a single argument (a potential CommandBarobject name) and returns True if the command bar exists This function loops through the CommandBarscollectionand exits if it finds a command bar with a name that matches the argument

partic-Function CommandBarExists(n) As BooleanDim cb As CommandBar

For Each cb In CommandBars

If UCase(cb.Name) = UCase(n) ThenCommandBarExists = True

Caution

Trang 13

Exit FunctionEnd If

Next cbCommandBarExists = FalseEnd Function

Properties of command bars

The following are some of the more useful properties of a CommandBarobject:

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 thebottom

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 bechanged by the user

msoBarNoChangeDock— Cannot be docked to a differentposition

msoBarNoVerticalDock— Cannot be docked along the left

or right edge of the window

msoBarNoHorizontalDock— Cannot be docked along thetop or bottom edge of the window

Trang 14

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 thecommand bar properties

Counting custom toolbars

The following function returns the number of custom toolbars It loops through the

CommandBarscollection and increments a counter if the command bar represented

by cbis a toolbar and if its BuiltInproperty is False

Function CustomToolbars()Dim cb As CommandBarDim Count As IntegerCount = 0

For Each cb In CommandBars

If cb.Type = msoBarTypeNormal Then

If Not cb.BuiltIn ThenCount = Count + 1End If

End IfNext cbCustomToolbars = CountEnd Function

Preventing a toolbar from being modified

The Protectionproperty of a CommandBarobject provides you with many optionsfor protecting a CommandBar The following instruction sets the Protectionpropertyfor a toolbar named MyToolbar:

CommandBars(“MyToolbar”).Protection = msoBarNoCustomize

After this instruction is executed, the user is unable to customize the toolbar

The Protectionconstants are additive, which means that you can apply different

types of protection with a single command For example, the following instructionsadjust the MyToolbartoolbar so that it cannot be customized or moved:

Set cb = CommandBars(“MyToolbar”)cb.Protection = msoBarNoCustomize + msoBarNoMove

Trang 15

Creating an “autosense” toolbar

Many of Excel’s built-in toolbars seem to have some intelligence; they appear whenyou’re working in a specific context and disappear when you stop working in thatcontext 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’reworking 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, youmight want to make a toolbar visible only when a certain worksheet is activated orwhen 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 anduses one of its worksheets’ SelectionChangeevents to determine whether theactive cell is contained in a range named ToolbarRange If so, the toolbar is madevisible; if not, the toolbar is hidden In other words, the toolbar is visible only whenthe active cell is within a specific range of the worksheet

This procedure, which is called by the Workbook_Openprocedure, creates a simpletoolbar named AutoSense The four toolbar buttons are set up to execute proce-dures named Button1, Button2, Button3, and Button4 Note that, before creatingthe 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 CommandBarDim Button As CommandBarButton

‘ Delete the existing toolbar if it exists

On Error Resume NextCommandBars(“AutoSense”).Delete

On Error GoTo 0

‘ Create the toolbarSet AutoSense = CommandBars.Add

Note

Trang 16

For i = 1 To 4Set Button = AutoSense.Controls.Add(msoControlButton)With Button

.OnAction = “Button” & i.FaceId = i + 37

End WithNext iAutoSense.Name = “AutoSense”

CommandBars(“AutoSense”).Visible = TrueElse

CommandBars(“AutoSense”).Visible = FalseEnd If

End Sub

This procedure checks the active cell If it’s contained within a range named

ToolbarRange, the AutoSensetoolbar’s Visibleproperty is set to True; wise, it is set to False

other-The workbook also contains a Workbook_BeforeCloseprocedure that deletes the

AutoSensetoolbar when the workbook is closed This technique, of course, can beadapted to provide other types of autosensing capability for a toolbar

For a comprehensive discussion of the types of events Excel recognizes, seeChapter 19

Hiding (and later restoring) all toolbars

Some developers like to “take over” Excel when their application is loaded Forexample, they like to hide all toolbars, the status bar, and the formula bar It’s onlyproper, however, for them to clean up when their application is closed Thisincludes restoring the toolbars that were originally visible

The example in this section describes a way to hide all toolbars and then restorethem when the application is closed The HideAllToolbarsprocedure is calledfrom the Workbook_Openevent-handler, and the RestoreToolbarsprocedure iscalled by the Workbook_BeforeCloseevent-handler

Cross-Reference

Trang 17

The code keeps track of which toolbars were visible by storing their names in aworksheet named TBSheet When the workbook closes, the RestoreToolbars

subroutine reads these cells and displays the toolbars Using a worksheet to storethe 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 CommandBarDim TBNum As IntegerDim TBSheet As WorksheetSet TBSheet = Sheets(“TBSheet”)Application.ScreenUpdating = False

‘ Clear the sheetTBSheet.Cells.Clear

‘ Hide all visible toolbars and store

‘ their namesTBNum = 0For Each TB In CommandBars

If TB.Type = msoBarTypeNormal Then

If TB.Visible ThenTBNum = TBNum + 1TB.Visible = FalseTBSheet.Cells(TBNum, 1) = TB.NameEnd If

End IfNext TBApplication.ScreenUpdating = TrueEnd Sub

Sub RestoreToolbars()Dim TBSheet As WorksheetDim cell As RangeSet TBSheet = Sheets(“TBSheet”)Application.ScreenUpdating = False

‘ Unhide the previously displayed the toolbars

On Error Resume NextFor Each cell In TBSheet.Range(“A:A”) _.SpecialCells(xlCellTypeConstants)CommandBars(cell.Value).Visible = TrueNext cell

Application.ScreenUpdating = TrueEnd Sub

Trang 18

In some cases, you may find that hiding the visible toolbars is insufficient Forexample, 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 youdon’t want to appear

Referring to controls in a command bar

A CommandBarobject such as a toolbar contains Controlobjects These objectsare mainly toolbar buttons and menu items

The following Testprocedure displays the Captionproperty for the first Control

object contained in the Standard toolbar, which has an index of 3:

Sub Test()MsgBox CommandBars(3).Controls(1).CaptionEnd 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 theCustomize 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 theprevious one:

Sub Test2()MsgBox CommandBars(“Standard”).Controls(“New”).CaptionEnd Sub

Referring to a control by using its caption is language dependent Therefore, theexample 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

Trang 19

If you display the Captionproperty for a control, you’ll see that it probablyincludes an ampersand (&) The letter following the ampersand is the underlinedhot key in the displayed text (for example, &New) When you refer to a commandbar control by using its Captionproperty, there is no need to include theampersand.

In some cases, Control objects may contain other Control objects For ple, the first control on the Drawing toolbar contains other controls (this alsodemonstrates that you can include menu items on a toolbar) The concept ofControlswithin Controls will become clearer in Chapter 23, when I discussmenus

exam-Listing the controls on a command bar

The following procedure displays the Captionproperty for each Controlobjectwithin a CommandBarobject This example uses the Standard toolbar

Sub ShowControlCaptions()Dim Cbar as CommandBarSet CBar = CommandBars(“Standard”)Cells.Clear

Row = 1For Each ctl In CBar.ControlsCells(Row, 1) = ctl.CaptionRow = Row + 1

Next ctlEnd Sub

The output of the ShowControlCaptionsprocedure is shown in Figure 22-8

Listing all controls on all toolbars

The following procedure loops through all command bars in the collection If thecommand bar is a toolbar — that is, if its Typeproperty is set to 1 — another loopdisplays the Captionfor each toolbar button

Sub ShowAllToolbarControls()Dim row As IntegerDim Cbar As CommandBarDim ctl As CommandBarControlCells.Clear

row = 1For Each Cbar In CommandBars

If Cbar.Type = msoBarTypeNormal ThenCells(row, 1) = Cbar.Name

Cross-Reference

Trang 20

Figure 22-8: A list of the captions for

each control on the Standard toolbar

For Each ctl In Cbar.ControlsCells(row, 2) = ctl.Captionrow = row + 1

Next ctlEnd IfNext CbarEnd Sub

Partial output of the ShowAllToolbarControlsprocedure is shown in Figure 22-9

Adding a control to a command bar

To add a new control to a CommandBarobject, use the Addmethod of the Controls

collection object The following instruction adds a new control to a toolbar named

MyToolbar Its Typeproperty is set to the msoControlButtonconstant, which creates a standard button

CommandBars(“MyToolbar”).Controls.Add _Type:=msoControlButton

The toolbar button added in the preceding instruction is just a blank button; ing it has no effect Most of the time, you’ll want to set some properties when youadd a new button to a toolbar The following code adds a new control, gives it animage through the FaceIdproperty, assigns a macro by way of the OnAction

click-property, and specifies a caption:

Trang 21

Figure 22-9: A list of the captions for each control

on all toolbars

Sub AddButton()Dim NewBtn As CommandBarButtonSet NewBtn = CommandBars(“MyToolbar”).Controls.Add _(Type:=msoControlButton)

With NewBtn.FaceId = 300.OnAction = “MyMacro”

.Caption = “Tooltip goes here”

End WithEnd Sub

The AddButtonprocedure creates an object variable (NewBtn) that represents theadded control The With-End Withconstruct then sets the properties for theobject

Deleting a control from a command bar

To delete a control from a CommandBarobject, use the Deletemethod of the

Controlscollection The following instruction deletes the first control on a toolbar named MyToolbar:

CommandBars(“MyToolbar”).Controls(1).Delete

Trang 22

You can also specify the control by referring to its caption The following tion deletes a control that has a caption of SortButton:

instruc-CommandBars(“MyToolbar”).Controls(“SortButton”).Delete

Properties of command bar controls

As you’ve seen, command bar controls have a number of properties that determinehow 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 themouse 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 CommandBarButtoncontrol

Style Determines whether the control appears with a caption

and/or image This property is available only for

CommandBarButtonand CommandBarComboBoxcontrols

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 Styleproperty of a control determines its appearance (this property appliesonly to CommandBarButtonand CommandBarComboBoxcontrols) This property isusually specified using a built-in constant For example, to display a button with animage and text, set the Styleproperty to msoButtonIconAndCaption Followingare valid style settings for a CommandBarButton:

✦msoButtonAutomatic

✦msoButtonCaption

✦msoButtonIcon

Trang 23

demon-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 isdetermined 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 anytoolbar button and select Change Button Image Doing so displays a list of 42images from which you can select Most of the time, none of these images is exactlywhat you need Therefore, you must specify the image with VBA

The image (if any) displayed on a toolbar control is determined by its FaceIderty For an image to be displayed, the control’s Styleproperty can be set to any

prop-value exceptmsoButtonCaption

The following instruction sets the FaceIdproperty of the first button on the

MyToolbartoolbar 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 trialand error and there’s also a free utility that I developed called FaceID Identifier.This add-in makes it easy to determine the FaceIDvalue 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

Trang 24

see a UserForm that shows all possible command bar images When you move themouse pointer over an image, the FaceIDvalue is displayed in a text box (seeFigure 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 Visibleproperty 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 Visibleproperty ofeach toolbar Hidden toolbars are displayed, and visible toolbars are hidden Toreturn things to normal, execute the procedure a second time

Sub ToggleAllToolbars()Dim cb As CommandBar

On Error Resume NextFor Each cb In CommandBars

If cb.Type = msoBarTypeNormal Thencb.Visible = Not cb.VisibleEnd If

Next cbEnd SubThe On Error Resume Next statement is present to prevent the error messagethat occurs when certain Excel 2002 toolbars are accessed in the incorrect context

Specifically, the toolbars that must be accessed in the correct context are PivotTable Field List, Online Meeting, and Document Recovery

Note

On the CD-ROM

Trang 25

Changing a control’s caption dynamically

The procedure in Listing 22-3 creates a toolbar that contains a single button Thecaption on this button displays the number format string for the active cell (seeFigure 22-12) The procedure uses Worksheetevents to monitor when the selection

is changed When a SelectionChangeevent occurs, a procedure is executed thatchanges 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 CommandBarDim NewBtn As CommandBarButton

‘ Delete existing toolbar if it exists

On Error Resume NextCommandBars(“Number Format”).Delete

On Error GoTo 0

‘ Create a new toolbarSet TBar = CommandBars.AddWith TBar

.Name = “Number Format”

.Visible = TrueEnd With

‘ Add a button controlSet NewBtn = CommandBars(“Number Format”).Controls.Add _(Type:=msoControlButton)

With NewBtn.Caption = “”

Trang 26

.OnAction = “ChangeNumFormat”

.TooltipText = “Click to change the number format”

.Style = msoButtonCaptionEnd With

Call UpdateToolbarEnd Sub

For more information about events, see Chapter 19

The UpdateToolbarprocedure, which follows, simply copies the NumberFormat

property of the ActiveCellto the Captionproperty of the button control:

Sub UpdateToolbar()

On Error Resume NextCommandBars(“Number Format”) _Controls(1).Caption = ActiveCell.NumberFormat

If Err <> 0 Then CommandBars(“Number Format”) _Controls(1).Caption = “”

End Sub

The button’s OnActionproperty is set to a procedure named ChangeNumFormat,which follows This procedure displays the Number tab of Excel’s Format Cells dialog box (see Figure 22-13)

Figure 22-13: Clicking the button enables

the user to select a new number format

Cross-Reference

Trang 27

Sub ChangeNumFormat()Application.Dialogs(xlDialogFormatNumber).ShowCall UpdateToolbar

End Sub

The technique described in this section works quite well, but it does have a flaw: Ifthe user changes the number format with a button on the Formatting toolbar, thedisplay in the Number Format is not changed, because changing the number format

of a cell does not trigger a trappable event

Assigning a custom macro to a built-in button

Each of Excel’s built-in toolbar buttons executes a specific internal procedure It’spossible to assign your own macro to a built-in button To do so, just use the

OnActionproperty The following instruction assigns a macro to the SortAscending toolbar button

CommandBars(“Standard”).Controls(“Sort Ascending”) _.OnAction = “ShowMsg”

After executing the instruction, clicking the Sort Ascending button will no longerwork Rather, it will execute the ShowMsgVBA procedure

To return the button to its normal functionality, assign an empty string to its

OnActionproperty:

CommandBars(“Standard”).Controls(“Sort Ascending”) _.OnAction = “”

“Executing” a command bar button

Command bar controls have an Executemethod When invoked, this method runsthe internal procedure assigned to a built-in control For example, executing the following instruction is equivalent to clicking the Sort Ascending button on theStandard toolbar:

CommandBars(“Standard”).Controls(“Sort Ascending”).Execute

Using the Executemethod with a custom command bar button runs the macroassigned to its OnActionproperty

Using other types of command bar controls

A standard toolbar button is just one type of five control types that you can add to

a toolbar The control type is determined by the Typeproperty of the control

The online help entices you with descriptions and images of 23 control types (seeFigure 22-14) Most of these, however, cannot be added to a command bar You mayrecognize many of these controls because they are used in Excel’s built-in toolbars

I have no idea why they are listed and described, if they cannot be used

Trang 28

Figure 22-14: The online help describes many controls that aren’t

available to you

The built-in constants for the control types that you can add to a command bar are

as follows:

msoControlButton A standard button

msoControlEdit An edit box

msoControlComboBox A combo box

msoControlDropdown A drop-down list

msoControlButtonPopup A button that, when clicked, displays other

controls Use this control to create a menu withmenu items

The Type property for a Control object is a read-only property that’s set whenthe control is created In other words, you can’t change a control’s type after it hasbeen created

The MakeMonthListprocedure in Listing 22-4 creates a new toolbar, adds a down list control, and fills that control with the names of each month It also setsthe OnActionproperty so that clicking the control executes a procedure named

drop-PasteMonth The resulting toolbar is shown in Figure 22-15

Note

Trang 29

Figure 22-15: This toolbar contains a drop-down list control, with an attached macro.

Listing 22-4: Attaching a drop-down list to a command bar

Sub MakeMonthList()Dim TBar As CommandBarDim NewDD As CommandBarControl

‘ Delete existing toolbar if it exists

On Error Resume NextCommandBars(“MonthList”).Delete

On Error GoTo 0

‘ Create a new toolbarSet TBar = CommandBars.AddWith TBar

.Name = “MonthList”

.Visible = TrueEnd With

‘ Add a DropDown controlSet NewDD = CommandBars(“MonthList”).Controls.Add _(Type:=msoControlDropdown)

With NewDD.Caption = “DateDD”

.OnAction = “PasteMonth”

.Style = msoButtonAutomatic

‘ Fill it with month name

For i = 1 To 12.AddItem Format(DateSerial(1, i, 1), “mmmm”)Next i

.ListIndex = 1End With

End Sub

Trang 30

The PasteMonthprocedure follows:

Sub PasteMonth()

‘ Puts the selected month in the active cell

On Error Resume NextWith CommandBars(“MonthList”).Controls(“DateDD”)ActiveCell.Value = List(.ListIndex)

End WithEnd Sub

The workbook has an additional twist: It uses a Worksheet_SelectionChange

event-handler This procedure, which follows, is executed whenever the user makes

a new selection on the worksheet The procedure determines whether the activecell contains a month name If so, it sets the ListIndexproperty of the drop-downlist control in the toolbar

Private Sub Worksheet_SelectionChange(ByVal Target _

As Excel.Range)For i = 1 To 12Set ActCell = Target.Range(“A1”)

If ActCell.Value = Format(DateSerial(1, i, 1), _

“mmmm”) ThenCommandBars(“MonthList”).Controls(“DateDD”) _.ListIndex = i

Exit SubEnd IfNext iEnd Sub

Trang 32

Creating Custom Menus

Virtually every Windows program has a menu system,

which usually serves as the primary user interface element The Windows standard places the menu bar directlybeneath the application’s title bar In addition, many programsnow implement another type of menu: shortcut menus

Typically, right-clicking an item displays a context-sensitiveshortcut menu containing relevant commands

Excel uses both types of menus, and developers have almostcomplete control over Excel’s entire menu system, includingshortcut menus This chapter tells you everything you need

to know about working with Excel’s menus

A Few Words about Excel’s Menu Bar

If you’ve read Chapter 22, you already know that a menu bar(like a toolbar) is a CommandBarobject In fact, the techniquesdescribed in Chapter 22 also apply to menu bars

So how does a menu bar differ from a toolbar? In general, amenu bar is displayed at the top of the Excel window, directlybelow the title bar When clicked, the top-level controls on amenu bar display a drop-down list of menu items A menu barmay also contain three window control buttons (Minimize,Restore, and Close) that are displayed only when a workbookwindow is maximized Toolbars, on the other hand, usuallyconsist of graphic icons and do not display any control but-tons These rules are definitely not hard and fast You can, ifdesired, add traditional toolbar buttons to a menu bar or addtraditional menu items to a toolbar You can even move a menubar from its traditional location and make it free-floating

23C H A P T E R

In This Chapter

An overview ofExcel’s menu systemTypes of menumodifications youcan makeHow to manipulatemenus with VBAVarious menuprogrammingtechniques usedwith events

A useful (and veryeasy) technique forcreating custommenus

A procedure forreplacing standardmenu conventionswith your ownHow to customize theshortcut menus

Trang 33

What You Can Do with Excel’s Menus

Typical Excel users get by just fine with the standard menus Because you’re ing this book, however, you’re probably not the typical Excel user You may want tomodify menus to make your life easier and to make life easier for the folks who usethe spreadsheets that you develop

read-To modify Excel’s menus, you can remove elements, add elements, and change elements In addition, you can temporarily replace Excel’s standard menu bar withone of your own creation You can change Excel’s menus two ways: manually, orwith VBA code

When you close Excel, it saves any changes that you’ve made to the menu system,and these changes appear the next time you open Excel The information aboutmenu modifications is stored in an XLB file, usually located in your Windowsdirectory

See Chapter 22 for more information about the XLB file

In most cases, you won’t want your menu modifications to be saved between

ses-sions Generally, you’ll need to write VBA code to change the menus while a

par-ticular workbook is open and then change them back when the workbook closes.Therefore, you’ll need VBA code to modify the menu when the workbook isopened and more VBA code to return the menus to normal when the workbook isclosed

Menu terminology

Menu terminology is often a bit confusing at first because many of the terms aresimilar The following list presents the official Excel menu terminology that I refer to

in this chapter:

✦ Command bar An object that can function as a menu bar, a shortcut menu, or

a toolbar It is represented by the CommandBarobject in the Microsoft Officeobject library

✦ Menu bar The row of words that appears directly below the application’s title

bar Excel has two menu bars: One is displayed when a worksheet is active,and the other is displayed when a chart sheet is active or when an embeddedchart is activated

✦ Menu A single, top-level element of a menu bar For example, both of Excel’s

menu bars have a File menu

✦ Menu item An element that appears in the drop-down list when you select a

menu For example, the first menu item under the File menu is New Menuitems also appear in submenus and shortcut menus

Note Cross-

Reference

Trang 34

✦ Separator bar A horizontal line that appears between two menu items The

separator bar is used to group similar menu items

✦ Submenu A second-level menu that is under some menus For example, the

Edit menu has a submenu called Clear

✦ Submenu item A menu item that appears in the list when you select a

sub-menu For example, the Edit ➪ Clear submenu contains the following submenuitems: All, Formats, Contents, and Comments

✦ Shortcut menu The floating list of menu items that appears when you

right-click a selection or an object The shortcut menu that appears depends on thecurrent context

✦ Enabled A menu item that can be used If a menu item isn’t enabled, its text

appears grayed, and it can’t be used

✦ Checked The status of a menu item that represents an on/off or True/False

state A menu item can display a graphical box that is checked or unchecked

The View ➪ Status Bar menu item is an example

✦ Image A small graphic icon that appears next to some menu items In VBA terms, the code associated with each image is known as a FaceID.

✦ Shortcut key combination A keystroke combination that serves as an alternate

method to execute a menu item The shortcut key combination is displayed atthe right side of the menu item For example, Ctrl+S is the shortcut key combi-nation for File ➪ Save

Removing menu elements

You can remove any part of Excel’s menu system: menu items, menus, and entiremenu bars For example, if you don’t want the end users of your application fiddlingwith the display, you can remove the View menu from the Worksheet Menu Bar Youcan also remove one or more menu items from a menu If you remove the New menuitem from the File menu, for example, users can’t use the menu to create a newworkbook Finally, you can eliminate Excel’s menu bar and replace it with one thatyou’ve created You might do this if you want your application to be completelyunder the control of your macros

It’s important to remember that simply removing menu bars, menus, or menuitems does not affect the alternate method of accomplishing some actions

Specifically, if there are corresponding shortcut keys, toolbar buttons, or shortcutmenus that perform the same action as a menu command, those alternate meth-ods still work For example, if you remove the New menu item from the File menu,the user can still use the New Workbook toolbar button, the Ctrl+N shortcut key,the Task Pane (in Excel 2002), or the Desktop shortcut menu to create a newworkbook

Caution

Trang 35

Adding menu elements

You can add custom menus to built-in menu bars, and you can add custom menuitems to a built-in menu In fact, you can create an entirely new menu bar if you like.For example, you might develop an application that doesn’t require any of Excel’sbuilt-in menus A simple solution is to create a new menu bar that consists of cus-tom menus and custom menu items that execute your macros You can hide Excel’snormal menu bar and replace it with your own

Changing menu elements

If you get bored with Excel’s standard menu text, you can change it to somethingelse — for instance, you can change the Tools menu to the Stuff menu You can alsoassign your own macros to built-in menu items You have many other options forchanging menu elements, including rearranging the order of the menus on a menubar (for example, to make the Help menu appear first instead of last)

Moving Up from Excel 5/95?

If you’ve customized menus using Excel 5 or Excel 95, you can pretty much forget thing you ever learned Beginning with Excel 97, menu customization has changed signifi-cantly in the following respects:

every-✦A menu bar is actually a toolbar in disguise If you don’t believe me, grab the

vertical bars at the very left of the menu bar and drag the bar away You’ll end upwith a floating toolbar The official (VBA) term for both menus and toolbars is

command bar.

The Excel 5/95 Menu Editor is gone To edit a menu manually, you use the View ➪

Toolbars ➪ Customize command Understand, however, that Excel 5/95 workbooksthat contain menus customized using the old Menu Editor still work in Excel 97 andlater However, to make any changes to these modified menus, you must do so inExcel 5/95

There is no easy way to assign a VBA macro to a new menu item on the Tools menu This was a piece of cake with Excel 5/95 Later in this chapter, however, I pro-

vide VBA code that you can use to add a new menu item to the Tools menu

Excel 2000 and later, by default, displays only the most recently used menu items.

In my opinion, this is one of the worst ideas Microsoft has come up with I can’timagine why anyone would want the order of his or her menu items to be shiftingaround Fortunately, this feature can be disabled in the Options panel of theCustomize dialog box

Trang 36

Be careful if you change the captions for Excel’s menus Some Excel developersrely on the standard menu captions when they create new menus and theircode will fail if you’ve modified your menu captions As you’ll see later in thischapter, using the FindControl method in your code will eliminate theseproblems.

The remainder of this chapter focuses on writing VBA code to modify menus

Chapter 22 provides background information about the Customize dialog box

VBA Examples

In this section, I present some practical examples of VBA code that manipulatesExcel’s menus

Listing menu information

The ListMenuInfoprocedure, which follows, may be instructive It displays thecaption for each item (menu, menu item, and submenu item) on the WorksheetMenu Bar

Sub ListMenuInfo()Dim row As IntegerDim Menu As CommandBarControlDim MenuItem As CommandBarControlDim SubMenuItem As CommandBarControlrow = 1

On Error Resume NextFor Each Menu In CommandBars(1).ControlsFor Each MenuItem In Menu.ControlsFor Each SubMenuItem In MenuItem.ControlsCells(row, 1) = Menu.Caption

Cross-Reference

Caution

Referencing the CommandBars Collection

The CommandBarscollection is a member of the Applicationobject When you referencethis collection in a regular VBA module, you can omit the reference to the Application

object (it is assumed) For example, the following statement (contained in a standard VBAmodule) displays the name of the first element of the CommandBarscollection:

MsgBox CommandBars(1).NameWhen you reference the CommandBarscollection from a code module for a ThisWorkbook

object, you must precede it with a reference to the Applicationobject, like this:

MsgBox Application.CommandBars(1).Name

Trang 37

Cells(row, 2) = MenuItem.CaptionCells(row, 3) = SubMenuItem.Captionrow = row + 1

Next SubMenuItemNext MenuItem

Next MenuEnd Sub

Figure 23-1 shows a portion of the ListMenuInfoprocedure’s output

Figure 23-1: A portion of the output from the ListMenuInfo

procedure

A workbook that contains this procedure is available on the companion CD-ROM

I use On Error Resume Next to avoid the error message that appears when theprocedure attempts to access a submenu item that doesn’t exist

Adding a new menu to a menu bar

In this section, I describe how to use VBA to add a new menu to the WorksheetMenu Bar The Worksheet Menu Bar is the first item in the CommandBarscollection,

so you can reference it one of two ways:

Note

On the CD-ROM

Trang 38

CommandBars(“Worksheet Menu Bar”)CommandBars(1)

In VBA terms, you use the Addmethod to append a new control to the Controls

collection The new control is a “pop-up control” of type msoControlPopup Youcan specify the new control’s position; if you don’t, the new menu is added to theend of the menu bar

Adding a new menu is a two-step process:

1 Use the Addmethod to create an object variable that refers to the new trol Arguments for the Addmethod enable you to specify the control’s type,its ID (useful only if you’re adding a built-in menu), its position, and whetherit’s a temporary control that will be deleted when Excel closes

con-2 Adjust the properties of the new control For example, you’ll probably want to

specify a Captionproperty and an OnActionproperty

Menu-Making Conventions

You may have noticed that menus in Windows programs typically adhere to some lished conventions No one knows where these conventions came from, but you should fol-low them if you want to give the impression that you know what you’re doing When youmodify menus, keep the following points in mind:

estab-✦Tradition dictates that the File menu is always first and the Help menu is always last

✦Menu text is always proper case The first letter of each word is uppercase, except

for minor words such as the, a, and and.

✦A top-level menu does not cause any action In other words, each menu must have

at least one menu item

✦Menu items are usually limited to three or fewer words

✦Every menu item should have a hot key (underlined letter) that’s unique within themenu

✦A menu item that displays a dialog box is followed by an ellipsis ( )

✦Menu item lists should be kept relatively short Sometimes, submenus provide agood alternative to long lists If you must have a lengthy list of menu items, use sep-arator bars to group items into logical groups

✦If possible, disable menu items that are not appropriate in the current context InVBA terminology, to disable a menu item, set its Enabledproperty to False

✦Some menu items serve as toggles When the option is on, the menu item is ceded by a check mark

Trang 39

pre-Adding a menu: Take 1

In this example, the objective is to add a new Budgeting menu to the WorksheetMenu Bar and to position this new menu to the left of the Help menu

Sub AddNewMenu()Dim HelpIndex As IntegerDim NewMenu As CommandBarPopup

‘ Get Index of Help menuHelpIndex = CommandBars(1).Controls(“Help”).Index

‘ Create the menuSet NewMenu = CommandBars(1).Controls.Add _(Type:=msoControlPopup, _

Before:=HelpIndex, _Temporary:=True)

‘ Add a captionNewMenu.Caption = “&Budgeting”

End Sub

The preceding code is not a good example of how to add a menu, and it may or may

not insert the menu at the proper position It suffers from two problems:

✦ It assumes that the Help menu exists The user may have removed the Helpmenu

✦ It assumes that the Help menu has Help as its caption Non-English versions of

Excel may have a different caption for their menus

Adding a menu: Take 2

Listing 23-1 presents a better demonstration It uses the FindControlmethod toattempt to locate the Help menu If the Help menu is not found, the code adds thenew menu item to the end of the Worksheet Menu Bar

Listing 23-1: Adding the Budgeting menu

to Excel’s main menu bar

Sub AddNewMenu()Dim HelpMenu As CommandBarControlDim NewMenu As CommandBarPopup

‘ Find the Help MenuSet HelpMenu = CommandBars(1).FindControl(Id:=30010)

If HelpMenu Is Nothing Then

‘ Add the menu to the end

Set NewMenu = CommandBars(1).Controls _.Add(Type:=msoControlPopup, Temporary:=True)

Trang 40

‘ Add the menu before Help

Set NewMenu = CommandBars(1).Controls _.Add(Type:=msoControlPopup, Before:=HelpMenu.Index, _Temporary:=True)

End If

‘ Add a captionNewMenu.Caption = “&Budgeting”

End Sub

The preceding procedure creates an essentially useless menu — it has no menuitems See “Adding a menu item to the Tools menu” later in this chapter for anexample of how to add a menu item to a menu

To use the FindControlmethod, you must know the IDproperty of the controlthat you’re looking for Each of Excel’s built-in CommandBarcontrols has a unique ID

property For this example, I determined the IDproperty of the Help menu by cuting the following statement:

exe-MsgBox CommandBars(1).Controls(“Help”).ID

The message box displayed 30010, which is the value I used as the IDargument forthe FindControlmethod Table 23-1 shows the IDproperty settings for the top-level controls in Excel’s menu bars

Table 23-1

ID Property Settings for Excel’s Top-Level Menus

File 30002 Edit 30003 View 30004 Insert 30005 Format 30006 Tools 30007 Data 30011 Chart 30022 Window 30009 Help 30010

Note

Ngày đăng: 14/08/2014, 02:20

TỪ KHÓA LIÊN QUAN