A variant of the Visual Basic programming language, VB for Applications VBA is built into Excel to facilitate its use as a platform.. If you're an experienced Excel user or a Visual Basi
Trang 1By Steve Saunders, Jeff Webb
Publisher: O'Reilly Pub Date: April 2006 Print ISBN-10: 0-596-00766-3 Print ISBN-13: 978-0-59-600766-9 Pages: 1114
Table of Contents | Index
Why program Excel? For solving complex calculations and presenting results, Excel is amazingly complete with every imaginable feature already in place But programming Excel isn't about adding new features as much as it's about combining existing features to solve particular problems With a few modifications, you can transform Excel into a task- specific piece of software that will quickly and precisely serve your needs In other words, Excel is an ideal platform for probably millions of small spreadsheet-based software
solutions.
The best part is, you can program Excel with no additional tools A variant of the Visual Basic programming language, VB for Applications (VBA) is built into Excel to facilitate its use as a platform With VBA, you can create macros and templates, manipulate user interface features such as menus and toolbars, and work with custom user forms or dialog
boxes VBA is relatively easy to use, but if you've never programmed before, Programming
Excel with VBA and NET is a great way to learn a lot very quickly If you're an experienced
Excel user or a Visual Basic programmer, you'll pick up a lot of valuable new tricks.
Developers looking forward to NET development will also find discussion of how the Excel object model works with NET tools, including Visual Studio Tools for Office (VSTO).
This book teaches you how to use Excel VBA by explaining concepts clearly and concisely
in plain English, and provides plenty of downloadable samples so you can learn by doing You'll be exposed to a wide range of tasks most commonly performed with Excel, arranged into chapters according to subject, with those subjects corresponding to one or more Excel objects With both the samples and important reference information for each object
included right in the chapters, instead of tucked away in separate sections, Programming
Excel with VBA and NET covers the entire Excel object library For those just starting out,
it also lays down the basic rules common to all programming languages.
With this single-source reference and how-to guide, you'll learn to use the complete range
Trang 2of Excel programming tasks to solve problems, no matter what you're experience level.
Trang 3By Steve Saunders, Jeff Webb
Publisher: O'Reilly Pub Date: April 2006 Print ISBN-10: 0-596-00766-3 Print ISBN-13: 978-0-59-600766-9 Pages: 1114
Trang 13most titles (safari.oreilly.com) For more information, contactour corporate/institutional sales department: (800) 998-9938 or
Trang 14Many of the designations used by manufacturers and sellers todistinguish their products are claimed as trademarks Wherethose designations appear in this book, and O'Reilly Media, Inc.was aware of a trademark claim, the designations have beenprinted in caps or initial caps
While every precaution has been taken in the preparation of thisbook, the publisher and authors assume no responsibility forerrors or omissions, or for damages resulting from the use ofthe information contained herein
ISBN: 0-596-00766-3
[M]
Trang 15I was lucky enough to be at Microsoft when Visual Basic wasadded to Excel I had just wrapped up working on OLE
Automationthe technology used to make Excel objects
programmableand I remember that meetings with the Excelgroup were, at times, difficult Why should a premier Microsoftproduct like Excel put so much effort into adding a low-profititem like Visual Basic when it already had a macro language?
"Because BillG said so" takes you only so far, even at Microsoft.The facts are that programmability doesn't sell products theway some other whizbang feature might, it adds risk to
delivering the product bug-free and on time, and (we foundout) it poses a security hazard
What programmability does do is make your product a platform
for others Today, Excel is the foundation for probably millions
of small spreadsheet-based software solutions and is used bycertainly thousands of very large and sophisticated applications
chapters and are motivated, I think you'll find this book a greatway to learn a lot very quickly
If you are an experienced Excel user or a Visual Basic
Trang 16Don't Force It
If you get stuck, there are a number of ways to resume yourprogress:
Try turning on macro recording (Tools Macros Record
a New Macro), performing the task in Excel, and then
turning off recording and examining the code that Excelgenerates
Search MSDN (http://www.microsoft.com/msdn) to see ifMicrosoft has addressed your problem
Search newsgroups (http://groups.google.com/groups) tosee if someone else has solved your problem
And of course, you can always check
http://excelworkshop.com to see if I've solved the problem!
If something still seems too difficult, examine your approach Igenerally go fishing in that situation and come back to the
problem later If you don't live somewhere with good fishing, Iguess you're just stuck
Excel Versions
This book was developed with Excel 2003 Professional Editionand is designed to be compatible with Excel 2000 and later If afeature is not available in Excel 2000, I make an effort to notethat, but if you are developing for a specific version of Excel,please check Appendix B for specific version compatibility andread Chapter 6 for information on developing design
Trang 17If you are developing with NET, I strongly recommend that youtarget Excel 2003 or later The code shown in this book is
written in the Visual Basic Applications Edition, but parallel NETsamples are provided online (see the next section)
chapter uses one main workbook (ch01.xls, ch02.xls, etc.) as a
starting point to provide instructions and navigation
What's in This Book
Chapters in this book are organized by programming task Icover the most common tasks for each subject within a chapter.Subjects usually correspond to one or more Excel objects, and Iinclude important reference information for those objects withineach chapter, rather than pushing that information to the back
of the book
I don't expect this book will be your only resource, and I try not to duplicate stuff you already have (like online Help), so I include cross- references to other sources I've also included those resources as hyperlinks in the sample workbooks (see the Resources sheet) Mostly, those links deal with much more specific issues related to the topic, but they also include links to toolkits and other software you may need.
Trang 18Chapter 1, Becoming an Excel Programmer, is meant for
those new to Excel programming It covers how to record,change, run, and debug code in the Excel Visual Basic
Editor Experienced Excel programmers can skip this
chapter, although they may want to read the section "WriteBug-Free Code."
Chapter 2, Knowing the Basics, explains the parts of a
program: classes, modules, procedures, properties, events,variables, constants, and all the other programming
fundamentals Experienced programmers might want toskip right to "Objects" and "Exceptions" in this chapter
Chapter 3, Tasks in Visual Basic, teaches how to use core
Visual Basic features to display simple dialog boxes,
perform calculations, work with text, read and write files,check results, and run other applications Experienced
a particular task
Chapter 5, Creating Your Own Objects, goes in-depth about
object-oriented programming (OOP) You'll learn how toconstruct classes, methods, properties, collections, and
events I also explain why it is important to destroy your
Trang 19Chapter 6, Writing Code for Use by Others, is about taking
your skills to the next level I cover the types of applicationsyou can create, explain the development process, and showhow to properly deploy a completed application
Chapter 7, Controlling Excel, begins the task-specific part of
this book It shows how to use the top-level Application
object to open and close Excel windows, display dialogs,and get references to other Excel objects
Chapter 8, Opening, Saving, and Sharing Workbooks,
teaches you how to work with Excel document files
(workbooks) As a bonus, I cover how to work with XML anduse SharePoint workspaces from Excel
Chapter 11, Printing and Publishing, is about sending output
to the printer or the Web I show how to control paging,change printer settings, filter output, preview results, andpublish ranges to a web page
Chapter 12, Loading and Manipulating Data, is all about
connecting to databases I show how to use Query Tablesand use the ADO and DAO object models
Trang 20program with one of Excel's most celebrated features I
show how to reorganize data from a wide variety of datasources, including OLAP data cubes
Chapter 14, Sharing Data Using Lists, goes into detail on
one of Excel's newest features: data lists I show how touse them to sort, filter, and even share lists across the
network through SharePoint
Chapter 15, Working with XML, is also a ground-breaker, by
showing how to convert XML datafiles into Excel workbooksand vice versa I provide a brief introduction to XML andXSL, then dive to the heart of how to import XML data tolists through XML maps
Chapter 16, Charting, covers how to create different types
of charts and control the main parts of a chart Charting is alarge and complex topic in Excel, so I also include a roadmap to the chart objects
Chapter 17, Formatting Charts, explains how to control the
fonts, backgrounds, and 3-D effects used on a chart It isthe companion to Chapter 16
Chapter 18, Drawing Graphics, is really just for fun Excel's
drawing tools let you create diagrams and other graphicsfrom data, but you need to know about a couple gotchas Icover those here
Chapter 19, Adding Menus and Toolbars, helps you hook
your application into the Excel user interface I also showhow to distribute the menus and toolbars with your code
Chapter 20, Building Dialog Boxes, is about creating data
Trang 21users I cover the controls included in the Microsoft Formslibraries here
Chapter 21, Sending and Receiving Workbooks, shows all
the ways to send email from Excel
Chapter 22, Building Add-Ins, covers how to create and
distribute your program as an Excel Add-In This chapterbegins the advanced programming material
Chapter 23, Integrating DLLs and COM, shows how to use
code from Windows itself or other applications within yourExcel programs
Chapter 24, Getting Data From the Web, explains how to
scrape data from web pages using web queries and how toexecute web services to perform tasks remotely across anetwork
Chapter 25, Programming Excel with NET, teaches how to
use NET code from within Excel, use Excel code from NET,
or integrate between Excel and NET using Visual StudioTools for Office (VSTO)
Chapter 26, Exploring Security in Depth, discusses Windows
security, encryption, passwords, protection, and InformationRights Management (IRM) within Excel I also show howwell (or poorly) certain security features perform
Font Conventions
This book follows certain conventions for font usage
Understanding these conventions up front makes it easier touse this book
Trang 22Pathnames, filenames, program names, compilers, options,and commands
New terms where they are defined
Internet addresses, such as domain names and URLs
Constant width is used for:
Anything that appears literally in a Visual Basic program,including keywords, data types, constants, method names,variables, class names, and interface names
Trang 23This icon designates a note, which is an important aside to the nearby text.
This icon designates a warning relating to the nearby text.
Syntax Conventions
Books about computer languages require a way to express thekinds of information you need to provide on one or more lines
as you type That is called the syntax of the language and
Backus-Naur Form (BNF) is the format used in this book andmost others In BNF notation, the following conventions apply:
Trang 24Using Code Examples
This book is here to help you get your job done In general, youmay use the code in this book in your programs and
documentation You do not need to contact us for permissionunless you're reproducing a significant portion of the code Forexample, writing a program that uses several chunks of codefrom this book does not require permission Selling or
distributing a CD-ROM of examples from O'Reilly books does
require permission Answering a question by citing this bookand quoting example code does not require permission
Incorporating a significant amount of example code from this
book into your product's documentation does require
permission
We appreciate, but do not require, attribution An attributionusually includes the title, author, publisher, and ISBN For
example: "Programming Excel with VBA and NET, by Jeff Webb
596-00766-3."
and Steve Saunders Copyright 2006 O'Reilly Media, Inc., 0-If you feel your use of code examples falls outside fair use orthe permission given above, feel free to contact us at
permissions@oreilly.com
Safari® Enabled
Trang 25Safari offers a solution that's better than e-books It's a virtuallibrary that lets you easily search thousands of top tech books,cut and paste code samples, download chapters, and find quickanswers when you need the most accurate, current information.Try it for free at http://safari.oreilly.com
How to Contact Us
Please address comments and questions concerning this book tothe publisher:
http://www.oreilly.com/catalog/progexcel/
To comment or ask technical questions about this book, sendemail to:
bookquestions@oreilly.com
For more information about our books, conferences, ResourceCenters, and the O'Reilly Network, see our web site at:
Trang 26Acknowledgments
It takes a long time and a great deal of help to write a book thisbig I would like to thank Steve Saunders for joining the effortand contributing Chapters 9 and 12 Steve and I go back a verylong way, through years at Microsoft and Digital Equipment
Corp Steve's an Access expert and a great writer, and he singswell, too
I'd also like to thank Simon St.Laurent for his work throughoutthe project We've done four books together nowthat's close to
2000 pages Finishing this together is like climbing a mountain:his company improved the ascent and it's great to stand withhim here at the summit Nice view
Trang 27
These chapters teach you how to write professional-quality code using Excel Visual Basic (VBA) This is morethan an entry-level tutorial to a macro language: it's a fullset of lessons for readers who are serious about
programming Once you've finished these chapters, you'll
be ready to program Excel, Word, or any other applicationthat exposes objects to Visual Basic
Trang 28Programmer
How do you become an excellent Excel programmer? The firststep for most folks is to buy a book I'm glad you bought thisone Next, you've got to learn the programming tools that Excelprovides Visual Basic is ideally suited as a learning tool
because it lets you get started without a lot of pedagogical
preparation That's an alliterative way of saying that you canlearn the rules as you go
So let's go!
Code used in this chapter and additional samples are available in
ch01.xls.
Trang 29
Excel is a mature product with every imaginable featuredoesn't
it do everything it needs to already? Excel is amazingly
complete, but programming Excel isn't really about adding newfeatures as much as it is about combining existing features tosolve specific problems
because they are great at performing repetitive operations andfollowing a logical path without getting tired or bored Theymake things more reliable because they slavishly follow yourdirections and never, ever get creative
Having such a devoted servant comes with a lot of
responsibility, however For instance, if you tell Excel to "lather,rinse, repeat" like it says on the back of a shampoo bottle, it'sliable to scrub the hair right off your head since you never told
it when to stop repeating (Hint: if that ever happens to you,press Ctrl-Break and step out of the shower.)
You need to understand the basic rules common to all
programming languages before you can write real programs inExcel (see Chapter 2) That's kind of dry stuff, though, so rightnow I'm going to jump ahead to something more fun
Trang 30
Figure 1-1 An example for recording code
Trang 33'
Trang 34Range("A1:C16").Select '< Following lines record what you did
Selection.AutoFormat Format:=xlRangeAutoFormatSimple, Number:=True, Font _ :=True, Alignment:=True, Border:=True, Pattern:=True, Width:=True
End Sub '< - End of procedure
Figure 1-5 Step 5
Trang 35Each procedure in a workbook has a unique name Excelassigns the names Macro1, Macro2, and so on to recordedcode
scrolling
Procedures always include an End statement to tell VisualBasic where to stop
So now that you've recorded code, what can you do with it?That's up next
Trang 36
Recorded code is a great way to learn, but it's not really a
program Real programs are much more flexible, and recordedcode always has the following limitations:
Follows a linear path
Excel can't infer logic from the user's actionseven if the userrepeats an action, Excel only records the action twice Itdoesn't know how to record "repeat until end" or "do thistask if " Excel can "replace all" and perform other globalactions, but that's still linear logic
Actions apply to the active item
Excel bases recorded actions on whatever worksheet,
range, or chart is currently selected by the user If you wantyour code to work with other sheets or ranges, you need toeither change the active selection or add object referencesthat tell the code which items to work with
Uses cell addresses
For example, Range("A1:C16") Although Excel keeps
references on worksheets up-to-date, Excel can't updateaddresses in code That means if your data is moved on theworksheet, the code won't work correctly To fix this, useExcel range properties or named ranges instead of
addresses in code
Trang 37Range("A1:C15").Select
Charts.Add
Trang 38ActiveChart.SetSourceData Source:=ws.Range("A1:C15"), PlotBy:= _
xlColumns
ActiveChart.Location Where:=xlLocationAsObject, Name:=ws.Name '"2002" ' Change Name to match the worksheet's name -^
Trang 39cells on the worksheet that contain data The hard part comes