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

Microsoft Excel VBA Programming for the Absolute Beginner Second Edition phần 1 ppsx

51 358 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

Định dạng
Số trang 51
Dung lượng 1,83 MB

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

Nội dung

added, Excel still couldn’t match other spreadsheet applications geared toward the scientist.After ignoring Excel for several years, I started a new job where Excel was the only spread-s

Trang 3

ing, or by any information storage or retrieval system without written

permission from Thomson Course Technology PTR, except for the

inclusion of brief quotations in a review.

The Premier Press and Thomson Course Technology PTR logo and

related trade dress are trademarks of Thomson Course Technology PTR

and may not be used without written permission.

Microsoft is a registered trademark of Microsoft Corporation in the

United States and/or other countries.

All other trademarks are the property of their respective owners.

Important: Thomson Course Technology PTR cannot provide software

support Please contact the appropriate software manufacturer’s

tech-nical support line or Web site for assistance.

Thomson Course Technology PTR and the author have attempted

throughout this book to distinguish proprietary trademarks from

descriptive terms by following the capitalization style used by the

manufacturer.

Information contained in this book has been obtained by Thomson

Course Technology PTR from sources believed to be reliable However,

because of the possibility of human or mechanical error by our sources,

Thomson Course Technology PTR, or others, the Publisher does not

guarantee the accuracy, adequacy, or completeness of any information

and is not responsible for any errors or omissions or the results

obtained from use of such information Readers should be particularly

aware of the fact that the Internet is an ever-changing entity Some

facts may have changed since this book went to press.

Educational facilities, companies, and organizations interested in

multiple copies or licensing of this book should contact the publisher

for quantity discount information Training manuals, CD-ROMs, and

portions of this book are also available individually or can be tailored

for specific needs.

ISBN: 1-59200-729-5

Library of Congress Catalog Card Number: 2004114911

Printed in the United States of America

05 06 07 08 09 BH 10 9 8 7 6 5 4 3 2 1

Thomson Course Technology PTR,

a division of Thomson Course Technology

25 Thomson Place Boston, MA 02210 http://www.courseptr.com

Associate Director of Marketing:

Trang 4

First, a special thank you goes out to my family:

• My wife Jill, for putting up with the late nights and weekends I spent writing

• My 8-year old son Aaron, who thinks it’s cool that his Dad writes suchlong books with so many words, but wishes it included chapters on dragons or wizards

• My 5-year old son Joshua, who wished his Dad would have played moregames with him instead of working on this book Don’t worry, Josh;

because of the guilt trip you sent me on, I’ll more than make it up to you

I would also like to thank Scott Harris at Argosy Publishing, Mitzi Koontz, and all

of the other contributors associated with Course Technology for their invaluablehelp in putting this book together

Acknowledgments

Trang 5

Duane Birnbaum began programming in graduate school, where he wrote

custom software for interfacing the electronic equipment required for hisexperiments and analyzing the data obtained from them Since completinghis Ph.D in physical chemistry in 1991, he has worked as a post-doctoral and researchscientist in academia and industry while continuing to teach on a part-time basis

He has been teaching courses in introductory programming, database design, anddata analysis in the Computer Science department at Indiana University/PurdueUniversity at Indianapolis for the past 8 years

Trang 6

Introduction x

Chapter 1 Visual Basic for Applications with Excel 1

Project: Colorful Stats 1

Installing and Enabling VBA 3

The VBA Integrated Development Environment (IDE) 5

Getting to the IDE from Excel 5

Components of the IDE 5

Programming Components within Excel 10

Macro Selection 10

The Visual Basic Toolbar 11

Getting Help with VBA 15

VBA Help 16

Constructing the Colorful Stats Program 17

Requirements of the Colorful Stats Program 18

Chapter Summary 22

Chapter 2 Beginning Programs with VBA 25

Project: Biorhythms and the Time of Your Life 25

Variables, Data Types, and Constants 26

Declaring Variables 27

Data Types 31

Constants 40

Simple Input and Output with VBA 40

Collecting User Input with InputBox() 40

Output with MsgBox() 41

Manipulating Strings with VBA Functions 42

Fun with Strings 43

Constructing the Biorhythms and the Time of Your Life Program 47

Requirements for Biorhythms and the Time of Your Life 48

Designing Biorhythms and the Time of Your Life 48

Coding Biorhythms and the Time of Your Life 49

Chapter Summary 54

Contents

Trang 7

Chapter 3 Procedures and Conditions 55

Project: Poker Dice 55

VBA Procedures 56

Event Procedures 56

Private, Public, and Procedure Scope 60

Sub Procedures 60

Function Procedures 64

Logical Operators with VBA 69

Conditionals and Branching 71

Constructing the Poker Dice Program 77

Requirements for Poker Dice 77

Designing Poker Dice 78

Coding Poker Dice 81

Chapter Summary 97

Chapter 4 Loops and Arrays 99

Project: Math Game 100

Looping with VBA 100

Do Loops 101

For Loops 103

Input Validation 107

Validation with the InputBox() Function 107

Validation with a Spreadsheet Cell 109

Arrays 109

One-Dimensional Arrays 111

Multi-Dimensional Arrays 114

Dynamic Arrays 116

Programming Formulas into Worksheet Cells 120

A1 Style References 120

R1C1-Style References 122

Constructing the Math Game 123

Requirements for the Math Game 123

Designing the Math Game 124

Coding the Math Game Program 134

Chapter Summary 147

Trang 8

Chapter 5 Basic Excel Objects 149

Project: Battlecell 149

VBA and Object-Oriented Programming 150

Objects Defined 151

VBA Collection Objects 153

The Object Browser 155

Top-Level Excel Objects 160

The Application Object 160

The Workbook and Window Objects 161

The Worksheet Object 169

The Range Object 170

Working with Objects 173

Constructing Battlecell 177

Requirements for Battlecell 177

Designing Battlecell 180

Coding Battlecell 182

Chapter Summary 205

Chapter 6 VBA UserForms and Additional Controls 207

Project: Blackjack 208

Designing Forms with VBA 208

Adding a Form to a Project 209

Components of the UserForm Object 210

Adding ActiveX Controls to a Form 212

Showing and Hiding Forms 213

Modal Forms 214

Designing Custom Dialog Boxes Using Forms 215

Derived Data Types in VBA 233

Defining Custom Data Types in VBA 234

Defining Enumerated Types in VBA 235

Chapter Project: Blackjack 237

Requirements for Blackjack 237

Designing Blackjack 239

Writing the Code for Blackjack 246

Chapter Summary 266

vii

Contents

Trang 9

Chapter 7 Error Handling, Debugging,

and Basic File I/O 269

Project: Word Find 269

Error Handling 270

Using the On Error Statement 271

Debugging 274

Break Mode 274

The Immediate Window 275

The Watch Window 277

The Locals Window 279

File Input and Output (I/O) 279

File I/O Using Workbook and Worksheet Objects 281

Using VBA File I/O Methods 282

Chapter Project: Word Find 296

Requirements for Word Find 296

Designing Word Find 298

Writing the Code for Word Find 301

Chapter Summary 326

Chapter 8 Using XML with Excel-VBA Projects 329

Project: Revisiting the Math Game 329

Introduction to XML 330

What Is XML? 331

XML Syntax 334

XML Schemas 337

XML Validation 338

XML and Excel 338

XML and VBA 343

The XmlMap Object 345

Chapter Project: The Math Game 349

Requirements for the Math Game Program 350

Designing the Math Game 351

Coding the Math Game Program 357

Chapter Summary 373

Trang 10

Chapter 9 Excel Charts 377

Project: The Alienated Game 377

The Chart Object 378

Accessing Existing Charts 379

Manipulating Charts 383

Creating Charts 388

Chart Events 392

Chapter Project: The Alienated Game 396

Requirements for the Alienated Game 397

Designing the Alienated Game 397

Coding the Alienated Game 402

Chapter Summary 425

Chapter 10 VBA Shapes 427

Project: Excetris 427

The Shapes Collection and Shape Objects 428

Manipulating a Shape Object 430

The ShapeRange Collection Object 432

Activating Shape Objects 435

The OLEObjects Collection 436

Chapter Project: Excetris 439

Requirements for Excetris 439

Designing Excetris 441

Coding Excetris 445

Chapter Summary 471

A Final Word 471

Index 473

ix

Contents

Trang 11

Visual Basic for Applications (VBA for short) is a programming environment

designed to work with Microsoft’s Office applications (Word, Excel,Access, and PowerPoint) Components in each application (for example,worksheets or documents) are exposed as objects to the programmer to use andmanipulate to a desired end Almost anything you can do through the normal use

of the Office application can also be automated through programming

VBA is a complete programming language, but you can’t use it outside the cation in which it is integrated This does not mean VBA can be integrated onlywith Office programs Any software vendor that decides to implement VBA caninclude it with their application

appli-VBA is relatively easy to learn, but to use it in a new application, you must firstbecome familiar with the object model of the application For example, the

Documentand Dictionaryobjects are specific to the Word object model, whereasthe Workbook, Worksheet, and Rangeobjects are specific to the Excel object model

As you proceed through this book, you will see that the Excel object model isfairly extensive; however, if you are familiar with Excel, you will find that usingthese objects is generally straightforward

Why VBA?

As a beginning language, VBA will suit your needs well VBA is not as vast as manypopular languages because such extensiveness is simply unnecessary VBA wasbuilt to work with and extend the abilities of Office applications, so it doesn’tneed the substance of a programming language used to build full-blown appli-cations from scratch The relative simplicity of VBA makes it less intimidatingand easier for you to learn VBA, however, does share many of the programmingconstructs common to all languages, so it also serves as a great introduction toprogramming For these reasons, and the fact that Excel is the most popularspreadsheet application available, I am writing this book

As a scientist, I never really gave business-orientated Excel a chance The earliestversions of Excel didn’t even have graphical capabilities; even after they were

Trang 12

added, Excel still couldn’t match other spreadsheet applications geared toward the scientist.After ignoring Excel for several years, I started a new job where Excel was the only spread-sheet application available; it was then that I discovered that it uses a macro language based

on the already very popular Visual Basic I started writing programs to handle some of theroutine data analyses required around the lab, and the time I have saved using these pro-grams has sold me on Excel as a valuable component in any lab or business

Who Should Read This Book?

The goal of this book is to help you learn VBA programming with Excel No prior programmingexperience is required or expected Although you do not have to be an Excel user, you musthave a good understanding of the basic tools involved in using any spreadsheet application

This includes a basic understanding of ranges and cell references, formulas, built-in functions, and charts I ask my students at the start of every semester if they know how to use Excel.

At least 90 percent of them say they are very comfortable with the application Within twoweeks of the start of the semester it is clear that no more than 10 percent of the class canwrite a proper formula—one that takes advantage of absolute and relative references, and built-in functions Furthermore, fewer than 5 percent know anything about chart typesand the kind of analyses they should be used in If you’re not comfortable with spreadsheetapplications or it’s been a while since you have used a spreadsheet, then I recommend youconsider purchasing another introductory book on how to use the Excel application prior

to learning how to program in VBA for Excel In addition to spreadsheets, I also expect you

to have a basic understanding of the Windows operating system

What ’s in This Book and What Is Required?

I developed the programs in this book using Excel 2003 for Windows Although Excel andVBA don’t change much from one version to the next, I can’t guarantee that the programs

in this book will execute without error in earlier versions of Excel With each new version

of Excel, VBA is updated with new objects, and existing objects are expanded with new erties and methods If I use even one new object, property, or method specific to VBA-Excel

prop-2003 in a program, then it will generate an error if executed in a previous version of Excel;therefore, you need Excel 2003—with VBA installed and activated—to use this book

The chapter projects in this book feature the development of games using VBA with Excel.This is somewhat unusual in the sense that prior to writing this book, I had never seen anExcel application that runs any kind of a game; however, it does serve to make programmingmore fun After all, what’s the first thing anybody does when a new computer is purchased?

xi

Introduction

Trang 13

The answer: find the games that are installed and start playing With this book, you get towrite the program and then play the game It actually works quite well The games developed

in this book illustrate the use of basic programming techniques and structures found in allprogramming languages as well as all of the common (and some less common) components

in Excel

What ’s on the CD-ROM?

The CD that accompanies this book includes the following:

• The source code for the longer sample programs and the chapter projects discussed

in the book, including all supporting image and sound files

• Audacity, an open-source audio editor

• The GIMP for Windows, a photo retouching and image composition program

• POV-Ray, a tool for creating high-quality three-dimensional graphics

• SawCutter, a tool for designing sounds

• cEdit Professional, an advanced, alternative text editor and IDE

Trang 14

Visual Basic for Applications

with Excel

1

C H A P T E R

In this first chapter, I introduce you to the programming tools available in

Excel These tools include the VBA IDE (Integrated Development ment), controls and functions available through the main Excel applica-tion, and VBA on-line help After your introduction to the VBA programmingenvironment, I take you through a very short and simple program that calculatessome basic statistics from a sample data set The program displays the statistics

Environ-in a worksheet formatted with a large font, bright colors, and a border to complete

the Colorful Stats project

Specifically this chapter will cover:

• Installing and enabling VBA

• The VBA IDE and components within

• Programming tools within Excel

• Using VBA on-line help

Project: Colorful Stats

The project in this chapter is short and simple, but will serve as your first duction to the VBA programming environment, ActiveX controls, event-drivenprogramming, and using VBA to interact with your spreadsheet A view of the

intro-Colorful Stats spreadsheet is shown in Figure 1.1

C H A P T E R

Trang 15

Don’t concern yourself with syntax (the rules of the VBA language) at this time In quent chapters, I will show you the tools needed to build VBA projects For right now, I justwant you to see how easy it is to make something work and recognize that many of the key-words we use in VBA programming projects in this book are already familiar to you as anExcel user

subse-Keywords are words used by the programming language for a special purposeand therefore are reserved This means you cannot use a keyword in your programfor anything other than what was designed into the language

H I N T

In the Real World

Event-driven programming refers to the creation of a program that is designed to run when the

user generates a stimulus For example, a keystroke or a mouse click may trigger specific pieces of a program to execute The event-driven programming model has been popular for years (since the first graphical-based operating systems such as Windows and Macintosh were introduced) and is now commonplace It is vastly superior to older programs that did not allow for much user interaction because the programmers dictated the flow of the program In event-driven programming, the user dictates the flow of the program and it is up to programmers

to anticipate the user’s needs.

Figure 1.1

The Colorful Stats

project.

Trang 16

Installing and Enabling VBA

Unfortunately, there are enough unscrupulous programmers out in the world that security

is of paramount importance for your computer Computer viruses are common and, liketechnology in general, are becoming increasingly more complex Macro language virusessuch as those written in VBA are relatively easy to write—even for a beginning programmer

As a result, Microsoft has added several levels of security to its Office programs in order toprotect against macro viruses The first level of security Microsoft has implemented is simply

to disable macro language support for its Office programs Disabling macro language support

is now the standard for the normal installation of Office or any of its component programs

If items such as add-ins, wizards, and the VBA project files on this book’s accompanying CD

do not function, then your Excel program was either installed without VBA or with VBA abled You must install VBA and enable macro language support before you can access theVBA IDE and create your own projects or use any of the aforementioned tools

dis-To install or enable VBA, you must insert the CD that contains the Excel program into yourcomputer and run the Office/Excel setup program by doing the following:

1 Double-click the Add/Remove Programs icon in the Microsoft Windows Control Panel(found on the Start menu)

2 If you installed Excel as part of Microsoft Office, click Microsoft Office (edition andversion) in the currently installed programs box, and then click the Change button

If you installed Excel individually, click Excel (edition and version) in the currentlyinstalled programs box, and then click the Change button

3 On the features to install screen in the Setup program, click the plus sign (+) next toOffice Shared Features

4 Select Visual Basic for Applications, click the arrow next to your selection, and thenclick Run from My Computer

5 In addition, you should install the VBA help files by selecting Visual Basic Help andRun from My Computer

After the installation is complete, you may also need to change the macro security setting

in Excel before you can run any VBA programs To change the macro security setting inExcel, do the following:

1 Select Tools, Macro, Security from the Excel application window (see Figure 1.2)

2 Set the security level to Medium or Low to enable macros

3

Chapter 1 • Visual Basic for Applications with Excel

Trang 17

I recommend setting the macro security level to Medium so that you will be able to run (andtherefore test) your VBA programs, yet still receive a warning message that macros are present

in the file With the macro security level set to Medium, you will always know if a macro ispresent in an Excel file, and then you can decide if it’s safe Never enable macros attached

to an Excel file from an untrustworthy source! Note that setting the security level to Highwill disable any macro attached to an Excel file that has not been digitally signed

Figure 1.2

Macro security

level settings

in Excel.

In the Real World

To ensure that third-party software written for Excel 2003 is from a trustworthy source, Microsoft allows programmers to digitally sign a file or a VBA project by using a digital signa- ture A digital signature is an electronic authentication mechanism for a program or document.

A digital signature confirms that the program originated from the signer and has not been altered To digitally sign macro projects, you must install a digital certificate A digital certifi- cate attached to a program vouches for its authenticity Digital certificates are obtained from commercial vendors such as Verisign who act as a trusted third party in the transaction When you set the macro security level to High, you can run macros written by programmers if they are digitally signed and have been added to your list of trusted sources.

Trang 18

The VBA Integrated Development Environment (IDE)

Before learning how to program in VBA, you have to learn how to use the software requiredfor creating your projects The VBA development software is included with each component

of the Microsoft Office suite of programs, including Excel Starting the VBA developmentsoftware places you in the VBA programming environment IDE, which provides you with anumber of tools for use in the development of your project

Getting to the IDE from Excel

Before you begin creating projects with VBA you must know your way around the IDE Youcan access the IDE from Excel in a couple of different ways In Excel: select Tools, Macro,Visual Basic Editor (as shown in Figure 1.3); or use the keystroke Alt + F11

Alternatively, select the Visual Basic toolbar from the View/Toolbars menu item in Excel.When the toolbar is displayed, select the Visual Basic Editor icon found in the middle of thetoolbar (see Figure 1.4)

Components of the IDE

After opening the VBA IDE you may find yourself looking at a window similar to what isshown in Figure 1.5 This figure shows the VBA IDE and some of the tools that can be used

to create projects

5

Chapter 1 • Visual Basic for Applications with Excel

In the Real World

An IDE is software used by programmers for rapid application development (RAD) IDE’s are available for numerous programming languages and are often quite expensive to purchase (several hundred dollars or more for a single license) The price is worth it because IDE’s provide tools that enable programmers to develop applications quickly, saving them considerable time and money Yet, the most important component of any development software is the compiler, which for many languages can be obtained at no cost The compiler converts your program into the binary code your computer understands If you have the compiler, all you really need to create an application—albeit with considerably more effort—is a text editor Excel comes with its own IDE and VBA compiler, thus making it more of a value than you may realize.

Trang 19

Figure 1.3

Accessing the

VBA IDE from

the Tools menu

Trang 20

Like in most applications, there is a menu bar across the top of the window You may onlyrecognize a few items that exist within this menu, but don’t worry I’ll show you the func-tion of most of these items as we proceed through the book

The Standard toolbar is one of four toolbars available from the IDE Like any toolbar, its tion is to give the user fast access to common tools available within the application Again,

func-I will explain the use of many of these functions, as well as the use of other toolbars, as weproceed through the book

Of particular importance is the Project Explorer window, shown in the upper left corner ofthe IDE window in Figure 1.5 The Project Explorer lists all projects currently open, includingthose opened by Excel upon startup The Project Explorer also lists the components of anyopened projects For example, Figure 1.5 shows that there is currently one project, called

Book1, open, and that this project contains four Excel objects: Sheet1, Sheet2, Sheet3, and

ThisWorkbook I will discuss Excel objects in detail in Chapter 5 For right now, recognize thatthese objects represent familiar components from Excel (the workbook and worksheets itcontains)

If I open more workbooks in Excel, or add more worksheets to a currently openworkbook in Excel, then their names will appear on the object list in the ProjectExplorer window

H I N T

7

Chapter 1 • Visual Basic for Applications with Excel

Figure 1.5

The VBA IDE.

The menu bar

Trang 21

Just below the Project Explorer window in Figure 1.5 is the Properties window The Propertieswindow displays a list of attributes or properties of the currently selected object in the ProjectExplorer window These properties are used to manipulate the behavior and appearance ofthe object to which they belong The properties of Sheet1are displayed in Figure 1.5 because

it has been selected in the Project Explorer Choosing a different object will result in a ferent properties list in the Properties window, as not all objects have the same properties

dif-As a simple example in manipulating the properties of a worksheet, open a new workbook

in Excel, note the name of your workbook and any worksheets it contains (do not changeany names), then open the VBA IDE Once in the IDE, display the Project Explorer and Propertieswindows If the Project Explorer and Properties windows are not already displayed you canaccess them through the View menu item (see Figure 1.6) You can also use the keystrokesCtrl+R and F4 to access the Project Explorer and Properties windows, respectively

Once the Project Explorer window is displayed, find the project that represents the workbookyou opened while in Excel (probably Book1or Book2) If the components of the workbook youopened in Excel are not displayed, click the + sign next to the Microsoft Excel Objects folderdirectly underneath the project name Next, find the object labeled Sheet1, select it with yourmouse and then turn your attention to the Properties window Scroll down the Propertieswindow until you come to the Nameproperty (the one without the parentheses around it).Delete the text entered to the right of the Nameproperty and enter MySheet Figure 1.7 illus-trates how to find the Nameproperty

Trang 22

Toggle back to Excel by pressing Alt+F11, or select it from the taskbar in Windows You willnote that the name of Sheet1has now been replaced with MySheetin your Excel workbook,

as shown in Figure 1.8

See how easy it is to alter the properties of a worksheet in Excel using VBA? As VBA developers,however, we will seldom, if ever, alter the properties of a workbook or worksheet at designtime The bulk of the work affecting workbooks and worksheets will occur at run time; however,

we will alter properties of ActiveX controls at design time

Design time refers to project development and the manipulation of object properties using the VBA IDE prior to running any code Conversely run time will

refer to the manipulation of object properties using a program; thus, the properties

of the object do not change until the code is executed

The View Object icon

The View Code icon

Trang 23

Finally, I will show you one more component of the VBA IDE If you look back at Figure 1.5you will also see a standard code window Windows such as these are used as containers foryour program(s) This is where you type in the code for your program, so these windows areessentially text editors very similar to Notepad You must be aware that there are pre-definedcode windows for specific Excel objects, namely the workbook (for example, ThisWorkbook)and the worksheets (for example, Sheet1) The code window displayed in Figure 1.5 repre-sents Sheet1contained within the workbook Book1.

You will also be able to add components to your project and they will have their own code dows I will explain how to use code windows more thoroughly as we proceed through thisbook For now, know that you can open a code window by double clicking on any object listed

win-in the Project Explorer You can also select the object win-in the Project Explorer and click on theView Code icon at the top left of the window (refer to Figure 1.7), select Code from the toolsmenu, or press F7 (refer to Figure 1.6) Note that you can also view the selected object in Excel

by selecting the appropriate item from these same locations (refer to Figures 1.7 and 1.8).There are, of course, more components to the VBA IDE, but I’ve shown you enough to get youstarted for now As the need arises, I will introduce more tools from the IDE that will aid inthe development of various projects

Programming Components within Excel

Not everything of interest to the VBA programmer can be found in the VBA IDE There are afew programming-related components that you can access from the Excel application Thecomponents I am referring to are the Macro items found under the Tools menu, and three

of the available toolbars—Visual Basic, Control Toolbox, and Forms—found in the View menu

in Excel

Macro Selection

Now that you’ve had an introduction to the VBA IDE, it’s time to look at development toolsaccessed directly from Excel To begin, take a closer look at the Macro selection from theTools menu, shown in Figure 1.3 Notice two other items displayed in Figure 1.3 that I havenot yet discussed: Macros and Record New Macro Essentially the Record Macro tool willallow you to create a VBA program by simply selecting various tasks in Excel through thenormal interface The Record Macro tool is quite helpful, as you will see in Chapter 4 when

I discuss it in detail The Macros menu item will simply display a dialog box with a list ofsome or all of the currently loaded VBA programs Again I will explain the Macro menu item

in more detail later in the book, but for now, remember that it is one way to access and rundesired VBA programs Figure 1.9 shows the Macro dialog box

Trang 24

Macros typically refer to programs that are recorded as the user executes a

series of tasks from the normal application interface They are useful when auser repeatedly performs the same tasks in Excel Instead of having to repeattasks, the user can simply record his/her actions once, then “play back” themacro when he/she needs to repeat the same series of tasks However, it is pos-sible to access programs that were not recorded through the Macro menu item,

thus I will use the term macro to refer to both recorded programs and those

programs written from scratch

The Visual Basic Toolbar

The Visual Basic toolbar shown in Figure 1.4 provides another set of tools for the VBA oper You have already seen how selecting the Visual Basic Editor icon from this toolbar givesyou access to the VBA IDE There are several other useful items on the Visual Basic toolbar,including Run Macro, Record Macro, and Design Mode, that I will discuss later Alsoincluded on the Visual Basic toolbar is an icon for the Control Toolbox, denoted by thecrossed hammer and wrench The Control Toolbox can also be accessed via the Toolbars item

devel-on the View menu

The Control Toolbox (refer to Figure 1.10) provides you with ActiveX controls which aregraphical tools, such as a Check Box or Command Button, that may be associated with amacro The Text Box, Command Button, Label, and Image Control are just some of theActiveX controls available and are specifically labeled in Figure 1.10 You place controls on

a worksheet by first clicking on the desired control and then drawing it onto the worksheet.Start by selecting the Command Button control and drawing it on a worksheet as shown inFigure 1.11

Trang 25

After the Command Button is placed on the worksheet, you will notice that it is selected andthe application is currently in Design Mode (check that the Design Mode icon in the upperleft corner of the Control Toolbox appears “pressed in”) You can access the properties of theCommand Button control while in Design Mode With the Command Button controlselected while in Design Mode, select the Properties icon from the Control Toolbox A windowmuch like the Properties window in the VBA IDE will appear The Properties window lists allthe attributes or properties used to describe the Command Button control Figure 1.12shows the Properties window.

Figure 1.10

The Control

Toolbox

The Properties Window toggle

View Code

The Command Button control

The Text Box control

The Image control

The Label control

Ngày đăng: 12/08/2014, 16:21

TỪ KHÓA LIÊN QUAN